Spaces:
Running
feat: remove AI assistant, Free/Plus plans, user templates API, security fixes
Browse files- Remove built-in AI (AIController, AIService, Gemini bridge, DeepSeek proxy, Node in Docker)
- Plans: only Free (small creation limits) and Plus (no limits); migrate Pro/Ultra to Plus
- New /api/templates for user templates; old built-in TemplateLibrary removed
- Security: auth + ownership checks on nodes/edges/habits/users/sync, remove anonymous
agent token and public user list, PBKDF2 password hashing with legacy upgrade,
CORS restricted to the web client, change-tier requires auth (Plus upgrade gated
by Payments:AllowFreeUpgrade), Stripe webhook disabled until signature check exists
- Hub only relays to connections that joined the board
- Clear stale SQLite lock files before opening the DB, add /api/health
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Files changed (39)
- Dockerfile-9
- FlowAPI.Application/DTOs/AI/AIDtos.csDeleted-44
- FlowAPI.Application/DTOs/Graph/GraphDtos.cs-10
- FlowAPI.Application/DTOs/Template/TemplateDtos.csAdded+36
- FlowAPI.Application/DTOs/User/UserDtos.cs-3
- FlowAPI.Application/Interfaces/IAIService.csDeleted-12
- FlowAPI.Application/Interfaces/ICustomTemplateRepository.cs+3
- FlowAPI.Application/Interfaces/IGeminiBridgeManager.csDeleted-9
- FlowAPI.Application/Interfaces/IGraphService.cs-3
- FlowAPI.Application/Interfaces/ITemplateService.csAdded+16
- FlowAPI.Application/Services/AIService.csDeleted-940
- FlowAPI.Application/Services/GeminiBridgeManager.csDeleted-203
- FlowAPI.Application/Services/GraphService.cs+13-180
- FlowAPI.Application/Services/HabitService.cs+3-6
- FlowAPI.Application/Services/Plans.csAdded+30
- FlowAPI.Application/Services/TemplateLibrary.csDeleted-353
- FlowAPI.Application/Services/TemplateService.csAdded+126
- FlowAPI.Application/Services/UserService.cs+43-10
- FlowAPI.Infrastructure/Migrations/20261017120000_MergeTiersIntoPlus.csAdded+28
- FlowAPI.Infrastructure/Repositories/CustomTemplateRepository.cs+21
- FlowAPI/Controllers/AIController.csDeleted-77
- FlowAPI/Controllers/AchievementsController.cs-1
- FlowAPI/Controllers/AgentCanvasController.cs-32
- FlowAPI/Controllers/EdgesController.cs+28-6
- FlowAPI/Controllers/GraphsController.cs-51
- FlowAPI/Controllers/HabitsController.cs+13-6
- FlowAPI/Controllers/HealthController.csAdded+15
- FlowAPI/Controllers/PaymentsController.cs+41-31
- FlowAPI/Controllers/SyncController.cs+2
- FlowAPI/Controllers/TaskNodesController.cs+38-11
- FlowAPI/Controllers/TemplatesController.csAdded+78
- FlowAPI/Controllers/UsersController.cs+22-9
- FlowAPI/FlowAPI.csproj-6
- FlowAPI/FreeDeepseekAPI/package.jsonDeleted-6
- FlowAPI/FreeDeepseekAPI/server.jsDeleted-1400
- FlowAPI/Hubs/BoardHub.cs+14-8
- FlowAPI/Program.cs+36-86
- FlowAPI/appsettings.json-7
- FlowAPI/gemini_bridge.pyDeleted-473
23 unmodified lines242526272829303132333435363738394023 unmodified lines# Create persistent data directory for SQLiteRUN mkdir -p /data/data# Install Node.js 20RUN apt-get update && apt-get install -y curl && \curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \apt-get install -y nodejs && \rm -rf /var/lib/apt/lists/*# Copy published .NET appCOPY --from=build /app/publish .# Copy FreeDeepseekAPI proxyCOPY FlowAPI/FreeDeepseekAPI ./FreeDeepseekAPI# Set entrypointENTRYPOINT ["dotnet", "FlowAPI.dll"]23 unmodified lines242526272829303123 unmodified lines# Create persistent data directory for SQLiteRUN mkdir -p /data/data# Copy published .NET appCOPY --from=build /app/publish .# Set entrypointENTRYPOINT ["dotnet", "FlowAPI.dll"]
1234567891011121314151617181920212223242526272829303132333435363738394041424344using FlowAPI.Application.DTOs.TaskNode;using FlowAPI.Application.DTOs.Edge;using FlowAPI.Application.DTOs.Graph;
namespace FlowAPI.Application.DTOs.AI{ public class GenerateAlternativeRequestDto { public Guid GraphId { get; set; } public Guid FailedNodeId { get; set; } }
public class AIPathResponseDto { public List<TaskNodeResponseDto> SuggestedNodes { get; set; } = new(); public List<EdgeResponseDto> SuggestedEdges { get; set; } = new(); }
public class GenerateGoalGraphRequestDto { public Guid UserId { get; set; } public string Goal { get; set; } = string.Empty; }
public class AIChatMessageDto { public string Role { get; set; } = string.Empty; // "user" or "model" public string Text { get; set; } = string.Empty; }
public class AICanvasAssistRequestDto { public Guid GraphId { get; set; } public string UserPrompt { get; set; } = string.Empty; public List<AIChatMessageDto> History { get; set; } = new(); }
public class AICanvasAssistResponseDto { public string Explanation { get; set; } = string.Empty; public List<NodeDto> NewNodes { get; set; } = new(); public List<EdgeDto> NewEdges { get; set; } = new(); }}47 unmodified lines4849505152535455565758596061626347 unmodified lines{public string Title { get; set; } = string.Empty;public string? Description { get; set; }public string? TemplateKey { get; set; }}public class TemplateInfoDto{public string Key { get; set; } = string.Empty;public string Title { get; set; } = string.Empty;public string Description { get; set; } = string.Empty;public string Icon { get; set; } = string.Empty;public string Category { get; set; } = string.Empty;}public class UpdateGraphDto47 unmodified lines48495051525347 unmodified lines{public string Title { get; set; } = string.Empty;public string? Description { get; set; }}public class UpdateGraphDto
123456789101112131415161718192021222324252627282930313233343536using System;
namespace FlowAPI.Application.DTOs.Template{ /// <summary> /// A user template. Content is an opaque JSON document produced by the web client: /// { "version": 2, "nodes": [...], "edges": [...] } in React Flow format. /// </summary> public class TemplateDto { public Guid Id { get; set; } public string Title { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public string Category { get; set; } = string.Empty; public string Icon { get; set; } = string.Empty; public string Content { get; set; } = string.Empty; public DateTime CreatedAt { get; set; } }
public class CreateTemplateDto { public string Title { get; set; } = string.Empty; public string? Description { get; set; } public string? Category { get; set; } public string? Icon { get; set; } public string Content { get; set; } = string.Empty; }
public class UpdateTemplateDto { public string? Title { get; set; } public string? Description { get; set; } public string? Category { get; set; } public string? Icon { get; set; } }}9 unmodified lines1011121314151617181911 unmodified lines313233343536379 unmodified linespublic class UpdateUserDto{public string? DisplayName { get; set; }public bool? IsPremium { get; set; }public string? AvatarUrl { get; set; }public string? Password { get; set; }public string? SubscriptionTier { get; set; }}public class LoginDto11 unmodified linespublic string? AvatarUrl { get; set; }public DateTime CreatedAt { get; set; }public string SubscriptionTier { get; set; } = "Free";public int DailyAiGenerationsCount { get; set; }}public class AuthResponseDto9 unmodified lines101112131415161711 unmodified lines2930313233349 unmodified linespublic class UpdateUserDto{public string? DisplayName { get; set; }public string? AvatarUrl { get; set; }public string? Password { get; set; }}public class LoginDto11 unmodified linespublic string? AvatarUrl { get; set; }public DateTime CreatedAt { get; set; }public string SubscriptionTier { get; set; } = "Free";}public class AuthResponseDto
123456789101112using FlowAPI.Application.DTOs.AI;using FlowAPI.Application.DTOs.Graph;
namespace FlowAPI.Application.Interfaces{ public interface IAIService { Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request); Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request); Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request); }}9 unmodified lines10111213149 unmodified linesTask<CustomTemplate?> GetByIdAsync(Guid id);Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId);Task<CustomTemplate> CreateAsync(CustomTemplate template);}}9 unmodified lines10111213141516179 unmodified linesTask<CustomTemplate?> GetByIdAsync(Guid id);Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId);Task<CustomTemplate> CreateAsync(CustomTemplate template);Task<CustomTemplate> UpdateAsync(CustomTemplate template);Task<bool> DeleteAsync(Guid id);Task<int> CountByUserIdAsync(Guid userId);}}
123456789using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface IGeminiBridgeManager { Task<string> SendPromptAsync(string prompt, bool isNewChat, int timeoutSeconds = 120); }}14 unmodified lines151617181920212214 unmodified linesTask<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto);Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId);Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId);Task<FlowAPI.Domain.Entities.CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description);Task<IEnumerable<FlowAPI.Domain.Entities.CustomTemplate>> GetCustomTemplatesAsync(Guid userId);}}14 unmodified lines151617181914 unmodified linesTask<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto);Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId);Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId);}}
12345678910111213141516using FlowAPI.Application.DTOs.Template;using System;using System.Collections.Generic;using System.Threading.Tasks;
namespace FlowAPI.Application.Interfaces{ public interface ITemplateService { Task<IEnumerable<TemplateDto>> GetMineAsync(Guid userId); Task<TemplateDto?> GetAsync(Guid id, Guid userId); Task<TemplateDto> CreateAsync(CreateTemplateDto dto, Guid userId); Task<TemplateDto?> UpdateAsync(Guid id, UpdateTemplateDto dto, Guid userId); Task<bool> DeleteAsync(Guid id, Guid userId); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Text;using System.Text.Json;using System.Text.Encodings.Web;using System.Text.Unicode;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Net.Http;using FlowAPI.Application.DTOs.AI;using FlowAPI.Application.DTOs.Graph;using FlowAPI.Application.DTOs.TaskNode;using FlowAPI.Application.DTOs.Edge;using FlowAPI.Application.Interfaces;using Microsoft.Extensions.Configuration;
namespace FlowAPI.Application.Services{ public class AIService : IAIService { private readonly IUserRepository _userRepo; private readonly IGraphRepository _graphRepo; private readonly IConfiguration _config; private readonly IGraphService _graphService; private readonly IGeminiBridgeManager _bridgeManager;
private const string GoalResponseSchema = @"{ ""type"": ""object"", ""properties"": { ""title"": { ""type"": ""string"" }, ""description"": { ""type"": ""string"" }, ""explanation"": { ""type"": ""string"" }, ""nodes"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""id"": { ""type"": ""string"" }, ""label"": { ""type"": ""string"" }, ""description"": { ""type"": ""string"" }, ""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] }, ""decision"": { ""type"": ""string"" }, ""dependsOn"": { ""type"": ""string"" }, ""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] } }, ""required"": [""id"", ""label"", ""description"", ""type""] } }, ""edges"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""from"": { ""type"": ""string"" }, ""to"": { ""type"": ""string"" }, ""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] }, ""condition"": { ""type"": ""string"" } }, ""required"": [""from"", ""to"", ""relationship""] } } }, ""required"": [""title"", ""description"", ""explanation"", ""nodes"", ""edges""]}";
private const string AssistResponseSchema = @"{ ""type"": ""object"", ""properties"": { ""explanation"": { ""type"": ""string"" }, ""newNodes"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""id"": { ""type"": ""string"" }, ""label"": { ""type"": ""string"" }, ""description"": { ""type"": ""string"" }, ""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] }, ""decision"": { ""type"": ""string"" }, ""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] } }, ""required"": [""id"", ""label"", ""description"", ""type""] } }, ""newEdges"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""from"": { ""type"": ""string"" }, ""to"": { ""type"": ""string"" }, ""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] }, ""condition"": { ""type"": ""string"" } }, ""required"": [""from"", ""to"", ""relationship""] } } }, ""required"": [""explanation"", ""newNodes"", ""newEdges""]}";
public AIService(IUserRepository userRepo, IGraphRepository graphRepo, IConfiguration config, IGraphService graphService, IGeminiBridgeManager bridgeManager) { _userRepo = userRepo; _graphRepo = graphRepo; _config = config; _graphService = graphService; _bridgeManager = bridgeManager; }
private async Task<string> CallGeminiApiAsync(string prompt, string? systemInstruction = null, string? responseSchemaJson = null) { var parts = new[] { new { text = prompt } }; var contents = new[] { new { parts = parts } }; return await CallGeminiApiAsync(contents, systemInstruction, responseSchemaJson); }
private async Task<string> CallGeminiApiAsync(object[] contents, string? systemInstruction = null, string? responseSchemaJson = null) { var deepseekToken = Environment.GetEnvironmentVariable("DEEPSEEK_TOKEN"); var deepseekCookie = Environment.GetEnvironmentVariable("DEEPSEEK_COOKIE"); if (!string.IsNullOrEmpty(deepseekToken) && !string.IsNullOrEmpty(deepseekCookie)) { return await CallDeepSeekProxyApiAsync(contents, systemInstruction, responseSchemaJson); }
var apiKey = _config["Gemini:ApiKey"] ?? Environment.GetEnvironmentVariable("GEMINI_API_KEY"); if (string.IsNullOrEmpty(apiKey)) { throw new Exception("Gemini API key is not configured. Please add Gemini:ApiKey to appsettings.json or set GEMINI_API_KEY environment variable."); }
var model = _config["Gemini:Model"] ?? "gemini-2.5-flash"; if (string.IsNullOrWhiteSpace(model) || model.StartsWith("AIzaSy", StringComparison.OrdinalIgnoreCase) || model.StartsWith("AQ.Ab", StringComparison.OrdinalIgnoreCase) || model.Length > 30 || !model.Contains("gemini", StringComparison.OrdinalIgnoreCase)) { model = "gemini-2.5-flash"; }
if (model.StartsWith("models/")) { model = model.Substring("models/".Length); } var url = $"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={apiKey}";
object? generationConfig = null; if (responseSchemaJson != null) { generationConfig = new { responseMimeType = "application/json", responseSchema = JsonSerializer.Deserialize<object>(responseSchemaJson) }; } else { generationConfig = new { responseMimeType = "application/json" }; }
object requestBody; if (!string.IsNullOrEmpty(systemInstruction)) { requestBody = new { contents = contents, systemInstruction = new { parts = new[] { new { text = systemInstruction } } }, generationConfig = generationConfig }; } else { requestBody = new { contents = contents, generationConfig = generationConfig }; }
using var httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromSeconds(5); var jsonPayload = JsonSerializer.Serialize(requestBody); HttpResponseMessage? response = null; string responseString = string.Empty; int maxRetries = 3; int delayMs = 1500; // 1.5s base delay for (int attempt = 1; attempt <= maxRetries; attempt++) { using var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); response = await httpClient.PostAsync(url, content); responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { break; } int statusCode = (int)response.StatusCode; if (attempt < maxRetries && (statusCode == 503 || statusCode == 429 || statusCode == 500)) { await Task.Delay(delayMs * attempt); continue; } throw new Exception($"Gemini API error (Status {response.StatusCode}): {responseString}"); }
using var doc = JsonDocument.Parse(responseString); var textResponse = doc.RootElement .GetProperty("candidates")[0] .GetProperty("content") .GetProperty("parts")[0] .GetProperty("text") .GetString();
if (string.IsNullOrEmpty(textResponse)) { throw new Exception("Empty response received from Gemini API."); }
return textResponse; }
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request) { var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId); if (graph == null) { throw new Exception("Graph not found."); } await CheckAndIncrementAiGenerationsLimitAsync(graph.UserId);
var failedNode = graph.Nodes.FirstOrDefault(n => n.Id == request.FailedNodeId); if (failedNode == null) { throw new Exception("Target node not found."); }
var prompt = $"В нашей дорожной карте произошел сбой на шаге: \"{failedNode.Label}\" (Описание: \"{failedNode.Description}\").\n" + $"Предложи альтернативный обходной путь из 2-3 шагов, чтобы пользователь мог ��родолжить движение к цели.\n" + $"Предоставь только новые шаги (NewNodes) и новые связи (NewEdges) для их интеграции.";
var systemInstruction = "You are a Roadmap Strategist AI Agent. You design failover alternative paths for failed tasks in a roadmap."; var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, AssistResponseSchema); responseJson = CleanJson(responseJson);
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options) ?? throw new Exception("Failed to deserialize AI alternative path response from Gemini.");
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase); idMap[failedNode.Id.ToString()] = failedNode.Id;
foreach (var node in rawAssist.NewNodes) { if (!idMap.ContainsKey(node.Id)) { idMap[node.Id] = Guid.NewGuid(); } }
var mappedNodes = rawAssist.NewNodes.Select(node => new TaskNodeResponseDto { Id = idMap[node.Id], Label = node.Label, PosX = failedNode.PosX + 300, PosY = failedNode.PosY + 150, State = FlowAPI.Domain.Enums.NodeState.Pending, CreatedAt = DateTime.UtcNow }).ToList();
var mappedEdges = new List<EdgeResponseDto>(); foreach (var edge in rawAssist.NewEdges) { if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid)) { mappedEdges.Add(new EdgeResponseDto { Id = Guid.NewGuid(), FromNodeId = fromGuid, ToNodeId = toGuid, Condition = edge.Relationship == "subgoal" ? "subgoals-source-right" : "True" }); } }
return new AIPathResponseDto { SuggestedNodes = mappedNodes, SuggestedEdges = mappedEdges }; }
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request) { await CheckAndIncrementAiGenerationsLimitAsync(request.UserId);
if (string.IsNullOrWhiteSpace(request.Goal)) { throw new ArgumentException("Goal description cannot be empty."); }
// 1. Build prompt for Gemini var prompt = $"������������ ����� ������� ��������� ����: \"{request.Goal}\". " + "������� ��������� ������������� �������� �����.\n" + "������� ���������� ������ � ��������� (�������������, ����������� � ������������������):\n" + "- � ��� ���� ��� ���� ������:\n" + " 1. 'relationship': 'sequential' � ���������������� ���� / ����. ������������ ��� �������� ���������, ��������� ����� ������� ������ ������ ����������, � ����� ��� ���������� ����� ������ ������� ������������ ���� � ������. ��������� ���� ��� ��� �����, ������� ������ �������������� ������� ���� �� ����� (��������: ����������� ���� -> �������� ����� -> ������ ����).\n" + " 2. 'relationship': 'subgoal' � ������������ � �������. ������������ ��� ���������� ������� ���� �� ������ ������ �����.\n" + "- ������� ����������� ������������:\n" + " * ����� ������� ���� �� ����� ������ ����� ���� ���������������. ���� ������� �������, ������ � �� � ����������� ������� (subgoals) � ���������������� ����.\n" + " * �� ������������� ����� ������� ��������. ������� �������� ������ (��������: ������� ���� -> ������� A -> ������� A.1 -> ������� A.1.1) � ��� ��������� � ��������������.\n" + "- ��� ��������� ������� ������������ � ��������-������������ ����� (����������):\n" + " * �� ����� ��� ��������� �������������! ���� ���� ������ ������� ������ ����������� ������ ���� �� ������ (���� ��������������� �����������), �� ������ ������� ������������ ���� ������ 'subgoal' ������ � ����� ������ ����� �������. ��� ����������� ���� ���� ������� �������� ��������������� ���� � ������ ����� 'sequential'.\n" + " * ��������� ��������� ����� �������� � �������� ����� 'subgoal' (�����������) ������ ���� ��� ������ ���������� ���� �� ����� � �� ����� ������ ������������ ��� � ����� ������� (��������: ���� ingredients � ���������� ������).\n" + " * �� ��������� ������������ �������� ��� ���������������� �����. ������� �� ����������������� ������ / ������. ������� ��������� / ����������� ������ �������� ������������.\n" + "- ���������� ������ �������� �����:\n" + " * ���� ���� ������� (��������, �������� ���, ������ ������), ������� ���������� ����� �� 3-5 �����.\n" + " * ���� ���� ������� (������� �����, �������� ����������������), ���������� ����������� ����� �� 8-15+ �����, ������������ ��� ������ ���� � �� ���������.\n" + "- ������� ��� ����� ����� (����������):\n" + " * 'sketch' � ����������� ���/���� (��������� � 99% �������). ����� ������� �������� ���, ���� ���� �� �������� ��������, ����� �������� (��������, '�������� 30 �����', '��������� 1 ���') ��� �������� ��������, ������ ����� ��� 'sketch'!\n" + " * 'habit' (��������) � ��������� ������ ������ ���� ������������ ����� ������ ���������� ����������, ���������/����������� ������������� �������� ��� ������������ �������� (��������, '������ ���� ���� ����'). ������� �� ��������� ��� ��� ������� ����� ��������!\n" + " * 'condition' (�������) � ��������� ������ ������ ��� ����� ���������� ���������, �������� � ������ (��������, '���� X, �� Y, ����� Z'). ������� �� ��������� ��� ��� ������� ����� � ���������� ����������, ���� ��� ��������� ����!\n" + "������� ���� ��� �������� �������� �������� (label) � ��������� �������� (description).\n" + "� ���� 'explanation' ������ �����, ������, ����������� � ������������� ����� �� ���� ����������� ������-��������. ������� � ������������� �� ������� ������������ �����, ��� ���������� ���������. ������� ����� ������ ������������ �����, ������ ������������ ����� ����������� �����������, � ������ ���������������, � ��� ������ ������������ ������ �� ���������� ����.";
// 2. Call Gemini API var systemInstruction = "You are a warm, friendly, and highly professional Roadmap Strategist AI Agent. You design roadmaps represented as graphs (nodes and edges). You break down complex goals into hierarchical, deeply nested subgoals (recursive subgoals, where subgoals can have their own subgoals). You connect a parent to multiple parallel subgoals using 'subgoal' relationship ONLY if they can be done in parallel or in any order. If subgoals have chronological dependencies, connect the parent to the first subgoal in the sequence using 'subgoal' and chain the remaining subgoals using 'sequential' relationship. Node types MUST follow these rules: 'sketch' for 99% of regular tasks (including tasks with durations/wait times); 'habit' ONLY for repeating daily/weekly actions meant to form a routine, if explicitly requested; 'condition' ONLY for logical forks/branches with conditions. You adapt the graph size: 3-5 nodes for simple goals, 8-15+ nodes for complex goals. In the 'explanation' field, you write in a warm, direct, and conversational human tone, explaining the plan's logic and giving practical advice."; var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, GoalResponseSchema); responseJson = CleanJson(responseJson);
// 3. Deserialize response var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var rawGraph = JsonSerializer.Deserialize<GeminiGoalResponse>(responseJson, options) ?? throw new Exception("Failed to deserialize generated roadmap graph from Gemini.");
// 4. Create the Graph record in the database first var createDto = new CreateGraphDto { Title = string.IsNullOrWhiteSpace(rawGraph.Title) ? request.Goal : rawGraph.Title, Description = string.IsNullOrWhiteSpace(rawGraph.Description) ? "Дорожная карта, сгенерированная AI Агентом" : rawGraph.Description }; var graphResponse = await _graphService.CreateAsync(createDto, request.UserId); var graphId = graphResponse.Id;
// 5. Map Gemini string IDs to GUIDs var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase); foreach (var node in rawGraph.Nodes) { if (!idMap.ContainsKey(node.Id)) { idMap[node.Id] = Guid.NewGuid(); } }
// 6. Construct DTO lists var mappedNodes = rawGraph.Nodes.Select(node => new NodeDto { Id = idMap[node.Id], Label = node.Label, PosX = 0, PosY = 0, Type = node.Type ?? "sketch", State = 0, // Pending Decision = node.Decision, Description = node.Description, Color = node.Color ?? "default", IsPinned = false }).ToList();
var mappedEdges = new List<EdgeDto>(); foreach (var edge in rawGraph.Edges) { if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid)) { mappedEdges.Add(new EdgeDto { Id = Guid.NewGuid(), FromNodeId = fromGuid, ToNodeId = toGuid, Condition = edge.Relationship == "subgoal" ? "subgoals-source-right" : (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition) }); } }
// 7. Calculate layouts ApplyBeautifulLayout(mappedNodes, mappedEdges);
// 8. Save fully generated graph to DB var fullGraphDto = new FullGraphResponseDto { Id = graphId, UserId = request.UserId, Title = createDto.Title, Description = createDto.Description, CreatedAt = DateTime.UtcNow, Nodes = mappedNodes, Edges = mappedEdges };
await _graphService.SaveFullGraphAsync(graphId, fullGraphDto, request.UserId);
// 9. Update roadmap description with explanation from strategist var graphEntity = await _graphRepo.GetByIdAsync(graphId); if (graphEntity != null) { graphEntity.Description = rawGraph.Explanation; await _graphRepo.UpdateAsync(graphEntity); fullGraphDto.Description = rawGraph.Explanation; }
return fullGraphDto; }
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request) { var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId); if (graph == null) { throw new Exception("Graph not found."); } await CheckAndIncrementAiGenerationsLimitAsync(graph.UserId);
// 1. Serialize existing nodes and edges for Gemini context var existingNodesText = new StringBuilder(); existingNodesText.AppendLine("Текущие узлы на доске:"); foreach (var node in graph.Nodes) { existingNodesText.AppendLine($"- ID: \"{node.Id}\", Название: \"{node.Label}\", Тип: \"{node.Type}\", Состояние: \"{node.State}\", Описание: \"{node.Description}\""); }
var existingEdgesText = new StringBuilder(); existingEdgesText.AppendLine("Текущие связи на доске:"); foreach (var edge in graph.Edges) { existingEdgesText.AppendLine($"- От: \"{edge.FromNodeId}\", К: \"{edge.ToNodeId}\", Условие: \"{edge.Condition}\""); }
// 2. Build the prompt var prompt = $"������������ ���������� � ���� (������-��������) �� ��������� ���������� ��� ��������:\n" + $"������ ������������: \"{request.UserPrompt}\"\n\n" + $"{existingNodesText}\n" + $"{existingEdgesText}\n\n" + "���� ������:\n" + "1. ���� ������ ������������ ������� ���������� ����� ���������, ����������� ��� ���������� �����: ���������� ����� ���� (NewNodes) � ����� ����� (NewEdges). ��� ���� ������ ������ �������� ���������� ������:\n" + " - � ��� ���� ��� ���� ������:\n" + " * 'relationship': 'sequential' � ���������������� ���� / ����. ������������ ��� �������� ���������, ��������� ����� ������� ������ ������ ����������, � ����� ��� ���������� ����� ������ ������� ������������ ���� � ������. ��������� ���� ��� ��� �����, ������� ������ �������������� ������� ���� �� ����� (��������: ����������� ���� -> �������� ����� -> ������ ����).\n" + " * 'relationship': 'subgoal' � ������������ � �������. ������������ ��� ���������� ������� ���� �� ������ ������ �����.\n" + " - ������� ����������� ������������:\n" + " * ����� ���� �� ����� ������ ����� ���� ���������������! ���� ������� ���� �� ���� �������, �� ������ ������� � �� � ����������� ������� (subgoals) � ���������������� ����.\n" + " * �� ������������� ����� ������� ��������. ������� �������� ������ (��������: ������� ���� -> ������� A -> ������� A.1 -> ������� A.1.1) � ��� ��������� � ��������������.\n" + " - ��� ��������� ������� ������������ � ��������-������������ ����� (����������):\n" + " * �� ����� ��� ��������� �������������! ���� ���� ������ ������� ������ ����������� ������ ���� �� ������ (���� ��������������� �����������), �� ������ ������� ������������ ���� ������ 'subgoal' ������ � ����� ������ ����� �������. ��� ����������� ���� ���� ������� �������� ��������������� ���� � ������ ����� 'sequential'.\n" + " * ��������� ��������� ����� �������� � �������� ����� 'subgoal' (�����������) ������ ���� ��� ������ ���������� ���� �� ����� � �� ����� ������ ������������ ��� � ����� �������.\n" + " * �� ��������� ������������ �������� ��� ���������������� �����. ������� �� ����������������� ������ / ������. ������� ��������� / ����������� ������ �������� ������������.\n" + " - ���������� ������ ����������:\n" + " * ���� ������������ ������ �������� ������� �������� ��� ������ ���������, ������ 1-3 ����.\n" + " * ���� ������������ ������ ��������� ��� ��������� ������� ����, ������ �����������, ������� � ��������� ���� �� 5-12 �����.\n" + " - ������� ��� ����� ����� (����������):\n" + " * 'sketch' � ����������� ���/���� (��������� � 99% �������). ����� ������� �������� ���, ���� ���� �� �������� ��������, ����� �������� (��������, '�������� 30 �����', '��������� 1 ���') ��� �������� ��������, ������ ����� ��� 'sketch'!\n" + " * 'habit' (��������) � ��������� ������ ������ ���� ������������ ����� ������ ���������� ����������, ���������/����������� ������������� �������� ��� ������������ �������� (��������, '������ ���� ���� ����'). ������� �� ��������� ��� ��� ������� ����� ��������!\n" + " * 'condition' (�������) � ��������� ������ ������ ��� ����� ���������� ���������, �������� � ������ (��������, '���� X, �� Y, ����� Z'). ������� �� ��������� ��� ��� ������� ����� � ���������� ����������, ���� ��� ��������� ����!\n" + " - �������� ����� ���� � ������������� ��� ���� � ������ � ������� ���������� ��������� ID (��������, new_step_1).\n" + "2. ���� ������ ������������ �� ������� ���������� ���������: ������ ������ 'NewNodes' � 'NewEdges' ������� ( [] ).\n" + "3. � ���� 'explanation' ������ ������������, ������, ����� � ����������� ����� �� ���� ��������-����������. ������ �� ������� ������������, ����� ������ ��������� ��������� ��� ������� ������ ������������ ����� �� ������� ������������ �����.";
var systemInstruction = "You are a warm, friendly, and highly professional Roadmap Strategist AI Agent. You interact with the user, answer their questions, and help them design, extend, or analyze their roadmaps. If changes are needed, you return the new nodes and edges, breaking down complex tasks into hierarchical, deeply nested subgoals (recursive subgoals, where subgoals can have their own subgoals). You connect a parent to multiple parallel subgoals using 'subgoal' relationship ONLY if they can be done in parallel or in any order. If subgoals have chronological dependencies, connect the parent to the first subgoal in the sequence using 'subgoal' and chain the remaining subgoals using 'sequential' relationship. Node types MUST follow these rules: 'sketch' for 99% of regular tasks (including tasks with durations/wait times); 'habit' ONLY for repeating daily/weekly actions meant to form a routine, if explicitly requested; 'condition' ONLY for logical forks/branches with conditions. You never connect subgoals directly to unrelated nodes without a parent node. In the 'explanation' field, you write in a warm, direct, and conversational human tone, explaining your changes or answering user questions."; var contentsList = new List<object>(); if (request.History != null) { foreach (var msg in request.History) { var role = msg.Role == "user" ? "user" : "model"; if (!string.IsNullOrWhiteSpace(msg.Text)) { contentsList.Add(new { role = role, parts = new[] { new { text = msg.Text } } }); } } }
// Add the current user prompt (contains graph context + query) contentsList.Add(new { role = "user", parts = new[] { new { text = prompt } } });
var responseJson = await CallGeminiApiAsync(contentsList.ToArray(), systemInstruction, AssistResponseSchema); responseJson = CleanJson(responseJson);
// 3. Deserialize Gemini response var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options) ?? throw new Exception("Failed to deserialize AI Assist response from Gemini.");
// 4. Map string IDs to Guids var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase); // Map existing node Guids to themselves so they remain stable foreach (var node in graph.Nodes) { idMap[node.Id.ToString()] = node.Id; }
// Generate new Guids for new node IDs foreach (var node in rawAssist.NewNodes) { if (!idMap.ContainsKey(node.Id)) { idMap[node.Id] = Guid.NewGuid(); } }
// 5. Construct DTO nodes list var mappedNewNodes = rawAssist.NewNodes.Select(node => new NodeDto { Id = idMap[node.Id], Label = node.Label, PosX = 0, PosY = 0, Type = node.Type ?? "sketch", State = 0, // Pending Decision = node.Decision, Description = node.Description, Color = node.Color ?? "default", IsPinned = false }).ToList();
// 6. Construct DTO edges list var mappedNewEdges = new List<EdgeDto>(); foreach (var edge in rawAssist.NewEdges) { if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid)) { mappedNewEdges.Add(new EdgeDto { Id = Guid.NewGuid(), FromNodeId = fromGuid, ToNodeId = toGuid, Condition = edge.Relationship == "subgoal" ? "subgoals-source-right" : (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition) }); } }
// 7. Positioning/Layout: // Find max PosY of existing nodes to place the new ones below double maxPosY = 100; if (graph.Nodes.Count > 0) { maxPosY = graph.Nodes.Max(n => n.PosY); }
// Run layout engine on the new nodes/edges ApplyBeautifulLayout(mappedNewNodes, mappedNewEdges);
// Shift all new nodes below the existing nodes double shiftY = maxPosY + 250; foreach (var node in mappedNewNodes) { node.PosY += shiftY; }
return new AICanvasAssistResponseDto { Explanation = rawAssist.Explanation, NewNodes = mappedNewNodes, NewEdges = mappedNewEdges }; }
private string CleanJson(string text) { text = text.Trim(); if (text.StartsWith("```")) { var lines = text.Split('\n'); var cleanLines = lines.Where(line => !line.Trim().StartsWith("```")).ToArray(); text = string.Join("\n", cleanLines).Trim(); } return text; }
private void ApplyBeautifulLayout(List<NodeDto> nodes, List<EdgeDto> edges) { if (nodes == null || nodes.Count == 0) return;
var inDegree = new Dictionary<Guid, int>(); var adj = new Dictionary<Guid, List<Guid>>(); foreach (var node in nodes) { inDegree[node.Id] = 0; adj[node.Id] = new List<Guid>(); }
foreach (var edge in edges) { if (inDegree.ContainsKey(edge.ToNodeId) && inDegree.ContainsKey(edge.FromNodeId)) { inDegree[edge.ToNodeId]++; adj[edge.FromNodeId].Add(edge.ToNodeId); } }
var layers = new Dictionary<Guid, int>(); foreach (var node in nodes) { layers[node.Id] = 0; }
var queue = new Queue<Guid>(); foreach (var node in nodes) { if (inDegree[node.Id] == 0) { queue.Enqueue(node.Id); } }
if (queue.Count == 0 && nodes.Count > 0) { queue.Enqueue(nodes[0].Id); }
var processed = new HashSet<Guid>(); while (queue.Count > 0) { var curr = queue.Dequeue(); processed.Add(curr);
int currentLayer = layers[curr]; foreach (var neighbor in adj[curr]) { layers[neighbor] = Math.Max(layers[neighbor], currentLayer + 1); if (!processed.Contains(neighbor) && !queue.Contains(neighbor)) { queue.Enqueue(neighbor); } } }
var nodesByLayer = new Dictionary<int, List<NodeDto>>(); foreach (var node in nodes) { int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0; if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List<NodeDto>(); } nodesByLayer[layer].Add(node); }
double marginY = 100; double spacingY = 220; double spacingX = 350; double centerX = 450;
var sortedLayers = nodesByLayer.Keys.OrderBy(l => l).ToList(); foreach (var layer in sortedLayers) { var layerNodes = nodesByLayer[layer]; int count = layerNodes.Count; for (int i = 0; i < count; i++) { var node = layerNodes[i]; node.PosY = marginY + layer * spacingY; node.PosX = centerX + (i - (count - 1) / 2.0) * spacingX; } } }
private void ApplyBeautifulLayout(List<FlowAPI.Domain.Entities.TaskNode> nodes, List<FlowAPI.Domain.Entities.Edge> edges) { if (nodes == null || nodes.Count == 0) return;
var inDegree = new Dictionary<Guid, int>(); var adj = new Dictionary<Guid, List<Guid>>(); foreach (var node in nodes) { inDegree[node.Id] = 0; adj[node.Id] = new List<Guid>(); }
foreach (var edge in edges) { if (inDegree.ContainsKey(edge.ToNodeId) && inDegree.ContainsKey(edge.FromNodeId)) { inDegree[edge.ToNodeId]++; adj[edge.FromNodeId].Add(edge.ToNodeId); } }
var layers = new Dictionary<Guid, int>(); foreach (var node in nodes) { layers[node.Id] = 0; }
var queue = new Queue<Guid>(); foreach (var node in nodes) { if (inDegree[node.Id] == 0) { queue.Enqueue(node.Id); } }
if (queue.Count == 0 && nodes.Count > 0) { queue.Enqueue(nodes[0].Id); }
var processed = new HashSet<Guid>(); while (queue.Count > 0) { var curr = queue.Dequeue(); processed.Add(curr);
int currentLayer = layers[curr]; foreach (var neighbor in adj[curr]) { layers[neighbor] = Math.Max(layers[neighbor], currentLayer + 1); if (!processed.Contains(neighbor) && !queue.Contains(neighbor)) { queue.Enqueue(neighbor); } } }
var nodesByLayer = new Dictionary<int, List<FlowAPI.Domain.Entities.TaskNode>>(); foreach (var node in nodes) { int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0; if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List<FlowAPI.Domain.Entities.TaskNode>(); } nodesByLayer[layer].Add(node); }
double marginY = 100; double spacingY = 220; double spacingX = 350; double centerX = 450;
var sortedLayers = nodesByLayer.Keys.OrderBy(l => l).ToList(); foreach (var layer in sortedLayers) { var layerNodes = nodesByLayer[layer]; int count = layerNodes.Count; for (int i = 0; i < count; i++) { var node = layerNodes[i]; node.PosY = marginY + layer * spacingY; node.PosX = centerX + (i - (count - 1) / 2.0) * spacingX; } } }
private class GeminiNode { public string Id { get; set; } = string.Empty; public string Label { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public string Type { get; set; } = "sketch"; public string? Decision { get; set; } public string? DependsOn { get; set; } public string? Color { get; set; } }
private class GeminiEdge { public string From { get; set; } = string.Empty; public string To { get; set; } = string.Empty; public string Relationship { get; set; } = "sequential"; public string? Condition { get; set; } }
private class GeminiGoalResponse { public string Title { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public string Explanation { get; set; } = string.Empty; public List<GeminiNode> Nodes { get; set; } = new(); public List<GeminiEdge> Edges { get; set; } = new(); }
private class GeminiAssistResponse { public string Explanation { get; set; } = string.Empty; public List<GeminiNode> NewNodes { get; set; } = new(); public List<GeminiEdge> NewEdges { get; set; } = new(); }
private async Task<string> CallDeepSeekProxyApiAsync(object[] contents, string? systemInstruction = null, string? responseSchemaJson = null) { var messages = new List<object>(); if (responseSchemaJson != null) { var schemaInstructions = $"\n\n[STRICT REQUIREMENT] You MUST respond ONLY with a JSON object that strictly adheres to the following JSON schema:\n{responseSchemaJson}\nDo not wrap the JSON in markdown code blocks like ```json ... ```, just output the raw JSON text."; if (!string.IsNullOrEmpty(systemInstruction)) { systemInstruction += schemaInstructions; } else { systemInstruction = schemaInstructions; } }
if (!string.IsNullOrEmpty(systemInstruction)) { messages.Add(new { role = "system", content = systemInstruction }); }
foreach (var content in contents) { try { var json = JsonSerializer.Serialize(content); using var doc = JsonDocument.Parse(json); var root = doc.RootElement; string role = "user"; if (root.TryGetProperty("role", out var roleProp)) { var rStr = roleProp.GetString(); role = rStr == "model" ? "assistant" : (rStr == "system" ? "system" : "user"); } string text = string.Empty; if (root.TryGetProperty("parts", out var partsProp) && partsProp.ValueKind == JsonValueKind.Array && partsProp.GetArrayLength() > 0) { var firstPart = partsProp[0]; if (firstPart.TryGetProperty("text", out var textProp)) { text = textProp.GetString() ?? string.Empty; } } if (!string.IsNullOrEmpty(text)) { messages.Add(new { role = role, content = text }); } } catch (Exception ex) { Console.WriteLine($"[DeepSeekProxy] Error mapping message: {ex.Message}"); } }
var requestBody = new { model = "deepseek-chat", messages = messages, stream = false };
using var httpClient = new HttpClient(); httpClient.Timeout = TimeSpan.FromMinutes(5); var jsonPayload = JsonSerializer.Serialize(requestBody); using var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); HttpResponseMessage? response = null; string responseString = string.Empty; int maxRetries = 3; int delayMs = 1500; for (int attempt = 1; attempt <= maxRetries; attempt++) { response = await httpClient.PostAsync("http://localhost:9655/v1/chat/completions", requestContent); responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { break; } int statusCode = (int)response.StatusCode; if (attempt < maxRetries && (statusCode == 503 || statusCode == 429 || statusCode == 500 || statusCode == 502)) { await Task.Delay(delayMs * attempt); continue; } throw new Exception($"DeepSeek Proxy API error (Status {response.StatusCode}): {responseString}"); }
using var resDoc = JsonDocument.Parse(responseString); var textResponse = resDoc.RootElement .GetProperty("choices")[0] .GetProperty("message") .GetProperty("content") .GetString();
if (string.IsNullOrEmpty(textResponse)) { throw new Exception("Empty response received from DeepSeek Proxy API."); }
return textResponse; }
private async Task CheckAndIncrementAiGenerationsLimitAsync(Guid userId) { var user = await _userRepo.GetByIdAsync(userId); if (user == null) throw new Exception("User not found.");
var today = DateTime.UtcNow.Date; if (user.LastAiGenerationDate.Date != today) { user.DailyAiGenerationsCount = 0; user.LastAiGenerationDate = DateTime.UtcNow; }
int limit = user.SubscriptionTier switch { "Free" => 3, "Pro" => 200, "Ultra" => int.MaxValue, _ => 3 };
if (user.DailyAiGenerationsCount >= limit) { throw new InvalidOperationException($"Daily AI generation limit reached for your tier ({limit} generations per day)."); }
user.DailyAiGenerationsCount++; await _userRepo.UpdateAsync(user); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203using System;using System.Diagnostics;using System.IO;using System.Text.Json;using System.Text.Encodings.Web;using System.Text.Unicode;using System.Threading;using System.Threading.Tasks;using FlowAPI.Application.Interfaces;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;
namespace FlowAPI.Application.Services{ public class GeminiBridgeManager : IGeminiBridgeManager, IDisposable { private readonly ILogger<GeminiBridgeManager> _logger; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); private Process? _process; private bool _isReady = false; private readonly JsonSerializerOptions _serializeOptions;
public GeminiBridgeManager(ILogger<GeminiBridgeManager> logger, IHostApplicationLifetime appLifetime) { _logger = logger; _serializeOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) };
appLifetime.ApplicationStopping.Register(() => { _logger.LogInformation("Application stopping, closing Gemini Bridge."); Dispose(); }); }
private async Task EnsureProcessStartedAsync() { if (_process != null && !_process.HasExited && _isReady) return;
_logger.LogInformation("Starting persistent Gemini Bridge process...");
string scriptPath = Path.Combine(AppContext.BaseDirectory, "gemini_bridge.py"); if (!File.Exists(scriptPath)) { scriptPath = Path.Combine(Directory.GetCurrentDirectory(), "gemini_bridge.py"); } if (!File.Exists(scriptPath)) { scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "gemini_bridge.py"); }
if (!File.Exists(scriptPath)) { throw new FileNotFoundException("Could not locate gemini_bridge.py in application folders."); }
var startInfo = new ProcessStartInfo { FileName = "python", Arguments = $"\"{scriptPath}\" --headless", RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(scriptPath) };
_process = new Process { StartInfo = startInfo }; _process.Start();
// Fire and forget error logging _ = Task.Run(async () => { while (_process != null && !_process.HasExited && !_process.StandardError.EndOfStream) { var errLine = await _process.StandardError.ReadLineAsync(); if (!string.IsNullOrEmpty(errLine)) { _logger.LogWarning($"[GeminiBridge Python]: {errLine}"); } } });
// Wait for bridge to declare itself "ready" var readyTimeout = Task.Delay(TimeSpan.FromSeconds(45)); var readReadyTask = Task.Run(async () => { while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream) { var l = await _process.StandardOutput.ReadLineAsync(); if (l != null && l.Contains("\"type\": \"ready\"")) { return true; } } return false; });
var completedTask = await Task.WhenAny(readReadyTask, readyTimeout); if (completedTask == readyTimeout || !await readReadyTask) { try { _process.Kill(); } catch { } _process = null; throw new Exception("Timeout or failure waiting for persistent Gemini Browser Bridge to initialize."); }
_isReady = true; _logger.LogInformation("Persistent Gemini Bridge initialized successfully."); }
public async Task<string> SendPromptAsync(string promptText, bool isNewChat, int timeoutSeconds = 120) { await _semaphore.WaitAsync(); try { await EnsureProcessStartedAsync();
if (_process == null || _process.HasExited) throw new Exception("Gemini Bridge process is not running.");
var promptObj = new { type = "prompt", id = Guid.NewGuid().ToString(), new_chat = isNewChat, content = promptText };
string promptRequestJson = JsonSerializer.Serialize(promptObj, _serializeOptions);
// Send Prompt to standard input await _process.StandardInput.WriteLineAsync(promptRequestJson); await _process.StandardInput.FlushAsync();
// Await Gemini final response var responseTimeout = Task.Delay(TimeSpan.FromSeconds(timeoutSeconds)); var readResponseTask = Task.Run(async () => { while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream) { var l = await _process.StandardOutput.ReadLineAsync(); if (l != null && l.Contains("\"type\": \"response\"") && l.Contains($"\"id\": \"{promptObj.id}\"")) { return l; } } return null; });
var responseCompletedTask = await Task.WhenAny(readResponseTask, responseTimeout); if (responseCompletedTask == responseTimeout) { // If timeout occurs, we should probably kill the process to avoid desync try { _process.Kill(); } catch { } _process = null; _isReady = false; throw new Exception("Timeout waiting for AI response from Gemini Bridge."); }
string? rawResponseJson = await readResponseTask;
if (string.IsNullOrEmpty(rawResponseJson)) { throw new Exception("Did not receive a valid response block from the Gemini Bridge."); }
return rawResponseJson; } finally { _semaphore.Release(); } }
public void Dispose() { if (_process != null) { try { if (!_process.HasExited) { _process.StandardInput.WriteLine("{\"type\": \"exit\"}"); _process.StandardInput.Flush(); Thread.Sleep(500); // Give it a moment to exit gracefully if (!_process.HasExited) { _process.Kill(); } } } catch { } _process.Dispose(); _process = null; } _semaphore.Dispose(); } }}16 unmodified lines171819202122231 unmodified line25262728293031321 unmodified line34353637383940108 unmodified lines1491501511521531541551561571581591601611621636 unmodified lines17017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025162 unmodified lines3143153163173183193203213223233243253263273283293301 unmodified line33233333433533633769 unmodified lines40740840941041141241341441541641741841942042142277 unmodified lines50050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757816 unmodified linesprivate readonly IAchievementService _achievementService;private readonly ISharedGraphRepository _sharedGraphRepo;private readonly IUserRepository _userRepo;private readonly ICustomTemplateRepository _customTemplateRepo;public GraphService(IGraphRepository repo,1 unmodified lineIEdgeRepository edgeRepo,IAchievementService achievementService,ISharedGraphRepository sharedGraphRepo,IUserRepository userRepo,ICustomTemplateRepository customTemplateRepo){_repo = repo;_nodeRepo = nodeRepo;1 unmodified line_achievementService = achievementService;_sharedGraphRepo = sharedGraphRepo;_userRepo = userRepo;_customTemplateRepo = customTemplateRepo;}public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)108 unmodified linesvar user = await _userRepo.GetByIdAsync(currentUserId);if (user == null) throw new Exception("User not found.");var tier = user.SubscriptionTier?.Trim();bool isFree = string.IsNullOrEmpty(tier) || tier == "Free";if (isFree){var ownedGraphsCount = (await _repo.GetAllByUserIdAsync(currentUserId)).Count();if (ownedGraphsCount >= 3){throw new InvalidOperationException("Free tier is limited to 3 canvases.");}}6 unmodified linesCreatedAt = DateTime.UtcNow};if (!string.IsNullOrEmpty(dto.TemplateKey)){// Try to load system template firstvar (nodes, edges) = TemplateLibrary.GetTemplateContent(dto.TemplateKey, graph.Id);// If not found in system templates, check custom templates in DBif (nodes.Count == 0 && Guid.TryParse(dto.TemplateKey, out var customTemplateId)){var customTemplate = await _customTemplateRepo.GetByIdAsync(customTemplateId);if (customTemplate != null && (customTemplate.UserId == currentUserId || user.SubscriptionTier == "Ultra")){try{var data = JsonSerializer.Deserialize<CustomTemplateContentDto>(customTemplate.ContentJson);if (data != null){var idMapping = new Dictionary<Guid, Guid>();foreach (var nodeDto in data.Nodes){var newId = Guid.NewGuid();idMapping[nodeDto.Id] = newId;var node = new TaskNode{Id = newId,GraphId = graph.Id,Label = nodeDto.Label,PosX = nodeDto.PosX,PosY = nodeDto.PosY,Type = nodeDto.Type,State = FlowAPI.Domain.Enums.NodeState.Pending,CreatedAt = DateTime.UtcNow,Description = nodeDto.Description,Color = nodeDto.Color,IsPinned = nodeDto.IsPinned,Width = nodeDto.Width,Height = nodeDto.Height,Data = nodeDto.Data,Decision = nodeDto.Decision};nodes.Add(node);}foreach (var edgeDto in data.Edges){if (idMapping.TryGetValue(edgeDto.FromNodeId, out var fromId) &&idMapping.TryGetValue(edgeDto.ToNodeId, out var toId)){edges.Add(new Edge{Id = Guid.NewGuid(),GraphId = graph.Id,FromNodeId = fromId,ToNodeId = toId,Condition = edgeDto.Condition});}}}}catch (Exception ex){System.Console.WriteLine($"[GraphService] Failed to load custom template: {ex.Message}");}}}if (nodes.Count > 0){graph.Nodes = nodes;graph.Edges = edges;if (string.IsNullOrEmpty(dto.Description) || dto.Description == "New strategy path..."){graph.Description = $"Побудовано за шаблоном";}}}var created = await _repo.CreateAsync(graph);await _achievementService.ProcessEventAsync(currentUserId, "GraphCreated");62 unmodified linesvar user = await _userRepo.GetByIdAsync(currentUserId);if (user == null) throw new Exception("User not found.");var tier = user.SubscriptionTier?.Trim();bool isFree = string.IsNullOrEmpty(tier) || tier == "Free";if (isFree){if (dto.Nodes.Count > 200){throw new InvalidOperationException("Free tier is limited to 200 nodes per canvas.");}}// Secure: only allowed for owner or shared users with Edit permissionif (graph.UserId != currentUserId){1 unmodified lineif (shared is null || shared.Permission != "Edit") return false;}// Map DTOs to Domain Entitiesvar mappedNodes = dto.Nodes.Select(nodeDto => new TaskNode{69 unmodified linesvar shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);int currentSharedCount = shares?.Count() ?? 0;var ownerTier = owner.SubscriptionTier?.Trim();bool ownerIsFree = string.IsNullOrEmpty(ownerTier) || ownerTier == "Free";if (ownerIsFree && currentSharedCount >= 1){throw new InvalidOperationException("Free tier is limited to 2 people on a board (1 guest).");}else if (ownerTier == "Pro" && currentSharedCount >= 9){throw new InvalidOperationException("Pro tier is limited to 10 people on a board (9 guests).");}var share = new SharedGraph77 unmodified linesDescription = graph.Description,CreatedAt = graph.CreatedAt};public async Task<CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description){var user = await _userRepo.GetByIdAsync(userId);if (user == null) throw new Exception("User not found.");if (user.SubscriptionTier != "Ultra"){throw new InvalidOperationException("Creating custom templates is an Ultra tier feature.");}var graph = await _repo.GetByIdWithDetailsAsync(graphId);if (graph == null || graph.UserId != userId){throw new Exception("Graph not found or you are not the owner.");}// Map nodes and edges to DTOs for serializationvar nodes = graph.Nodes.Select(n => new NodeDto{Id = n.Id,Label = n.Label,PosX = n.PosX,PosY = n.PosY,Type = n.Type,State = (int)n.State,Decision = n.Decision,Description = n.Description,Color = n.Color,IsPinned = n.IsPinned,Width = n.Width,Height = n.Height,Data = n.Data}).ToList();var edges = graph.Edges.Select(e => new EdgeDto{Id = e.Id,FromNodeId = e.FromNodeId,ToNodeId = e.ToNodeId,Condition = e.Condition}).ToList();var contentJson = JsonSerializer.Serialize(new CustomTemplateContentDto{Nodes = nodes,Edges = edges});var template = new CustomTemplate{Id = Guid.NewGuid(),UserId = userId,Title = title,Description = description,Category = "Custom",Icon = "BookOpen",ContentJson = contentJson,CreatedAt = DateTime.UtcNow};return await _customTemplateRepo.CreateAsync(template);}public async Task<IEnumerable<CustomTemplate>> GetCustomTemplatesAsync(Guid userId){return await _customTemplateRepo.GetByUserIdAsync(userId);}private class CustomTemplateContentDto{public List<NodeDto> Nodes { get; set; } = new();public List<EdgeDto> Edges { get; set; } = new();}}}16 unmodified lines1718192021221 unmodified line242526272829301 unmodified line323334353637108 unmodified lines1461471481491501511521531541551561576 unmodified lines16416516616716816962 unmodified lines2322332342352362371 unmodified line23924024124224324424524624724824925025169 unmodified lines32132232332432532632732832977 unmodified lines40740840941041116 unmodified linesprivate readonly IAchievementService _achievementService;private readonly ISharedGraphRepository _sharedGraphRepo;private readonly IUserRepository _userRepo;public GraphService(IGraphRepository repo,1 unmodified lineIEdgeRepository edgeRepo,IAchievementService achievementService,ISharedGraphRepository sharedGraphRepo,IUserRepository userRepo){_repo = repo;_nodeRepo = nodeRepo;1 unmodified line_achievementService = achievementService;_sharedGraphRepo = sharedGraphRepo;_userRepo = userRepo;}public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)108 unmodified linesvar user = await _userRepo.GetByIdAsync(currentUserId);if (user == null) throw new Exception("User not found.");if (!Plans.IsPlus(user)){var ownedGraphsCount = (await _repo.GetAllByUserIdAsync(currentUserId)).Count();if (ownedGraphsCount >= Plans.FreeMaxBoards){throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxBoards} boards. Upgrade to Plus for unlimited boards.");}}6 unmodified linesCreatedAt = DateTime.UtcNow};var created = await _repo.CreateAsync(graph);await _achievementService.ProcessEventAsync(currentUserId, "GraphCreated");62 unmodified linesvar user = await _userRepo.GetByIdAsync(currentUserId);if (user == null) throw new Exception("User not found.");// Secure: only allowed for owner or shared users with Edit permissionif (graph.UserId != currentUserId){1 unmodified lineif (shared is null || shared.Permission != "Edit") return false;}// Limits are bound to the board owner's plan, not to the editor'svar owner = graph.UserId == currentUserId ? user : await _userRepo.GetByIdAsync(graph.UserId);if (owner != null && !Plans.IsPlus(owner) && dto.Nodes.Count > Plans.FreeMaxNodesPerBoard){throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxNodesPerBoard} nodes per board. Upgrade to Plus for unlimited nodes.");}// Map DTOs to Domain Entitiesvar mappedNodes = dto.Nodes.Select(nodeDto => new TaskNode{69 unmodified linesvar shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);int currentSharedCount = shares?.Count() ?? 0;if (!Plans.IsPlus(owner) && currentSharedCount >= Plans.FreeMaxGuestsPerBoard){throw new InvalidOperationException($"Free plan allows up to {Plans.FreeMaxGuestsPerBoard} guests per board. Upgrade to Plus for unlimited collaborators.");}var share = new SharedGraph77 unmodified linesDescription = graph.Description,CreatedAt = graph.CreatedAt};}}
31 unmodified lines323334353637383940414243444546474831 unmodified linesvar existing = await _repo.GetRecordForDateAsync(dto.UserId, dto.HabitName, targetDate.Date);if (existing is not null) return MapToDto(existing);var tier = user.SubscriptionTier?.Trim();bool isFree = string.IsNullOrEmpty(tier) || tier == "Free";if (isFree){var allRecords = await _repo.GetAllByUserIdAsync(dto.UserId);var distinctHabits = allRecords.Select(r => r.HabitName).Distinct().ToList();if (!distinctHabits.Contains(dto.HabitName) && distinctHabits.Count >= 3){throw new InvalidOperationException("Free tier is limited to 3 habits.");}}31 unmodified lines323334353637383940414243444531 unmodified linesvar existing = await _repo.GetRecordForDateAsync(dto.UserId, dto.HabitName, targetDate.Date);if (existing is not null) return MapToDto(existing);if (!Plans.IsPlus(user)){var allRecords = await _repo.GetAllByUserIdAsync(dto.UserId);var distinctHabits = allRecords.Select(r => r.HabitName).Distinct().ToList();if (!distinctHabits.Contains(dto.HabitName) && distinctHabits.Count >= Plans.FreeMaxHabits){throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxHabits} habits.");}}
123456789101112131415161718192021222324252627282930using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Services{ /// <summary> /// Subscription plans. There are only two: Free (small creation limits) and Plus (no limits). /// Legacy values ("Pro", "Ultra") are treated as Plus. /// </summary> public static class Plans { public const string Free = "Free"; public const string Plus = "Plus";
public const int FreeMaxBoards = 5; public const int FreeMaxNodesPerBoard = 300; public const int FreeMaxGuestsPerBoard = 2; public const int FreeMaxTemplates = 3; public const int FreeMaxHabits = 3;
public static string Normalize(string? tier) => string.IsNullOrWhiteSpace(tier) || tier.Trim().Equals(Free, System.StringComparison.OrdinalIgnoreCase) ? Free : Plus;
public static bool IsValid(string? tier) => tier != null && (tier.Trim() == Free || tier.Trim() == Plus);
public static bool IsPlus(User user) => Normalize(user.SubscriptionTier) == Plus; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353using System;using System.Collections.Generic;using FlowAPI.Application.DTOs.Graph;using FlowAPI.Domain.Entities;using FlowAPI.Domain.Enums;
namespace FlowAPI.Application.Services{ public static class TemplateLibrary { private class TemplateNodeDef { public string TempId { get; set; } = string.Empty; public string Label { get; set; } = string.Empty; public double PosX { get; set; } public double PosY { get; set; } public string Type { get; set; } = "sketch"; public string Color { get; set; } = "white"; public string Description { get; set; } = string.Empty; public string DecisionJson { get; set; } = string.Empty; public double? Width { get; set; } public double? Height { get; set; } }
private class TemplateEdgeDef { public string FromTempId { get; set; } = string.Empty; public string ToTempId { get; set; } = string.Empty; public string Condition { get; set; } = "True"; }
private class TemplateDef { public string Key { get; set; } = string.Empty; public string Title { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public string Icon { get; set; } = string.Empty; public string Category { get; set; } = string.Empty; public List<TemplateNodeDef> Nodes { get; set; } = new(); public List<TemplateEdgeDef> Edges { get; set; } = new(); }
private static readonly Dictionary<string, TemplateDef> Templates = new() { { "startup", new TemplateDef { Key = "startup", Title = "Запуск Стартапу", Description = "Шлях від формулювання ціннісної пропозиції та CustDev до запуску MVP та перших 100 користувачів.", Icon = "Rocket", Category = "Business", Nodes = new List<TemplateNodeDef> { new() { TempId = "vprop", Label = "Формулювання ціннісної пропозиції", PosX = 250, PosY = 50, Color = "purple", Description = "Чітко опишіть, яку проблему вирішує ваш продукт і для кого." }, new() { TempId = "custdev", Label = "CustDev: Інтерв'ю з клієнтами", PosX = 250, PosY = 170, Color = "blue", Description = "Проведіть принаймні 10 інтерв'ю з потенційними користувачами." }, new() { TempId = "fit", Label = "Чи підтверджено проблему?", PosX = 250, PosY = 290, Type = "condition", DecisionJson = "{\"options\":[{\"id\":\"opt-yes\",\"label\":\"Так (Є інтерес)\"},{\"id\":\"opt-no\",\"label\":\"Ні (Потрібен півот)\"}],\"selected\":[],\"multiSelect\":false}" }, new() { TempId = "mvp", Label = "Розробка MVP", PosX = 100, PosY = 420, Color = "green", Description = "Створіть мінімально життєздатний продукт з однією ключовою функцією." }, new() { TempId = "pivot", Label = "Півот ідеї", PosX = 400, PosY = 420, Color = "orange", Description = "Змініть напрямок або цільову аудиторію на основі фідбеку з інтерв'ю." }, new() { TempId = "landing", Label = "Лендинг та збір заявок", PosX = 100, PosY = 550, Color = "pink", Description = "Налаштуйте просту сторінку для збору контактів зацікавлених клієнтів." }, new() { TempId = "users", Label = "Залучення перших 100 користувачів", PosX = 100, PosY = 680, Color = "yellow", Description = "Використовуйте безкоштовні канали (соцмережі, профільні форуми, зв'язки)." } }, Edges = new List<TemplateEdgeDef> { new() { FromTempId = "vprop", ToTempId = "custdev" }, new() { FromTempId = "custdev", ToTempId = "fit" }, new() { FromTempId = "fit", ToTempId = "mvp", Condition = "True" }, new() { FromTempId = "fit", ToTempId = "pivot", Condition = "False" }, new() { FromTempId = "pivot", ToTempId = "vprop" }, new() { FromTempId = "mvp", ToTempId = "landing" }, new() { FromTempId = "landing", ToTempId = "users" } } } }, { "software", new TemplateDef { Key = "software", Title = "Розробка ПЗ (Web App)", Description = "Стандартний життєвий цикл розробки веб-додатку: вимоги, дизайн, UI/UX, API, інтеграція та реліз.", Icon = "Code", Category = "Development", Nodes = new List<TemplateNodeDef> { new() { TempId = "req", Label = "Збір та аналіз вимог", PosX = 250, PosY = 50, Color = "blue", Description = "Опишіть функціонал проекту та підготуйте ТЗ." }, new() { TempId = "arch", Label = "Архітектура та проектування БД", PosX = 250, PosY = 170, Color = "purple", Description = "Спроектуйте схему бази даних та виберіть стек технологій." }, new() { TempId = "uiux", Label = "UI/UX макети та дизайн", PosX = 100, PosY = 300, Color = "pink", Description = "Створіть клікабельний прототип у Figma." }, new() { TempId = "api", Label = "Розробка API та Бекенду", PosX = 400, PosY = 300, Color = "yellow", Description = "Реалізуйте серверу логіку, авторизацію та базу даних." }, new() { TempId = "integ", Label = "Інтеграція та тестування", PosX = 250, PosY = 440, Color = "green", Description = "З'єднайте фронтенд з бекендом та проведіть ручне тестування." }, new() { TempId = "staging", Label = "Деплой на Staging сервер", PosX = 250, PosY = 560, Color = "orange", Description = "Розгорніть тестову версію додатку для фінальної перевірки." }, new() { TempId = "prod", Label = "Реліз у Production та моніторинг", PosX = 250, PosY = 680, Color = "green", Description = "Запустіть додаток для реальних користувачів та підключіть аналітику." } }, Edges = new List<TemplateEdgeDef> { new() { FromTempId = "req", ToTempId = "arch" }, new() { FromTempId = "arch", ToTempId = "uiux" }, new() { FromTempId = "arch", ToTempId = "api" }, new() { FromTempId = "uiux", ToTempId = "integ" }, new() { FromTempId = "api", ToTempId = "integ" }, new() { FromTempId = "integ", ToTempId = "staging" }, new() { FromTempId = "staging", ToTempId = "prod" } } } }, { "language", new TemplateDef { Key = "language", Title = "Вивчення Іноземної Мови", Description = "Методика освоєння мови через щоденні звички, проходження базового курсу та вихід у практику.", Icon = "Languages", Category = "Education", Nodes = new List<TemplateNodeDef> { new() { TempId = "goal", Label = "Визначення цілей та ресурсів", PosX = 250, PosY = 50, Color = "purple", Description = "Оберіть додатки, підручники та поставте чітку ціль (наприклад, рівень B1)." }, new() { TempId = "words", Label = "Вчити 15 нових слів щодня", PosX = 100, PosY = 170, Type = "habit", Color = "blue", Description = "Використовуйте картки Anki або Quizlet для регулярного повторення.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Використовуйте картки Anki або Quizlet для регулярного повторення.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "listen", Label = "Слухати подкаст / дивитись відео", PosX = 400, PosY = 170, Type = "habit", Color = "pink", Description = "Принаймні 20 хвилин фонового або активного слухання щодня.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Принаймні 20 хвилин фонового або активного слухання щодня.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "course", Label = "Завершити курс для початківців", PosX = 250, PosY = 300, Color = "yellow", Description = "Пройти базову граматику та отримати розуміння структури мови." }, new() { TempId = "speak", Label = "Розмовна сесія (1 раз на тиждень)", PosX = 100, PosY = 430, Type = "habit", Color = "green", Description = "Знайдіть партнера для спілкування на Tandem або викладача.", DecisionJson = "{\"resetRule\":{\"type\":\"weekly\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Знайдіть партнера для спілкування на Tandem або викладача.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "read", Label = "Прочитати першу коротку розповідь", PosX = 400, PosY = 430, Color = "orange", Description = "Оберіть адаптовану книгу під ваш поточний рівень." }, new() { TempId = "exam", Label = "Скласти тестовий іспит", PosX = 250, PosY = 560, Color = "green", Description = "Перевірте свій прогрес за допомогою офіційного пробного тесту." } }, Edges = new List<TemplateEdgeDef> { new() { FromTempId = "goal", ToTempId = "words" }, new() { FromTempId = "goal", ToTempId = "listen" }, new() { FromTempId = "words", ToTempId = "course" }, new() { FromTempId = "listen", ToTempId = "course" }, new() { FromTempId = "course", ToTempId = "speak" }, new() { FromTempId = "course", ToTempId = "read" }, new() { FromTempId = "speak", ToTempId = "exam" }, new() { FromTempId = "read", ToTempId = "exam" } } } }, { "fitness", new TemplateDef { Key = "fitness", Title = "Фітнес та Здорове Тіло", Description = "Збалансований план тренувань, контролю харчування та циклічного аналізу результатів.", Icon = "Activity", Category = "Health", Nodes = new List<TemplateNodeDef> { new() { TempId = "setup", Label = "Поставити ціль та розрахувати КБЖВ", PosX = 250, PosY = 50, Color = "blue", Description = "Визначте добову норму калорій залежно від мети (схуднення чи набір маси)." }, new() { TempId = "plan", Label = "Скласти план тренувань та раціон", PosX = 250, PosY = 170, Color = "purple", Description = "Виберіть 3 дні для занять та підготуйте перелік здорових страв." }, new() { TempId = "diet", Label = "Трекати щоденне харчування та воду", PosX = 100, PosY = 300, Type = "habit", Color = "green", Description = "Записуйте все з'їдене в MyFitnessPal та пийте достатньо води.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Записуйте все з'їдене в MyFitnessPal та пийте достатньо води.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "workout", Label = "Силове або кардіо тренування", PosX = 400, PosY = 300, Type = "habit", Color = "orange", Description = "Виконуйте заплановане тренування 3 рази на тиждень.", DecisionJson = "{\"resetRule\":{\"type\":\"weekly\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Виконуйте заплановане тренування 3 рази на тиждень.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "check", Label = "Контрольне зважування та заміри (4 тижні)", PosX = 250, PosY = 430, Color = "yellow", Description = "Порівняйте поточну вагу та об'єми тіла з початковими показниками." }, new() { TempId = "satisfied", Label = "Чи є прогрес задовільним?", PosX = 250, PosY = 550, Type = "condition", DecisionJson = "{\"options\":[{\"id\":\"opt-yes\",\"label\":\"Так (Продовжуємо)\"},{\"id\":\"opt-no\",\"label\":\"Ні (Потрібні коригування)\"}],\"selected\":[],\"multiSelect\":false}" }, new() { TempId = "advance", Label = "Ускладнити програму тренувань", PosX = 100, PosY = 680, Color = "pink", Description = "Додайте вагу на снарядах або збільшіть інтенсивність." }, new() { TempId = "adjust", Label = "Скоригувати КБЖВ та план їжі", PosX = 400, PosY = 680, Color = "yellow", Description = "Зменшіть або збільшіть калорійність раціону на 10%." } }, Edges = new List<TemplateEdgeDef> { new() { FromTempId = "setup", ToTempId = "plan" }, new() { FromTempId = "plan", ToTempId = "diet" }, new() { FromTempId = "plan", ToTempId = "workout" }, new() { FromTempId = "diet", ToTempId = "check" }, new() { FromTempId = "workout", ToTempId = "check" }, new() { FromTempId = "check", ToTempId = "satisfied" }, new() { FromTempId = "satisfied", ToTempId = "advance", Condition = "True" }, new() { FromTempId = "satisfied", ToTempId = "adjust", Condition = "False" }, new() { FromTempId = "adjust", ToTempId = "plan" } } } }, { "gamedev", new TemplateDef { Key = "gamedev", Title = "Створення Інді-Гри", Description = "Повний цикл геймдеву від ідеї та прототипу до створення сторінки в Steam та релізу.", Icon = "Gamepad", Category = "Creative", Nodes = new List<TemplateNodeDef> { new() { TempId = "concept", Label = "Концепт та написання GDD", PosX = 250, PosY = 50, Color = "pink", Description = "Сформулюйте основну ідею гри та опишіть її механіки в дизайн-документі." }, new() { TempId = "proto", Label = "Прототип базового геймплею", PosX = 250, PosY = 170, Color = "purple", Description = "Створіть «сіру коробку» на рушії, щоб перевірити, чи весело грати." }, new() { TempId = "art", Label = "Стилістика та створення артів", PosX = 100, PosY = 300, Color = "orange", Description = "Визначте художній стиль та підготуйте перші 2D/3D моделі." }, new() { TempId = "level", Label = "Дизайн рівнів та звуковий супровід", PosX = 400, PosY = 300, Color = "blue", Description = "Створіть тестовий рівень та додайте базові звукові ефекти." }, new() { TempId = "playable", Label = "Перша грабельна демо-версія", PosX = 250, PosY = 430, Color = "yellow", Description = "Зберіть стабільний білд для тестування друзями." }, new() { TempId = "test", Label = "Плейтести та виправлення багів", PosX = 100, PosY = 560, Type = "habit", Color = "pink", Description = "Щодня грайте, збирайте фідбек та виправляйте помилки.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Щодня грайте, збирайте фідбек та виправляйте помилки.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "steam", Label = "Створення сторінки в Steam", PosX = 400, PosY = 560, Color = "yellow", Description = "Підготуйте красиві скріншоти, трейлер та запустіть сторінку для збору Wishlists." }, new() { TempId = "release", Label = "Реліз гри в Steam", PosX = 250, PosY = 690, Color = "green", Description = "Опублікуйте фінальний білд та підтримайте запуск маркетинговою кампанією." } }, Edges = new List<TemplateEdgeDef> { new() { FromTempId = "concept", ToTempId = "proto" }, new() { FromTempId = "proto", ToTempId = "art" }, new() { FromTempId = "proto", ToTempId = "level" }, new() { FromTempId = "art", ToTempId = "playable" }, new() { FromTempId = "level", ToTempId = "playable" }, new() { FromTempId = "playable", ToTempId = "test" }, new() { FromTempId = "playable", ToTempId = "steam" }, new() { FromTempId = "test", ToTempId = "release" }, new() { FromTempId = "steam", ToTempId = "release" } } } }, { "finance", new TemplateDef { Key = "finance", Title = "Фінансова Свобода", Description = "Покроковий план досягнення фінансової незалежності: облік витрат, подушка безпеки та інвестиції.", Icon = "DollarSign", Category = "Finance", Nodes = new List<TemplateNodeDef> { new() { TempId = "audit", Label = "Аудит активів та боргових зобов'язань", PosX = 250, PosY = 50, Color = "yellow", Description = "Запишіть усі свої збереження, майно та кредити." }, new() { TempId = "track", Label = "Щоденний облік усіх витрат", PosX = 100, PosY = 170, Type = "habit", Color = "blue", Description = "Записуйте кожну покупку в мобільний додаток або Excel таблицю.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Записуйте кожну покупку в мобільний додаток або Excel таблицю.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "emergency", Label = "Сформувати подушку на 3 місяці", PosX = 300, PosY = 170, Color = "orange", Description = "Розрахуйте мінімальний бюджет життя та накопичте цю суму на депозиті." }, new() { TempId = "debt", Label = "Виплатити всі споживчі кредити", PosX = 250, PosY = 290, Color = "pink", Description = "Спрямуйте вільні кошти на швидке закриття боргів з найвищими відсотками." }, new() { TempId = "invest", Label = "Інвестувати 20% від доходу", PosX = 100, PosY = 420, Type = "habit", Color = "green", Description = "Регулярно купуйте надійні індекси (ETF) або облігації.", DecisionJson = "{\"resetRule\":{\"type\":\"monthly\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Регулярно купуйте надійні індекси (ETF) або облігації.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "passive", Label = "Створити джерело пасивного доходу", PosX = 400, PosY = 420, Color = "purple", Description = "Створіть власний блог, курс, невеликий онлайн-сервіс чи придбайте дивідендні акції." }, new() { TempId = "freedom", Label = "Досягти фінансової незалежності", PosX = 250, PosY = 550, Color = "green", Description = "Коли пасивний дохід повністю перекриє ваші щомісячні витрати." } }, Edges = new List<TemplateEdgeDef> { new() { FromTempId = "audit", ToTempId = "track" }, new() { FromTempId = "audit", ToTempId = "emergency" }, new() { FromTempId = "track", ToTempId = "debt" }, new() { FromTempId = "emergency", ToTempId = "debt" }, new() { FromTempId = "debt", ToTempId = "invest" }, new() { FromTempId = "debt", ToTempId = "passive" }, new() { FromTempId = "invest", ToTempId = "freedom" }, new() { FromTempId = "passive", ToTempId = "freedom" } } } }, { "writing", new TemplateDef { Key = "writing", Title = "Написання та Публікація Книги", Description = "Шлях автора: від розробки сюжету та персо��ажів до щоденного написання, редактури та релізу.", Icon = "BookOpen", Category = "Creative", Nodes = new List<TemplateNodeDef> { new() { TempId = "outline", Label = "Побудова сюжету та анкет персонажів", PosX = 250, PosY = 50, Color = "pink", Description = "Напишіть синопсис та детально розпишіть структуру розділів книги." }, new() { TempId = "words", Label = "Писати по 1000 слів щодня", PosX = 100, PosY = 170, Type = "habit", Color = "purple", Description = "Формуйте звичку писати без критики та внутрішнього редактора.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Формуйте звичку писати без критики та внутрішнього редактора.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" }, new() { TempId = "draft", Label = "Завершити першу чернетку", PosX = 350, PosY = 170, Color = "yellow", Description = "Напишіть повну історію від початку до кінця (орієнтовно 50-80 тис. слів)." }, new() { TempId = "edit", Label = "Самостійна редактура та вичитка", PosX = 250, PosY = 300, Color = "orange", Description = "Виправте логічні помилки, покращіть діалоги та стиль оповідання." }, new() { TempId = "beta", Label = "Отримати фідбек від бета-рідерів", PosX = 250, PosY = 420, Color = "blue", Description = "Дайте почитати книгу кільком людям із вашої цільової аудиторії." }, new() { TempId = "professional", Label = "Професійна коректура та верстка", PosX = 250, PosY = 540, Color = "pink", Description = "Знайдіть професійного редактора для виправлення граматики та підготовки макету." }, new() { TempId = "cover", Label = "Створення обкладинки та форматування", PosX = 100, PosY = 660, Color = "purple", Description = "Замовте обкладинку в дизайнера та підготуйте формати ePub, PDF." }, new() { TempId = "publish", Label = "Публікація та запуск маркетингу", PosX = 350, PosY = 660, Color = "green", Description = "Опублікуйте книгу на Amazon / Litres та запустіть промо-акції." } }, Edges = new List<TemplateEdgeDef> { new() { FromTempId = "outline", ToTempId = "words" }, new() { FromTempId = "words", ToTempId = "draft" }, new() { FromTempId = "draft", ToTempId = "edit" }, new() { FromTempId = "edit", ToTempId = "beta" }, new() { FromTempId = "beta", ToTempId = "professional" }, new() { FromTempId = "professional", ToTempId = "cover" }, new() { FromTempId = "professional", ToTempId = "publish" } } } } };
public static IEnumerable<TemplateInfoDto> GetTemplateInfos() { var list = new List<TemplateInfoDto>(); foreach (var kv in Templates) { list.Add(new TemplateInfoDto { Key = kv.Value.Key, Title = kv.Value.Title, Description = kv.Value.Description, Icon = kv.Value.Icon, Category = kv.Value.Category }); } return list; }
public static (List<TaskNode> Nodes, List<Edge> Edges) GetTemplateContent(string key, Guid graphId) { if (!Templates.TryGetValue(key.ToLower().Trim(), out var template)) { return (new List<TaskNode>(), new List<Edge>()); }
var nodes = new List<TaskNode>(); var edges = new List<Edge>(); var idMapping = new Dictionary<string, Guid>();
// 1. Instantiate nodes and map their IDs foreach (var nodeDef in template.Nodes) { var newId = Guid.NewGuid(); idMapping[nodeDef.TempId] = newId;
var taskNode = new TaskNode { Id = newId, GraphId = graphId, Label = nodeDef.Label, PosX = nodeDef.PosX, PosY = nodeDef.PosY, Type = nodeDef.Type, State = NodeState.Pending, CreatedAt = DateTime.UtcNow, Description = nodeDef.Description, Color = nodeDef.Color, IsPinned = false, Decision = string.IsNullOrEmpty(nodeDef.DecisionJson) ? null : nodeDef.DecisionJson };
// For normal sketch nodes without custom Decision JSON, populate standard default JSON if (nodeDef.Type == "sketch" && string.IsNullOrEmpty(nodeDef.DecisionJson)) { taskNode.Decision = $"{{\"description\":\"{nodeDef.Description}\",\"progress\":0,\"showProgress\":false,\"decision\":\"bottom\",\"assignees\":[],\"color\":\"{nodeDef.Color}\",\"isPinned\":false,\"tags\":[],\"status\":\"Todo\"}}"; }
nodes.Add(taskNode); }
// 2. Instantiate edges foreach (var edgeDef in template.Edges) { if (idMapping.TryGetValue(edgeDef.FromTempId, out var fromId) && idMapping.TryGetValue(edgeDef.ToTempId, out var toId)) { var edge = new Edge { Id = Guid.NewGuid(), GraphId = graphId, FromNodeId = fromId, ToNodeId = toId, Condition = edgeDef.Condition }; edges.Add(edge); } }
return (nodes, edges); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126using FlowAPI.Application.DTOs.Template;using FlowAPI.Application.Interfaces;using FlowAPI.Domain.Entities;using System;using System.Collections.Generic;using System.Linq;using System.Text.Json;using System.Threading.Tasks;
namespace FlowAPI.Application.Services{ public class TemplateService : ITemplateService { private const int MaxContentLength = 1_500_000; private const int MaxTitleLength = 80; private const int MaxDescriptionLength = 300;
private readonly ICustomTemplateRepository _repo; private readonly IUserRepository _userRepo;
public TemplateService(ICustomTemplateRepository repo, IUserRepository userRepo) { _repo = repo; _userRepo = userRepo; }
public async Task<IEnumerable<TemplateDto>> GetMineAsync(Guid userId) { var templates = await _repo.GetByUserIdAsync(userId); return templates.Select(MapToDto); }
public async Task<TemplateDto?> GetAsync(Guid id, Guid userId) { var template = await _repo.GetByIdAsync(id); if (template is null || template.UserId != userId) return null; return MapToDto(template); }
public async Task<TemplateDto> CreateAsync(CreateTemplateDto dto, Guid userId) { var user = await _userRepo.GetByIdAsync(userId) ?? throw new InvalidOperationException("User not found.");
if (!Plans.IsPlus(user) && await _repo.CountByUserIdAsync(userId) >= Plans.FreeMaxTemplates) { throw new InvalidOperationException($"Free plan allows up to {Plans.FreeMaxTemplates} saved templates. Upgrade to Plus for unlimited templates."); }
var title = (dto.Title ?? string.Empty).Trim(); if (title.Length == 0) throw new InvalidOperationException("Template title is required."); if (title.Length > MaxTitleLength) title = title[..MaxTitleLength];
ValidateContent(dto.Content);
var template = new CustomTemplate { Id = Guid.NewGuid(), UserId = userId, Title = title, Description = Truncate(dto.Description, MaxDescriptionLength), Category = string.IsNullOrWhiteSpace(dto.Category) ? "Мої" : dto.Category.Trim(), Icon = string.IsNullOrWhiteSpace(dto.Icon) ? "LayoutTemplate" : dto.Icon.Trim(), ContentJson = dto.Content, CreatedAt = DateTime.UtcNow };
return MapToDto(await _repo.CreateAsync(template)); }
public async Task<TemplateDto?> UpdateAsync(Guid id, UpdateTemplateDto dto, Guid userId) { var template = await _repo.GetByIdAsync(id); if (template is null || template.UserId != userId) return null;
if (!string.IsNullOrWhiteSpace(dto.Title)) template.Title = Truncate(dto.Title, MaxTitleLength); if (dto.Description != null) template.Description = Truncate(dto.Description, MaxDescriptionLength); if (!string.IsNullOrWhiteSpace(dto.Category)) template.Category = dto.Category.Trim(); if (!string.IsNullOrWhiteSpace(dto.Icon)) template.Icon = dto.Icon.Trim();
return MapToDto(await _repo.UpdateAsync(template)); }
public async Task<bool> DeleteAsync(Guid id, Guid userId) { var template = await _repo.GetByIdAsync(id); if (template is null || template.UserId != userId) return false; return await _repo.DeleteAsync(id); }
private static void ValidateContent(string content) { if (string.IsNullOrWhiteSpace(content)) throw new InvalidOperationException("Template content is empty."); if (content.Length > MaxContentLength) throw new InvalidOperationException("Template is too large. Remove images and try again.");
try { using var doc = JsonDocument.Parse(content); if (!doc.RootElement.TryGetProperty("nodes", out var nodes) || nodes.ValueKind != JsonValueKind.Array || nodes.GetArrayLength() == 0) { throw new InvalidOperationException("Template must contain at least one node."); } } catch (JsonException) { throw new InvalidOperationException("Template content is not valid JSON."); } }
private static string Truncate(string? value, int max) { var trimmed = (value ?? string.Empty).Trim(); return trimmed.Length > max ? trimmed[..max] : trimmed; }
private static TemplateDto MapToDto(CustomTemplate t) => new() { Id = t.Id, Title = t.Title, Description = t.Description, Category = t.Category, Icon = t.Icon, Content = t.ContentJson, CreatedAt = t.CreatedAt }; }}35 unmodified lines36373839404118 unmodified lines60616263646566676840 unmodified lines10911011111211311411511611711811912012112210 unmodified lines1331341351361371381391401411424 unmodified lines14714814915015115215315435 unmodified linespublic async Task<AuthResponseDto> RegisterAsync(CreateUserDto dto){var existing = await _repo.GetByEmailAsync(dto.Email);if (existing is not null)throw new InvalidOperationException("User with this email already exists.");18 unmodified linespublic async Task<AuthResponseDto?> LoginAsync(LoginDto dto){var user = await _repo.GetByEmailAsync(dto.Email);if (user is null || string.IsNullOrEmpty(user.PasswordHash) || user.PasswordHash != HashPassword(dto.Password))return null;return new AuthResponseDto{User = MapToDto(user),40 unmodified linesbool isAvatarUpdated = dto.AvatarUrl is not null && user.AvatarUrl != dto.AvatarUrl;if (dto.DisplayName is not null) user.DisplayName = dto.DisplayName;if (dto.IsPremium.HasValue) user.IsPremium = dto.IsPremium.Value;if (dto.AvatarUrl is not null) user.AvatarUrl = dto.AvatarUrl;if (dto.SubscriptionTier is not null){user.SubscriptionTier = dto.SubscriptionTier;user.IsPremium = dto.SubscriptionTier != "Free";}if (!string.IsNullOrEmpty(dto.Password)) user.PasswordHash = HashPassword(dto.Password);var updated = await _repo.UpdateAsync(user);10 unmodified linesreturn await _repo.DeleteAsync(id);}private static string HashPassword(string password){var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(password));return Convert.ToBase64String(bytes);}private static UserResponseDto MapToDto(User user) => new()4 unmodified linesIsPremium = user.IsPremium,AvatarUrl = user.AvatarUrl,CreatedAt = user.CreatedAt,SubscriptionTier = user.SubscriptionTier,DailyAiGenerationsCount = user.DailyAiGenerationsCount};}}35 unmodified lines36373839404142434418 unmodified lines63646566676869707172737475767740 unmodified lines11811912012112212312412512612712812913010 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751764 unmodified lines18118218318418518618735 unmodified linespublic async Task<AuthResponseDto> RegisterAsync(CreateUserDto dto){if (string.IsNullOrWhiteSpace(dto.Email) || string.IsNullOrEmpty(dto.Password) || dto.Password.Length < MinPasswordLength)throw new ArgumentException($"Email is required and password must be at least {MinPasswordLength} characters.");var existing = await _repo.GetByEmailAsync(dto.Email);if (existing is not null)throw new InvalidOperationException("User with this email already exists.");18 unmodified linespublic async Task<AuthResponseDto?> LoginAsync(LoginDto dto){var user = await _repo.GetByEmailAsync(dto.Email);if (user is null || string.IsNullOrEmpty(user.PasswordHash) || !VerifyPassword(dto.Password, user.PasswordHash, out var needsRehash))return null;if (needsRehash){user.PasswordHash = HashPassword(dto.Password);await _repo.UpdateAsync(user);}return new AuthResponseDto{User = MapToDto(user),40 unmodified linesbool isAvatarUpdated = dto.AvatarUrl is not null && user.AvatarUrl != dto.AvatarUrl;if (dto.DisplayName is not null) user.DisplayName = dto.DisplayName;if (dto.AvatarUrl is not null) user.AvatarUrl = dto.AvatarUrl;if (!string.IsNullOrEmpty(dto.Password)){if (dto.Password.Length < MinPasswordLength)throw new ArgumentException($"Password must be at least {MinPasswordLength} characters.");user.PasswordHash = HashPassword(dto.Password);}var updated = await _repo.UpdateAsync(user);10 unmodified linesreturn await _repo.DeleteAsync(id);}// Format: pbkdf2-sha256$<iterations>$<salt b64>$<hash b64>private const string HashPrefix = "pbkdf2-sha256";private const int HashIterations = 210_000;private const int MinPasswordLength = 6;private static string HashPassword(string password){var salt = RandomNumberGenerator.GetBytes(16);var hash = Rfc2898DeriveBytes.Pbkdf2(password, salt, HashIterations, HashAlgorithmName.SHA256, 32);return $"{HashPrefix}${HashIterations}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}";}private static bool VerifyPassword(string password, string stored, out bool needsRehash){needsRehash = false;var parts = stored.Split('$');if (parts.Length == 4 && parts[0] == HashPrefix && int.TryParse(parts[1], out var iterations)){var salt = Convert.FromBase64String(parts[2]);var expected = Convert.FromBase64String(parts[3]);var actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA256, expected.Length);needsRehash = iterations < HashIterations;return CryptographicOperations.FixedTimeEquals(actual, expected);}// Legacy unsalted SHA-256 hashes: accept once, then upgrade to PBKDF2var legacy = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(password)));var ok = CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(legacy), Encoding.UTF8.GetBytes(stored));needsRehash = ok;return ok;}private static UserResponseDto MapToDto(User user) => new()4 unmodified linesIsPremium = user.IsPremium,AvatarUrl = user.AvatarUrl,CreatedAt = user.CreatedAt,SubscriptionTier = Plans.Normalize(user.SubscriptionTier)};}}
12345678910111213141516171819202122232425262728using FlowAPI.Infrastructure.Data;using Microsoft.EntityFrameworkCore.Infrastructure;using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace FlowAPI.Infrastructure.Migrations{ /// <summary> /// Data-only migration: the Pro and Ultra tiers were merged into a single Plus plan. /// </summary> [DbContext(typeof(AppDbContext))] [Migration("20261017120000_MergeTiersIntoPlus")] public partial class MergeTiersIntoPlus : Migration { /// <inheritdoc /> protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql("UPDATE Users SET SubscriptionTier = 'Plus', IsPremium = 1 WHERE SubscriptionTier IN ('Pro', 'Ultra');"); }
/// <inheritdoc /> protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.Sql("UPDATE Users SET SubscriptionTier = 'Pro' WHERE SubscriptionTier = 'Plus';"); } }}36 unmodified lines373839404136 unmodified linesawait _context.SaveChangesAsync();return template;}}}36 unmodified lines373839404142434445464748495051525354555657585960616236 unmodified linesawait _context.SaveChangesAsync();return template;}public async Task<CustomTemplate> UpdateAsync(CustomTemplate template){_context.CustomTemplates.Update(template);await _context.SaveChangesAsync();return template;}public async Task<bool> DeleteAsync(Guid id){var template = await _context.CustomTemplates.FindAsync(id);if (template is null) return false;_context.CustomTemplates.Remove(template);await _context.SaveChangesAsync();return true;}public async Task<int> CountByUserIdAsync(Guid userId){return await _context.CustomTemplates.CountAsync(t => t.UserId == userId);}}}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677using FlowAPI.Application.DTOs.AI;using FlowAPI.Application.DTOs.Graph;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Mvc;
namespace FlowAPI.Controllers{ [ApiController] [Route("api/[controller]")] public class AIController : ControllerBase { private readonly IAIService _aiService;
public AIController(IAIService aiService) { _aiService = aiService; }
[HttpPost("generate-alternative")] public async Task<ActionResult<AIPathResponseDto>> GenerateAlternative([FromBody] GenerateAlternativeRequestDto request) { try { var response = await _aiService.GenerateAlternativePathAsync(request); return Ok(response); } catch (UnauthorizedAccessException) { return StatusCode(403, new { message = "Premium subscription required for AI generation." }); } catch (InvalidOperationException ex) { return StatusCode(403, new { message = ex.Message }); } catch (Exception ex) { return BadRequest(new { message = ex.Message }); } }
[HttpPost("generate-goal")] public async Task<ActionResult<FullGraphResponseDto>> GenerateGoal([FromBody] GenerateGoalGraphRequestDto request) { try { var response = await _aiService.GenerateGoalGraphAsync(request); return Ok(response); } catch (InvalidOperationException ex) { return StatusCode(403, new { message = ex.Message }); } catch (Exception ex) { return BadRequest(new { message = ex.Message }); } }
[HttpPost("assist")] public async Task<ActionResult<AICanvasAssistResponseDto>> CanvasAssist([FromBody] AICanvasAssistRequestDto request) { try { var response = await _aiService.CanvasAssistAsync(request); return Ok(response); } catch (InvalidOperationException ex) { return StatusCode(403, new { message = ex.Message }); } catch (Exception ex) { return BadRequest(new { message = ex.Message }); } } }}29 unmodified lines3031323334353629 unmodified lines}[HttpPost("seed")][AllowAnonymous] // Allowing anonymous for easy dev setup. Can be secured later.public async Task<IActionResult> SeedAchievements(){await _achievementService.SeedAchievementsAsync();29 unmodified lines30313233343529 unmodified lines}[HttpPost("seed")]public async Task<IActionResult> SeedAchievements(){await _achievementService.SeedAchievementsAsync();
39 unmodified lines404142434445464748495051525354555657585960616263646566676869707172737475767739 unmodified lines_config = config;}[AllowAnonymous][HttpGet("token")]public async Task<IActionResult> GetToken(){// First check if the user exists by email to prevent Unique Index violationsvar user = await _userRepo.GetByEmailAsync("dan9228335@gmail.com");if (user == null){var userId = Guid.Parse("33d1ae31-bf51-4b12-89d0-8e574e7916ab");// Check if the hardcoded ID is somehow already in usevar existingById = await _userRepo.GetByIdAsync(userId);if (existingById != null){user = existingById;}else{user = new User{Id = userId,Email = "dan9228335@gmail.com",DisplayName = "Dodikuser",PasswordHash = "",CreatedAt = DateTime.UtcNow};await _userRepo.CreateAsync(user);}}var token = _tokenService.CreateToken(user);return Ok(new { token });}[HttpPost("create")]public async Task<IActionResult> CreateFromAgent([FromBody] QuestSchemaDto schema){39 unmodified lines40414243444539 unmodified lines_config = config;}[HttpPost("create")]public async Task<IActionResult> CreateFromAgent([FromBody] QuestSchemaDto schema){
12345678910111213141516171819202122232425262728293031323334353637388 unmodified lines4748495051525354using FlowAPI.Application.DTOs.Edge;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Mvc;namespace FlowAPI.Controllers{[ApiController][Route("api/[controller]")]public class EdgesController : ControllerBase{private readonly IEdgeService _service;public EdgesController(IEdgeService service){_service = service;}[HttpGet("graph/{graphId:guid}")]public async Task<ActionResult<IEnumerable<EdgeResponseDto>>> GetAllByGraphId(Guid graphId){var edges = await _service.GetAllByGraphIdAsync(graphId);return Ok(edges);}[HttpGet("{id:guid}")]public async Task<ActionResult<EdgeResponseDto>> GetById(Guid id){var edge = await _service.GetByIdAsync(id);if (edge is null) return NotFound();return Ok(edge);}[HttpPost]public async Task<ActionResult<EdgeResponseDto>> Create([FromBody] CreateEdgeDto dto){try{var edge = await _service.CreateAsync(dto);8 unmodified lines[HttpDelete("{id:guid}")]public async Task<IActionResult> Delete(Guid id){var result = await _service.DeleteAsync(id);if (!result) return NotFound();return NoContent();}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354558 unmodified lines64656667686970717273747576using FlowAPI.Application.DTOs.Edge;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System.Security.Claims;namespace FlowAPI.Controllers{[ApiController][Authorize][Route("api/[controller]")]public class EdgesController : ControllerBase{private readonly IEdgeService _service;private readonly IGraphService _graphService;public EdgesController(IEdgeService service, IGraphService graphService){_service = service;_graphService = graphService;}private Guid CurrentUserId =>Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;private async Task<string?> GetPermissionAsync(Guid graphId) =>(await _graphService.GetByIdAsync(graphId, CurrentUserId))?.Permission;private static bool CanWrite(string? permission) => permission is "Owner" or "Edit";[HttpGet("graph/{graphId:guid}")]public async Task<ActionResult<IEnumerable<EdgeResponseDto>>> GetAllByGraphId(Guid graphId){if (await GetPermissionAsync(graphId) is null) return NotFound();return Ok(await _service.GetAllByGraphIdAsync(graphId));}[HttpGet("{id:guid}")]public async Task<ActionResult<EdgeResponseDto>> GetById(Guid id){var edge = await _service.GetByIdAsync(id);if (edge is null || await GetPermissionAsync(edge.GraphId) is null) return NotFound();return Ok(edge);}[HttpPost]public async Task<ActionResult<EdgeResponseDto>> Create([FromBody] CreateEdgeDto dto){var permission = await GetPermissionAsync(dto.GraphId);if (permission is null) return NotFound();if (!CanWrite(permission)) return Forbid();try{var edge = await _service.CreateAsync(dto);8 unmodified lines[HttpDelete("{id:guid}")]public async Task<IActionResult> Delete(Guid id){var edge = await _service.GetByIdAsync(id);if (edge is null) return NotFound();var permission = await GetPermissionAsync(edge.GraphId);if (permission is null) return NotFound();if (!CanWrite(permission)) return Forbid();if (!await _service.DeleteAsync(id)) return NotFound();return NoContent();}}
12345624 unmodified lines313233343536373839404142434445464748495051525354555657585960112 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203using FlowAPI.Application.DTOs.Graph;using FlowAPI.Application.Interfaces;using FlowAPI.Application.Services;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System;24 unmodified lines}}[HttpGet("templates")]public async Task<ActionResult<IEnumerable<TemplateInfoDto>>> GetTemplates(){var templates = TemplateLibrary.GetTemplateInfos().ToList();var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;if (Guid.TryParse(userIdStr, out var userId)){var customTemplates = await _service.GetCustomTemplatesAsync(userId);foreach (var t in customTemplates){templates.Add(new TemplateInfoDto{Key = t.Id.ToString(),Title = t.Title,Description = t.Description,Icon = t.Icon,Category = t.Category});}}return Ok(templates);}[HttpGet("user/{userId:guid}")]public async Task<ActionResult<IEnumerable<GraphResponseDto>>> GetAllByUserId(Guid userId){112 unmodified linesif (!result) return NotFound();return NoContent();}[HttpPost("{id:guid}/save-as-template")]public async Task<IActionResult> SaveAsTemplate(Guid id, [FromBody] SaveTemplateDto dto){if (CurrentUserId == Guid.Empty) return Unauthorized();try{var template = await _service.SaveAsTemplateAsync(id, CurrentUserId, dto.Title, dto.Description);return Ok(new { message = "Template saved successfully", templateId = template.Id });}catch (InvalidOperationException ex){return BadRequest(new { message = ex.Message });}catch (Exception ex){return BadRequest(new { message = ex.Message });}}}public class SaveTemplateDto{public string Title { get; set; } = string.Empty;public string Description { get; set; } = string.Empty;}}1234524 unmodified lines303132333435112 unmodified lines148149150151152using FlowAPI.Application.DTOs.Graph;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System;24 unmodified lines}}[HttpGet("user/{userId:guid}")]public async Task<ActionResult<IEnumerable<GraphResponseDto>>> GetAllByUserId(Guid userId){112 unmodified linesif (!result) return NotFound();return NoContent();}}}
123456789104 unmodified lines15161718192021222324252627282930313233344 unmodified lines3940414243444546using FlowAPI.Application.DTOs.Habit;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Mvc;namespace FlowAPI.Controllers{[ApiController][Route("api/[controller]")]public class HabitsController : ControllerBase{4 unmodified lines_service = service;}[HttpGet("user/{userId:guid}")]public async Task<ActionResult<IEnumerable<HabitRecordResponseDto>>> GetAllByUserId(Guid userId){var habits = await _service.GetAllByUserIdAsync(userId);return Ok(habits);}[HttpPost("record")]public async Task<ActionResult<HabitRecordResponseDto>> Record([FromBody] CreateHabitRecordDto dto){try{var record = await _service.RecordHabitAsync(dto);return Ok(record);}catch (InvalidOperationException ex){4 unmodified lines[HttpGet("streak/{userId:guid}/{habitName}")]public async Task<ActionResult<int>> GetStreak(Guid userId, string habitName){var streak = await _service.GetStreakAsync(userId, habitName);return Ok(streak);}}}123456789101112134 unmodified lines1819202122232425262728293031323334353637383940414 unmodified lines4647484950515253using FlowAPI.Application.DTOs.Habit;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System.Security.Claims;namespace FlowAPI.Controllers{[ApiController][Authorize][Route("api/[controller]")]public class HabitsController : ControllerBase{4 unmodified lines_service = service;}private Guid CurrentUserId =>Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;[HttpGet("user/{userId:guid}")]public async Task<ActionResult<IEnumerable<HabitRecordResponseDto>>> GetAllByUserId(Guid userId){if (userId != CurrentUserId) return Forbid();return Ok(await _service.GetAllByUserIdAsync(userId));}[HttpPost("record")]public async Task<ActionResult<HabitRecordResponseDto>> Record([FromBody] CreateHabitRecordDto dto){// Always record for the authenticated user, whatever the body saysdto.UserId = CurrentUserId;try{return Ok(await _service.RecordHabitAsync(dto));}catch (InvalidOperationException ex){4 unmodified lines[HttpGet("streak/{userId:guid}/{habitName}")]public async Task<ActionResult<int>> GetStreak(Guid userId, string habitName){if (userId != CurrentUserId) return Forbid();return Ok(await _service.GetStreakAsync(userId, habitName));}}}
123456789101112131415using Microsoft.AspNetCore.Mvc;
namespace FlowAPI.Controllers{ /// <summary> /// Lightweight liveness endpoint; the web client pings it to keep the HF Space awake. /// </summary> [ApiController] [Route("api/[controller]")] public class HealthController : ControllerBase { [HttpGet] public IActionResult Get() => Ok(new { status = "ok" }); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Mvc;namespace FlowAPI.Controllers{[ApiController][Route("api/[controller]")]public class PaymentsController : ControllerBase{private readonly IPaymentService _paymentService;private readonly IUserRepository _userRepo;public PaymentsController(IPaymentService paymentService, IUserRepository userRepo){_paymentService = paymentService;_userRepo = userRepo;}[HttpPost("create-checkout-session/{userId:guid}")]public async Task<ActionResult<object>> CreateCheckoutSession(Guid userId){var url = await _paymentService.CreateCheckoutSessionAsync(userId);return Ok(new { checkoutUrl = url });}[HttpPost("webhook")]public async Task<IActionResult> Webhook(){var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();var signature = Request.Headers["Stripe-Signature"];var result = await _paymentService.HandleWebhookAsync(json, signature!);if (result) return Ok();return BadRequest();}[HttpPost("change-tier/{userId:guid}")]public async Task<IActionResult> ChangeTier(Guid userId, [FromBody] ChangeTierDto dto){var user = await _userRepo.GetByIdAsync(userId);if (user == null) return NotFound("User not found.");var upperTier = dto.Tier.Trim();if (upperTier != "Free" && upperTier != "Pro" && upperTier != "Ultra"){return BadRequest("Invalid tier. Must be 'Free', 'Pro', or 'Ultra'.");}user.SubscriptionTier = upperTier;user.IsPremium = upperTier != "Free";await _userRepo.UpdateAsync(user);return Ok(new {id = user.Id,email = user.Email,displayName = user.DisplayName,isPremium = user.IsPremium,avatarUrl = user.AvatarUrl,createdAt = user.CreatedAt,subscriptionTier = user.SubscriptionTier,dailyAiGenerationsCount = user.DailyAiGenerationsCount});}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475using FlowAPI.Application.Interfaces;using FlowAPI.Application.Services;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System.Security.Claims;namespace FlowAPI.Controllers{[ApiController][Authorize][Route("api/[controller]")]public class PaymentsController : ControllerBase{private readonly IPaymentService _paymentService;private readonly IUserRepository _userRepo;private readonly IUserService _userService;private readonly IConfiguration _config;public PaymentsController(IPaymentService paymentService, IUserRepository userRepo, IUserService userService, IConfiguration config){_paymentService = paymentService;_userRepo = userRepo;_userService = userService;_config = config;}private Guid CurrentUserId =>Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;[HttpPost("create-checkout-session")]public async Task<ActionResult<object>> CreateCheckoutSession(){if (CurrentUserId == Guid.Empty) return Unauthorized();var url = await _paymentService.CreateCheckoutSessionAsync(CurrentUserId);return Ok(new { checkoutUrl = url });}// Disabled until Stripe signature verification is implemented: accepting unsigned// webhooks would let anyone fake a successful payment.[AllowAnonymous][HttpPost("webhook")]public IActionResult Webhook() => StatusCode(StatusCodes.Status501NotImplemented);/// <summary>/// Switches the current user's plan. Downgrading to Free is always allowed./// Upgrading to Plus requires a payment, so without a payment provider it is only/// allowed when Payments:AllowFreeUpgrade is true (local development / demos)./// </summary>[HttpPost("change-tier")]public async Task<IActionResult> ChangeTier([FromBody] ChangeTierDto dto){if (CurrentUserId == Guid.Empty) return Unauthorized();var plan = dto.Tier?.Trim();if (!Plans.IsValid(plan)){return BadRequest(new { message = $"Invalid plan. Must be '{Plans.Free}' or '{Plans.Plus}'." });}var user = await _userRepo.GetByIdAsync(CurrentUserId);if (user == null) return NotFound(new { message = "User not found." });if (plan == Plans.Plus && !Plans.IsPlus(user) && !_config.GetValue<bool>("Payments:AllowFreeUpgrade")){return StatusCode(StatusCodes.Status402PaymentRequired, new { message = "Online payments are not connected yet." });}user.SubscriptionTier = plan!;user.IsPremium = plan == Plans.Plus;await _userRepo.UpdateAsync(user);return Ok(await _userService.GetByIdAsync(user.Id));}}
63 unmodified lines64656667686970717263 unmodified linesreturn true;}[HttpPost("{userId:guid}")]public async Task<ActionResult<SyncResponseDto>> Sync(Guid userId, [FromBody] SyncRequestDto request){var response = await _syncService.SyncChangesAsync(userId, request);return Ok(response);}63 unmodified lines646566676869707172737463 unmodified linesreturn true;}[Authorize][HttpPost("{userId:guid}")]public async Task<ActionResult<SyncResponseDto>> Sync(Guid userId, [FromBody] SyncRequestDto request){if (userId != CurrentUserId) return Forbid();var response = await _syncService.SyncChangesAsync(userId, request);return Ok(response);}
12345678910111213141516171819202122232425262728293031323334353637388 unmodified lines4748495051522 unmodified lines5556575859606162636465666768697071727374using FlowAPI.Application.DTOs.TaskNode;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Mvc;namespace FlowAPI.Controllers{[ApiController][Route("api/[controller]")]public class TaskNodesController : ControllerBase{private readonly ITaskNodeService _service;public TaskNodesController(ITaskNodeService service){_service = service;}[HttpGet("graph/{graphId:guid}")]public async Task<ActionResult<IEnumerable<TaskNodeResponseDto>>> GetAllByGraphId(Guid graphId){var nodes = await _service.GetAllByGraphIdAsync(graphId);return Ok(nodes);}[HttpGet("{id:guid}")]public async Task<ActionResult<TaskNodeResponseDto>> GetById(Guid id){var node = await _service.GetByIdAsync(id);if (node is null) return NotFound();return Ok(node);}[HttpPost]public async Task<ActionResult<TaskNodeResponseDto>> Create([FromBody] CreateTaskNodeDto dto){try{var node = await _service.CreateAsync(dto);8 unmodified lines[HttpPut("{id:guid}")]public async Task<ActionResult<TaskNodeResponseDto>> Update(Guid id, [FromBody] UpdateTaskNodeDto dto){var node = await _service.UpdateAsync(id, dto);if (node is null) return NotFound();return Ok(node);2 unmodified lines[HttpDelete("{id:guid}")]public async Task<IActionResult> Delete(Guid id){var result = await _service.DeleteAsync(id);if (!result) return NotFound();return NoContent();}[HttpGet("{id:guid}/data")]public async Task<ActionResult<object>> GetNodeData(Guid id){var nodeData = await _service.GetNodeDataAsync(id);if (nodeData is null){var node = await _service.GetByIdAsync(id);if (node is null) return NotFound();}return Ok(new { data = nodeData });}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455568 unmodified lines6566676869707172737475762 unmodified lines798081828384858687888990919293949596979899100101using FlowAPI.Application.DTOs.TaskNode;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System.Security.Claims;namespace FlowAPI.Controllers{[ApiController][Authorize][Route("api/[controller]")]public class TaskNodesController : ControllerBase{private readonly ITaskNodeService _service;private readonly IGraphService _graphService;public TaskNodesController(ITaskNodeService service, IGraphService graphService){_service = service;_graphService = graphService;}private Guid CurrentUserId =>Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;// null = no access; otherwise the caller's permission on the board ("Owner", "Edit", "Read")private async Task<string?> GetPermissionAsync(Guid graphId) =>(await _graphService.GetByIdAsync(graphId, CurrentUserId))?.Permission;private static bool CanWrite(string? permission) => permission is "Owner" or "Edit";[HttpGet("graph/{graphId:guid}")]public async Task<ActionResult<IEnumerable<TaskNodeResponseDto>>> GetAllByGraphId(Guid graphId){if (await GetPermissionAsync(graphId) is null) return NotFound();return Ok(await _service.GetAllByGraphIdAsync(graphId));}[HttpGet("{id:guid}")]public async Task<ActionResult<TaskNodeResponseDto>> GetById(Guid id){var node = await _service.GetByIdAsync(id);if (node is null || await GetPermissionAsync(node.GraphId) is null) return NotFound();return Ok(node);}[HttpPost]public async Task<ActionResult<TaskNodeResponseDto>> Create([FromBody] CreateTaskNodeDto dto){var permission = await GetPermissionAsync(dto.GraphId);if (permission is null) return NotFound();if (!CanWrite(permission)) return Forbid();try{var node = await _service.CreateAsync(dto);8 unmodified lines[HttpPut("{id:guid}")]public async Task<ActionResult<TaskNodeResponseDto>> Update(Guid id, [FromBody] UpdateTaskNodeDto dto){var existing = await _service.GetByIdAsync(id);if (existing is null) return NotFound();var permission = await GetPermissionAsync(existing.GraphId);if (permission is null) return NotFound();if (!CanWrite(permission)) return Forbid();var node = await _service.UpdateAsync(id, dto);if (node is null) return NotFound();return Ok(node);2 unmodified lines[HttpDelete("{id:guid}")]public async Task<IActionResult> Delete(Guid id){var existing = await _service.GetByIdAsync(id);if (existing is null) return NotFound();var permission = await GetPermissionAsync(existing.GraphId);if (permission is null) return NotFound();if (!CanWrite(permission)) return Forbid();if (!await _service.DeleteAsync(id)) return NotFound();return NoContent();}[HttpGet("{id:guid}/data")]public async Task<ActionResult<object>> GetNodeData(Guid id){var node = await _service.GetByIdAsync(id);if (node is null || await GetPermissionAsync(node.GraphId) is null) return NotFound();var nodeData = await _service.GetNodeDataAsync(id);return Ok(new { data = nodeData });}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778using FlowAPI.Application.DTOs.Template;using FlowAPI.Application.Interfaces;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System;using System.Collections.Generic;using System.Security.Claims;using System.Threading.Tasks;
namespace FlowAPI.Controllers{ /// <summary> /// User-owned templates. Built-in templates live in the web client. /// </summary> [ApiController] [Authorize] [Route("api/[controller]")] public class TemplatesController : ControllerBase { private readonly ITemplateService _service;
public TemplatesController(ITemplateService service) { _service = service; }
private Guid CurrentUserId => Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
[HttpGet] public async Task<ActionResult<IEnumerable<TemplateDto>>> GetMine() { if (CurrentUserId == Guid.Empty) return Unauthorized(); return Ok(await _service.GetMineAsync(CurrentUserId)); }
[HttpGet("{id:guid}")] public async Task<ActionResult<TemplateDto>> Get(Guid id) { if (CurrentUserId == Guid.Empty) return Unauthorized(); var template = await _service.GetAsync(id, CurrentUserId); if (template is null) return NotFound(); return Ok(template); }
[HttpPost] public async Task<ActionResult<TemplateDto>> Create([FromBody] CreateTemplateDto dto) { if (CurrentUserId == Guid.Empty) return Unauthorized(); try { var template = await _service.CreateAsync(dto, CurrentUserId); return CreatedAtAction(nameof(Get), new { id = template.Id }, template); } catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); } }
[HttpPut("{id:guid}")] public async Task<ActionResult<TemplateDto>> Update(Guid id, [FromBody] UpdateTemplateDto dto) { if (CurrentUserId == Guid.Empty) return Unauthorized(); var template = await _service.UpdateAsync(id, dto, CurrentUserId); if (template is null) return NotFound(); return Ok(template); }
[HttpDelete("{id:guid}")] public async Task<IActionResult> Delete(Guid id) { if (CurrentUserId == Guid.Empty) return Unauthorized(); if (!await _service.DeleteAsync(id, CurrentUserId)) return NotFound(); return NoContent(); } }}32 unmodified lines3334353637383940414243444546474811 unmodified lines60616263646518 unmodified lines8485868788899091929394959697989910032 unmodified linesreturn Ok(user);}[HttpGet]public async Task<ActionResult<IEnumerable<UserResponseDto>>> GetAll(){var users = await _service.GetAllAsync();return Ok(users);}[HttpGet("{id:guid}")]public async Task<ActionResult<UserResponseDto>> GetById(Guid id){var user = await _service.GetByIdAsync(id);if (user is null) return NotFound();return Ok(user);11 unmodified lines{return Conflict(new { message = ex.Message });}}[HttpPost("login")]18 unmodified lines}}[HttpPut("{id:guid}")]public async Task<ActionResult<UserResponseDto>> Update(Guid id, [FromBody] UpdateUserDto dto){var user = await _service.UpdateAsync(id, dto);if (user is null) return NotFound();return Ok(user);}[HttpDelete("{id:guid}")]public async Task<IActionResult> Delete(Guid id){var result = await _service.DeleteAsync(id);if (!result) return NotFound();return NoContent();32 unmodified lines333435363738394041424344454611 unmodified lines5859606162636465666718 unmodified lines868788899091929394959697989910010110210310410510610710810911011111211332 unmodified linesreturn Ok(user);}private Guid CurrentUserId =>Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;[Authorize][HttpGet("{id:guid}")]public async Task<ActionResult<UserResponseDto>> GetById(Guid id){if (id != CurrentUserId) return Forbid();var user = await _service.GetByIdAsync(id);if (user is null) return NotFound();return Ok(user);11 unmodified lines{return Conflict(new { message = ex.Message });}catch (ArgumentException ex){return BadRequest(new { message = ex.Message });}}[HttpPost("login")]18 unmodified lines}}[Authorize][HttpPut("{id:guid}")]public async Task<ActionResult<UserResponseDto>> Update(Guid id, [FromBody] UpdateUserDto dto){if (id != CurrentUserId) return Forbid();try{var user = await _service.UpdateAsync(id, dto);if (user is null) return NotFound();return Ok(user);}catch (ArgumentException ex){return BadRequest(new { message = ex.Message });}}[Authorize][HttpDelete("{id:guid}")]public async Task<IActionResult> Delete(Guid id){if (id != CurrentUserId) return Forbid();var result = await _service.DeleteAsync(id);if (!result) return NotFound();return NoContent();
19 unmodified lines2021222324252627282919 unmodified lines<ProjectReference Include="..\FlowAPI.Infrastructure\FlowAPI.Infrastructure.csproj" /></ItemGroup><ItemGroup><None Update="FreeDeepseekAPI\**"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></None></ItemGroup></Project>19 unmodified lines2021222319 unmodified lines<ProjectReference Include="..\FlowAPI.Infrastructure\FlowAPI.Infrastructure.csproj" /></ItemGroup></Project>
123456{ "name": "free-deepseek-api", "version": "0.1.0", "main": "server.js", "type": "commonjs"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400#!/usr/bin/env node/** * OpenAI-compatible API server wrapping DeepSeek Web API * Supports BOTH streaming (SSE) and non-streaming modes * Includes tool calling: injects tool definitions into system prompt, * parses LLM text responses for TOOL_CALL patterns, returns OpenAI tool_calls format. * * Per-agent sessions: each unique `user` field gets its own DeepSeek web session. * Auto-reset: sessions reset when message chain > 50 messages or age > 2 hours. * Listens on 0.0.0.0:9655 */
const http = require('http');const fs = require('fs');const os = require('os');const path = require('path');const readline = require('readline');const { spawnSync } = require('child_process');
const SERVER_HOST = os.hostname(); // Dynamic hostname detectionconst SERVER_PUBLIC_IP = (() => { try { const interfaces = os.networkInterfaces(); for (const name of Object.keys(interfaces)) { for (const iface of interfaces[name]) { if (iface.family === 'IPv4' && !iface.internal) return iface.address; } } } catch (e) {} return 'localhost';})();
const FORGETMEAI_WATERMARK = 't.me/forgetmeai';const PORT = Number(process.env.PORT || 9655);const HOST = process.env.HOST || '0.0.0.0';function formatWatermark(prefix = 'ForgetMeAI') { return `${prefix}: ${FORGETMEAI_WATERMARK}`; }function printBanner() { console.log(`███████ ██████ ███████ ███████ ██████ ███████ ███████ ███████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███████ ██████ █████ █████ ██ ██ █████ █████ █████ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ███████ ███████ ██████ ███████ ███████ ███████ ██ ██
FreeDeepseekAPI — API-прокси для DeepSeek Web Chat ${formatWatermark()}`);}function prompt(question) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise(resolve => rl.question(question, ans => { rl.close(); resolve(ans); }));}function isTruthy(value) { return typeof value === 'string' && ['1','true','yes','on'].includes(value.trim().toLowerCase()); }
// === Per-Agent Session Store ===const sessions = new Map(); // keyed by agent ID (from `user` field)const MAX_HISTORY_LENGTH = 15;const MAX_HISTORY_CHARS = 10000;const MAX_MESSAGE_DEPTH = 100; // auto-reset after this many messagesconst SESSION_TTL_MS = 2 * 60 * 60 * 1000; // 2 hours
// === DeepSeek Web API Config — loaded from external config file ===const DS_CONFIG_PATH = process.env.DEEPSEEK_AUTH_PATH || path.join(__dirname, 'deepseek-auth.json');let DS_CONFIG = {};let BASE_HEADERS = {};function buildBaseHeaders() { return { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36", "x-client-platform": "web", "x-client-version": "2.0.0", "x-client-locale": "ru", "x-client-timezone-offset": "14400", "x-app-version": "2.0.0", "Authorization": `Bearer ${DS_CONFIG.token || ''}`, "x-hif-dliq": DS_CONFIG.hif_dliq || '', "x-hif-leim": DS_CONFIG.hif_leim || '', "Origin": "https://chat.deepseek.com", "Referer": "https://chat.deepseek.com/", "Cookie": DS_CONFIG.cookie || '', "Content-Type": "application/json", };}function loadDeepSeekConfig({ fatal = true } = {}) { try { if (fs.existsSync(DS_CONFIG_PATH)) { const raw = fs.readFileSync(DS_CONFIG_PATH, 'utf8'); DS_CONFIG = JSON.parse(raw); console.log(`[DS-API] Loaded auth config from ${DS_CONFIG_PATH}`); } else { DS_CONFIG = { token: process.env.DEEPSEEK_TOKEN || '', cookie: process.env.DEEPSEEK_COOKIE || '', hif_dliq: process.env.DEEPSEEK_HIF_DLIQ || '', hif_leim: process.env.DEEPSEEK_HIF_LEIM || '', wasmUrl: process.env.DEEPSEEK_WASM_URL || 'https://fe-static.deepseek.com/chat/static/sha3_wasm_bg.7b9ca65ddd.wasm', }; console.log(`[DS-API] Loaded auth config from process.env`); } BASE_HEADERS = buildBaseHeaders(); return true; } catch (e) { DS_CONFIG = {}; BASE_HEADERS = buildBaseHeaders(); if (fatal) { console.error(`[DS-API] FATAL: Could not load auth config: ${e.message}`); process.exit(1); } return false; }}function hasAuthConfig() { return !!(DS_CONFIG.token && DS_CONFIG.cookie); }loadDeepSeekConfig({ fatal: false });
function createSession() { return { id: null, parentMessageId: null, createdAt: null, messageCount: 0, history: [], };}
function getOrCreateAgentSession(agentId) { if (!sessions.has(agentId)) { sessions.set(agentId, createSession()); } return sessions.get(agentId);}
async function solvePOW(challenge) { const resp = await fetch(DS_CONFIG.wasmUrl); const wasmBytes = await resp.arrayBuffer(); const mod = await WebAssembly.instantiate(wasmBytes, { wbg: {} }); const e = mod.instance.exports; const encoder = new TextEncoder(); const prefix = challenge.salt + '_' + challenge.expire_at + '_'; const cBytes = encoder.encode(challenge.challenge); const pBytes = encoder.encode(prefix); const cP = e.__wbindgen_export_0(cBytes.length, 1) >>> 0; const pP = e.__wbindgen_export_0(pBytes.length, 1) >>> 0; new Uint8Array(e.memory.buffer, cP, cBytes.length).set(cBytes); new Uint8Array(e.memory.buffer, pP, pBytes.length).set(pBytes); const sp = e.__wbindgen_add_to_stack_pointer(-16); e.wasm_solve(sp, cP, cBytes.length, pP, pBytes.length, challenge.difficulty); const dv = new DataView(e.memory.buffer); const code = dv.getInt32(sp, true); const ans = dv.getFloat64(sp + 8, true); e.__wbindgen_add_to_stack_pointer(16); if (code === 0 || !Number.isFinite(ans) || ans <= 0) throw new Error('POW failed'); return Math.floor(ans);}
const MODEL_CONFIGS = { // DeepSeek Web real model_type: default / UI name: "Быстрый". // Public model family: DeepSeek-V3.2-Exp chat mode (fast, no visible reasoning). 'deepseek-chat': { model_type: 'default', thinking_enabled: false, search_enabled: false, real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)', capabilities: { reasoning: false, web_search: false, files: true }, supported: true, }, 'deepseek-v3': { model_type: 'default', thinking_enabled: false, search_enabled: false, real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)', capabilities: { reasoning: false, web_search: false, files: true }, supported: true, }, 'deepseek-default': { model_type: 'default', thinking_enabled: false, search_enabled: false, real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)', capabilities: { reasoning: false, web_search: false, files: true }, supported: true, }, // Same DeepSeek Web default model, but with thinking_enabled=true. UI exposes it as thinking/reasoning mode. 'deepseek-reasoner': { model_type: 'default', thinking_enabled: true, search_enabled: false, real_model: 'DeepSeek-V4-Flash thinking mode (DeepSeek Web “Быстрый” + thinking_enabled)', capabilities: { reasoning: true, web_search: false, files: true }, supported: true, }, 'deepseek-r1': { model_type: 'default', thinking_enabled: true, search_enabled: false, real_model: 'DeepSeek-V4-Flash thinking mode; R1-compatible alias, not a separate R1 model_type in current Web API', capabilities: { reasoning: true, web_search: false, files: true }, supported: true, }, 'deepseek-chat-search': { model_type: 'default', thinking_enabled: false, search_enabled: true, real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search', capabilities: { reasoning: false, web_search: true, files: true }, supported: true, }, 'deepseek-default-search': { model_type: 'default', thinking_enabled: false, search_enabled: true, real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search', capabilities: { reasoning: false, web_search: true, files: true }, supported: true, }, 'deepseek-reasoner-search': { model_type: 'default', thinking_enabled: true, search_enabled: true, real_model: 'DeepSeek-V4-Flash thinking mode + web search', capabilities: { reasoning: true, web_search: true, files: true }, supported: true, }, 'deepseek-r1-search': { model_type: 'default', thinking_enabled: true, search_enabled: true, real_model: 'DeepSeek-V4-Flash thinking mode + web search; R1-compatible alias', capabilities: { reasoning: true, web_search: true, files: true }, supported: true, }, // DeepSeek Web UI name: “Эксперт”. Requires current web client headers (x-client-version=2.0.0). 'deepseek-expert': { model_type: 'expert', thinking_enabled: false, search_enabled: false, real_model: 'DeepSeek Web “Эксперт” (limited resources)', capabilities: { reasoning: false, web_search: false, files: false }, supported: true, }, 'deepseek-v4-pro': { model_type: 'expert', thinking_enabled: true, search_enabled: false, real_model: 'DeepSeek Web “Эксперт” + thinking mode (exposed as deepseek-v4-pro alias)', capabilities: { reasoning: true, web_search: false, files: false }, supported: true, }, 'deepseek-expert-search': { model_type: 'expert', thinking_enabled: false, search_enabled: true, real_model: 'DeepSeek Web “Эксперт” + search requested, but Expert has search_feature=null in remote config', capabilities: { reasoning: false, web_search: false, files: false }, supported: false, unavailable_reason: 'Expert mode is rejected; remote config says search is not available for Expert.', }, 'deepseek-vision': { model_type: 'vision', thinking_enabled: false, search_enabled: false, real_model: 'DeepSeek Web “Распознавание” / image understanding beta', capabilities: { reasoning: false, web_search: false, files: true, vision: true }, supported: false, unavailable_reason: 'Current Web API returns: Vision is temporarily unavailable (backend_err_by_model).', },};
const SUPPORTED_MODEL_IDS = Object.keys(MODEL_CONFIGS).filter(id => MODEL_CONFIGS[id].supported);const ALL_MODEL_CAPABILITIES = Object.fromEntries(Object.entries(MODEL_CONFIGS).map(([id, cfg]) => [id, { id, real_model: cfg.real_model, model_type: cfg.model_type, thinking_enabled: cfg.thinking_enabled, search_enabled: cfg.search_enabled, capabilities: cfg.capabilities, supported: cfg.supported, unavailable_reason: cfg.unavailable_reason || null,}]));
function resolveModelConfig(model) { const requested = String(model || 'deepseek-chat').toLowerCase(); return MODEL_CONFIGS[requested] || MODEL_CONFIGS['deepseek-chat'];}function isKnownModel(model) { return Object.prototype.hasOwnProperty.call(MODEL_CONFIGS, String(model || '').toLowerCase()); }function isSupportedModel(model) { return resolveModelConfig(model).supported === true; }
async function askDeepSeekStream(prompt, agentId, model = 'deepseek-default') { const modelCfg = resolveModelConfig(model); const session = getOrCreateAgentSession(agentId); const agentTag = `[${agentId}]`;
// Auto-reset on deep message chain if (session.id && session.messageCount >= MAX_MESSAGE_DEPTH) { console.log(`${agentTag} Session ${session.id} hit ${session.messageCount} messages. Auto-resetting.`); session.id = null; session.parentMessageId = null; session.createdAt = null; session.messageCount = 0; // History preserved for context injection }
// Reset expired sessions (DeepSeek web sessions last ~1-2 hours) if (session.id && session.createdAt && (Date.now() - session.createdAt > SESSION_TTL_MS)) { console.log(`${agentTag} Session ${session.id} expired (age: ${Math.round((Date.now() - session.createdAt) / 60000)}min). Creating new...`); session.id = null; session.parentMessageId = null; session.createdAt = null; session.messageCount = 0; }
const cr = await fetch('https://chat.deepseek.com/api/v0/chat/create_pow_challenge', { method: 'POST', headers: BASE_HEADERS, body: JSON.stringify({ target_path: '/api/v0/chat/completion' }) }); const chalJson = JSON.parse(await cr.text()); const challenge = chalJson.data.biz_data.challenge; const answer = await solvePOW(challenge);
if (!session.id) { const sr = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', { method: 'POST', headers: BASE_HEADERS, body: '{}' }); const sessionData = await sr.json(); session.id = sessionData.data.biz_data.chat_session?.id || sessionData.data.biz_data.id; session.parentMessageId = null; session.createdAt = Date.now(); session.messageCount = 0; console.log(`${agentTag} Created new session: ${session.id}`); } else { console.log(`${agentTag} Reusing session: ${session.id} (parent: ${session.parentMessageId}, msg#${session.messageCount})`); }
const powB64 = Buffer.from(JSON.stringify({ algorithm: challenge.algorithm, challenge: challenge.challenge, salt: challenge.salt, answer: answer, signature: challenge.signature, target_path: '/api/v0/chat/completion' })).toString('base64'); const resp = await fetch('https://chat.deepseek.com/api/v0/chat/completion', { method: 'POST', headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': powB64 }, body: JSON.stringify({ chat_session_id: session.id, parent_message_id: session.parentMessageId, model_type: modelCfg.model_type, prompt: prompt, ref_file_ids: [], thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled, action: null, preempt: false, }) });
// If session expired, reset and retry once if (resp.status !== 200) { const errText = await resp.text(); console.log(`${agentTag} Session error (${resp.status}): ${errText.substring(0, 100)}`); if (resp.status === 400 || resp.status === 404 || resp.status === 500) { console.log(`${agentTag} Session ${session.id} expired. Creating new session...`); session.id = null; session.parentMessageId = null; session.createdAt = null; session.messageCount = 0;
const sr2 = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', { method: 'POST', headers: BASE_HEADERS, body: '{}' }); const sessionData2 = await sr2.json(); session.id = sessionData2.data.biz_data.chat_session?.id || sessionData2.data.biz_data.id; session.parentMessageId = null; session.createdAt = Date.now(); console.log(`${agentTag} Created new session: ${session.id}`);
const newPowB64 = Buffer.from(JSON.stringify({ algorithm: challenge.algorithm, challenge: challenge.challenge, salt: challenge.salt, answer: answer, signature: challenge.signature, target_path: '/api/v0/chat/completion' })).toString('base64'); const resp2 = await fetch('https://chat.deepseek.com/api/v0/chat/completion', { method: 'POST', headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': newPowB64 }, body: JSON.stringify({ chat_session_id: session.id, parent_message_id: null, model_type: modelCfg.model_type, prompt: prompt, ref_file_ids: [], thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled, action: null, preempt: false, }) }); return { resp: resp2, agentId }; } }
return { resp, agentId };}
// === Tool Calling Support ===
function formatToolDefinitions(tools) { if (!tools || tools.length === 0) return ''; let text = '\n\n--- TOOL REQUEST SYSTEM ---\n'; text += 'You are an AI that ONLY REASONS and REQUESTS tool executions. You do NOT run any commands yourself.\n'; text += 'When you need data from the local server, REQUEST exactly one tool call. Prefer strict JSON:\n'; text += '{"tool_call":{"name":"<function_name>","arguments":{...}}}\n\n'; text += 'Legacy format is also accepted: TOOL_CALL: <function_name>\narguments: <JSON arguments>\n\n'; text += 'Your response will be sent to the local gateway, which executes the command and sends the output back in the next message.\n\n'; text += 'RULES:\n'; text += '1. You ONLY output the tool request — you never run anything yourself\n'; text += '2. Do NOT simulate, guess, or fabricate command output — wait for the actual result\n'; text += '3. The tool runs on ' + SERVER_HOST + ' (' + SERVER_PUBLIC_IP + '), the local server — NOT on DeepSeek\n'; text += '4. After the tool executes, the result will be sent to you as a new user/tool message\n'; text += '5. Never add explanation before or after the tool request when requesting a tool\n'; text += '6. Keep arguments compact. Do not include large file contents unless the tool schema requires it.\n\n'; text += 'Available functions:\n'; for (const tool of tools) { if (tool.type === 'function' && tool.function) { const fn = tool.function; text += `\n## ${fn.name}\n`; text += `${fn.description || ''}\n`; if (fn.parameters) { text += `Parameters: ${JSON.stringify(fn.parameters)}\n`; } } } text += '\n--- END TOOL REQUEST SYSTEM ---\n'; text += '\nREMEMBER: Request tools only with strict JSON or TOOL_CALL legacy format. Never simulate results.'; return text;}
function extractBalancedJsonAt(text, startIndex) { let braceDepth = 0; let inString = false; let escape = false; for (let i = startIndex; i < text.length; i++) { const ch = text[i]; if (escape) { escape = false; continue; } if (ch === '\\' && inString) { escape = true; continue; } if (ch === '"') { inString = !inString; continue; } if (!inString) { if (ch === '{') braceDepth++; if (ch === '}') { braceDepth--; if (braceDepth === 0) return text.substring(startIndex, i + 1); } } } return null;}
function coerceToolCallObject(obj) { if (!obj || typeof obj !== 'object') return null; const candidate = obj.tool_call || obj.tool || obj.function_call || obj; if (!candidate || typeof candidate !== 'object') return null; const fn = candidate.function && typeof candidate.function === 'object' ? candidate.function : candidate; const name = fn.name || candidate.name || obj.name; let args = fn.arguments ?? candidate.arguments ?? candidate.input ?? obj.arguments ?? obj.input ?? {}; if (!name || typeof name !== 'string') return null; if (typeof args === 'string') { try { args = JSON.parse(args); } catch (e) { args = { raw: args }; } } if (!args || typeof args !== 'object' || Array.isArray(args)) args = { value: args }; return { name, arguments: JSON.stringify(args) };}
function parseJsonToolCandidate(raw, label = 'json') { if (!raw) return null; try { const parsed = JSON.parse(raw); const tc = coerceToolCallObject(parsed); if (tc) { console.log(`[parseToolCall] SUCCESS ${label}: ${tc.name} (args=${tc.arguments.length} chars)`); return tc; } } catch (e) { console.log(`[parseToolCall] ${label} JSON.parse failed: ${e.message.substring(0, 100)}`); } return null;}
function parseToolCall(text) { if (!text || typeof text !== 'string') return null;
// XML-ish wrappers used by some agent prompts. const xmlMatch = text.match(/<tool_call[^>]*>([\s\S]*?)<\/tool_call>/i); if (xmlMatch) { const inner = xmlMatch[1].trim(); const tc = parseJsonToolCandidate(inner, 'xml'); if (tc) return tc; }
// Fenced JSON blocks. const fenceRe = /```(?:json)?\s*([\s\S]*?)```/gi; let fence; while ((fence = fenceRe.exec(text)) !== null) { const tc = parseJsonToolCandidate(fence[1].trim(), 'fenced'); if (tc) return tc; }
// Legacy TOOL_CALL: name + first balanced JSON object after it. const match = text.match(/TOOL_CALL:\s*([\w-]+)\s*/i); if (match) { const name = match[1]; const afterMatch = text.substring(match.index + match[0].length); const braceIdx = afterMatch.indexOf('{'); if (braceIdx !== -1) { const rawJson = extractBalancedJsonAt(afterMatch, braceIdx); if (rawJson) { try { const args = JSON.parse(rawJson); console.log(`[parseToolCall] SUCCESS legacy: ${name} (args=${rawJson.length} chars)`); return { name, arguments: JSON.stringify(args) }; } catch (e) { console.log(`[parseToolCall] legacy JSON.parse failed: ${e.message.substring(0,100)}`); } } else { console.log(`[parseToolCall] TOOL_CALL:${name} found but JSON braces are unbalanced`); } } else { console.log(`[parseToolCall] TOOL_CALL:${name} found but no { after it`); } }
// First balanced JSON object in the whole response. Supports: // {"tool_call":{"name":"...","arguments":{...}}}, {"name":"...","arguments":{...}}, etc. for (let i = 0; i < text.length; i++) { if (text[i] !== '{') continue; const rawJson = extractBalancedJsonAt(text, i); if (!rawJson) continue; const tc = parseJsonToolCandidate(rawJson, 'inline'); if (tc) return tc; }
console.log(`[parseToolCall] No tool call match in ${text.length} chars`); return null;}
/** * Strip surrogate characters and other problematic Unicode from text * to prevent httpx/urlencode crashes when the gateway sends to Telegram. */function sanitizeContent(text) { return text.replace(/[\ud800-\udfff]/g, '');}
function estimateTokens(text) { return text ? Math.ceil(String(text).length / 4) : 0;}
function buildUsage(prompt, content, reasoningContent = '') { const promptTokens = estimateTokens(prompt); const contentTokens = estimateTokens(content); const reasoningTokens = estimateTokens(reasoningContent); const completionTokens = contentTokens + reasoningTokens; return { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens, completion_tokens_details: { reasoning_tokens: reasoningTokens } };}
function buildToolCallResponse(toolCall, model = 'deepseek-default', prompt = '', reasoningContent = '') { const id = 'call_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8); const message = { role: 'assistant', content: null, tool_calls: [{ id: id, type: 'function', function: { name: toolCall.name, arguments: toolCall.arguments } }] }; // Do not attach reasoning to tool-call turns. Some agent clients treat any // reasoning/text payload as a final assistant answer and stop their tool loop. return { id: 'ds-' + Date.now(), object: 'chat.completion', created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, message, finish_reason: 'tool_calls' }], usage: buildUsage(prompt, '', reasoningContent), watermark: FORGETMEAI_WATERMARK };}
function buildTextResponse(content, prompt, model = 'deepseek-default', reasoningContent = '') { const message = { role: 'assistant', content }; if (reasoningContent) message.reasoning_content = reasoningContent; return { id: 'ds-' + Date.now(), object: 'chat.completion', created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, message, finish_reason: 'stop' }], usage: buildUsage(prompt, content, reasoningContent), watermark: FORGETMEAI_WATERMARK };}
function normalizeMessageContent(content) { if (content === null || content === undefined) return ''; if (typeof content === 'string') return content; if (Array.isArray(content)) { return content.map(part => { if (typeof part === 'string') return part; if (!part || typeof part !== 'object') return ''; if (part.type === 'text' || part.type === 'input_text' || part.type === 'output_text') return part.text || ''; if (part.type === 'tool_result') return `[Tool Result ${part.tool_use_id || ''}]\n${normalizeMessageContent(part.content)}`; if (part.type === 'image_url') return `[Image: ${part.image_url?.url || ''}]`; return part.text || part.content || JSON.stringify(part); }).filter(Boolean).join('\n'); } return String(content);}
function normalizeAnthropicTools(tools = []) { return (tools || []).map(tool => ({ type: 'function', function: { name: tool.name, description: tool.description || '', parameters: tool.input_schema || tool.parameters || { type: 'object', properties: {} } } })).filter(tool => tool.function.name);}
function normalizeResponsesTools(tools = []) { return (tools || []).map(tool => { if (tool.type === 'function' && tool.function) return tool; if (tool.type === 'function' && tool.name) { return { type: 'function', function: { name: tool.name, description: tool.description || '', parameters: tool.parameters || { type: 'object', properties: {} } } }; } return null; }).filter(Boolean);}
function normalizeResponsesInput(input) { if (typeof input === 'string') return [{ role: 'user', content: input }]; if (!Array.isArray(input)) return []; const messages = []; for (const item of input) { if (!item || typeof item !== 'object') continue; if (item.type === 'message') { messages.push({ role: item.role || 'user', content: normalizeMessageContent(item.content) }); } else if (item.role) { messages.push({ role: item.role, content: normalizeMessageContent(item.content) }); } else if (item.type === 'function_call_output') { messages.push({ role: 'tool', tool_call_id: item.call_id, content: item.output || '' }); } else if (item.type === 'input_text') { messages.push({ role: 'user', content: item.text || '' }); } } return messages;}
function normalizeApiParams(params, apiMode) { if (apiMode === 'anthropic') { const messages = []; if (params.system) messages.push({ role: 'system', content: normalizeMessageContent(params.system) }); for (const msg of params.messages || []) { if (msg.role === 'assistant' && Array.isArray(msg.content)) { const toolUses = msg.content.filter(part => part && part.type === 'tool_use'); const text = normalizeMessageContent(msg.content.filter(part => !part || part.type !== 'tool_use')); if (text) messages.push({ role: 'assistant', content: text }); for (const tu of toolUses) { messages.push({ role: 'assistant', content: null, tool_calls: [{ id: tu.id, type: 'function', function: { name: tu.name, arguments: JSON.stringify(tu.input || {}) } }] }); } } else if (msg.role === 'user' && Array.isArray(msg.content) && msg.content.some(part => part && part.type === 'tool_result')) { for (const part of msg.content) { if (part && part.type === 'tool_result') messages.push({ role: 'tool', tool_call_id: part.tool_use_id, content: normalizeMessageContent(part.content) }); else messages.push({ role: 'user', content: normalizeMessageContent(part) }); } } else { messages.push({ role: msg.role || 'user', content: normalizeMessageContent(msg.content) }); } } return { ...params, model: params.model || 'deepseek-chat', messages, tools: normalizeAnthropicTools(params.tools || []), stream: params.stream === true, user: params.metadata?.user_id || params.user, }; } if (apiMode === 'responses') { const messages = normalizeResponsesInput(params.input); if (params.instructions) messages.unshift({ role: 'system', content: params.instructions }); return { ...params, model: params.model || 'deepseek-chat', messages, tools: normalizeResponsesTools(params.tools || []), stream: params.stream === true, user: params.user, }; } return params;}
function safeJsonParseObject(text, fallback = {}) { try { const parsed = JSON.parse(text || '{}'); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback; } catch (e) { return fallback; }}
function toAnthropicResponse(openaiResp) { const choice = openaiResp.choices[0]; const msg = choice.message || {}; const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0; const content = []; if (hasToolCalls) { for (const tc of msg.tool_calls) { content.push({ type: 'tool_use', id: tc.id, name: tc.function.name, input: safeJsonParseObject(tc.function.arguments) }); } } else { content.push({ type: 'text', text: msg.content || '' }); } const response = { id: 'msg_' + openaiResp.id, type: 'message', role: 'assistant', model: openaiResp.model, content, stop_reason: choice.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn', stop_sequence: null, usage: { input_tokens: openaiResp.usage?.prompt_tokens || 0, output_tokens: openaiResp.usage?.completion_tokens || 0, }, watermark: FORGETMEAI_WATERMARK, }; if (!hasToolCalls && msg.reasoning_content) response.reasoning_content = msg.reasoning_content; return response;}
function writeSse(res, event, data) { if (event) res.write(`event: ${event}\n`); res.write(`data: ${JSON.stringify(data)}\n\n`);}
function sendAnthropicStream(res, openaiResp) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' }); const choice = openaiResp.choices[0]; const msg = choice.message || {}; const message = toAnthropicResponse(openaiResp); const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0; writeSse(res, 'message_start', { type: 'message_start', message: { ...message, content: [] } });
// Anthropic-compatible clients expect a tool turn to be made of tool_use // content blocks. If we emit DeepSeek reasoning as a text block before the // tool_use block, some agents treat the turn as a normal text answer and do // not execute the tool. Keep tool streaming clean: tool_use blocks only. if (hasToolCalls) { msg.tool_calls.forEach((tc, i) => { writeSse(res, 'content_block_start', { type: 'content_block_start', index: i, content_block: { type: 'tool_use', id: tc.id, name: tc.function.name, input: {} } }); writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: i, delta: { type: 'input_json_delta', partial_json: tc.function.arguments || '{}' } }); writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: i }); }); writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: message.usage }); } else { if (msg.reasoning_content) { writeSse(res, 'content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }); writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: `[reasoning]\n${msg.reasoning_content}\n[/reasoning]\n` } }); writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: 0 }); } const offset = msg.reasoning_content ? 1 : 0; writeSse(res, 'content_block_start', { type: 'content_block_start', index: offset, content_block: { type: 'text', text: '' } }); const text = msg.content || ''; for (let i = 0; i < text.length; i += 80) { writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: offset, delta: { type: 'text_delta', text: text.substring(i, i + 80) } }); } writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: offset }); writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: message.usage }); } writeSse(res, 'message_stop', { type: 'message_stop' }); res.end();}
function toResponsesResponse(openaiResp) { const choice = openaiResp.choices[0]; const msg = choice.message || {}; const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0; const output = []; if (!hasToolCalls && msg.reasoning_content) { output.push({ id: 'rs_' + Date.now(), type: 'reasoning', summary: [{ type: 'summary_text', text: msg.reasoning_content }] }); } if (hasToolCalls) { for (const tc of msg.tool_calls) { output.push({ type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}' }); } } else { output.push({ id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: msg.content || '', annotations: [] }] }); } return { id: openaiResp.id.replace(/^ds-/, 'resp_'), object: 'response', created_at: openaiResp.created, status: 'completed', model: openaiResp.model, output, output_text: msg.content || '', usage: { input_tokens: openaiResp.usage?.prompt_tokens || 0, output_tokens: openaiResp.usage?.completion_tokens || 0, total_tokens: openaiResp.usage?.total_tokens || 0, output_tokens_details: { reasoning_tokens: openaiResp.usage?.completion_tokens_details?.reasoning_tokens || 0 }, }, watermark: FORGETMEAI_WATERMARK, };}
function sendResponsesStream(res, openaiResp) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' }); const response = toResponsesResponse(openaiResp); const choice = openaiResp.choices[0]; const msg = choice.message || {}; const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0; writeSse(res, 'response.created', { type: 'response.created', response: { ...response, status: 'in_progress', output: [] } }); writeSse(res, 'response.in_progress', { type: 'response.in_progress', response: { ...response, status: 'in_progress', output: [] } }); let outputIndex = 0; if (!hasToolCalls && msg.reasoning_content) { const reasoningItem = { id: 'rs_' + Date.now(), type: 'reasoning', summary: [], status: 'completed' }; writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...reasoningItem, status: 'in_progress' } }); writeSse(res, 'response.reasoning_summary_text.delta', { type: 'response.reasoning_summary_text.delta', output_index: outputIndex, summary_index: 0, delta: msg.reasoning_content }); writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item: { ...reasoningItem, summary: [{ type: 'summary_text', text: msg.reasoning_content }] } }); outputIndex++; } if (hasToolCalls) { msg.tool_calls.forEach((tc) => { const item = { type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}', status: 'completed' }; writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, arguments: '', status: 'in_progress' } }); writeSse(res, 'response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', output_index: outputIndex, item_id: item.id, delta: item.arguments }); writeSse(res, 'response.function_call_arguments.done', { type: 'response.function_call_arguments.done', output_index: outputIndex, item_id: item.id, arguments: item.arguments }); writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item }); outputIndex++; }); } else { const text = msg.content || ''; const item = { id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text, annotations: [] }] }; writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, status: 'in_progress', content: [] } }); writeSse(res, 'response.content_part.added', { type: 'response.content_part.added', output_index: outputIndex, content_index: 0, item_id: item.id, part: { type: 'output_text', text: '', annotations: [] } }); for (let i = 0; i < text.length; i += 80) { writeSse(res, 'response.output_text.delta', { type: 'response.output_text.delta', output_index: outputIndex, content_index: 0, item_id: item.id, delta: text.substring(i, i + 80) }); } writeSse(res, 'response.output_text.done', { type: 'response.output_text.done', output_index: outputIndex, content_index: 0, item_id: item.id, text }); writeSse(res, 'response.content_part.done', { type: 'response.content_part.done', output_index: outputIndex, content_index: 0, item_id: item.id, part: item.content[0] }); writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item }); } writeSse(res, 'response.completed', { type: 'response.completed', response }); res.write('data: [DONE]\n\n'); res.end();}
function sendOpenAIStream(res, openaiResp) { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' }); const choice = openaiResp.choices[0]; const msg = choice.message || {}; const id = openaiResp.id; const created = openaiResp.created; const model = openaiResp.model; const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0; if (!hasToolCalls && msg.reasoning_content) { for (let i = 0; i < msg.reasoning_content.length; i += 50) { const chunk = msg.reasoning_content.substring(i, i + 50); res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { reasoning_content: chunk }, finish_reason: null }] })}\n\n`); } } if (hasToolCalls) { res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { role: 'assistant', content: null, tool_calls: msg.tool_calls }, finish_reason: null }] })}\n\n`); res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] })}\n\ndata: [DONE]\n\n`); } else { for (let i = 0; i < (msg.content || '').length; i += 50) { const chunk = msg.content.substring(i, i + 50); res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { content: chunk }, finish_reason: null }] })}\n\n`); } res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`); } res.end();}
function storeHistory(agentId, prompt, content, toolCall) { const session = getOrCreateAgentSession(agentId); const assistantResponse = toolCall ? `TOOL_CALL: ${toolCall.name}\narguments: ${toolCall.arguments}` : content; // Save last 500 chars of the prompt for history context const shortPrompt = prompt.length > 500 ? '...' + prompt.substring(prompt.length - 500) : prompt; session.history.push({ user: shortPrompt, assistant: assistantResponse }); while (session.history.length > MAX_HISTORY_LENGTH) session.history.shift(); let historyChars = session.history.reduce((sum, e) => sum + e.user.length + e.assistant.length, 0); while (historyChars > MAX_HISTORY_CHARS && session.history.length > 1) { const removed = session.history.shift(); historyChars -= removed.user.length + removed.assistant.length; }}
// Extract MEDIA: paths from tool results that contain screenshot pathsfunction extractScreenshotPaths(messages) { const paths = []; const fs = require('fs'); for (const msg of messages) { if (msg.role === 'tool' && msg.content) { // Look for screenshot_path or path fields in JSON tool results // These come DIRECTLY from browser_vision — always the real path const pngMatch = msg.content.match(/["'](screenshot_path|path)["']\s*:\s*["']([^"']+\.(?:png|jpg|jpeg|webp|gif))["']/i); if (pngMatch) { const filePath = pngMatch[2]; if (filePath.startsWith('/') && fs.existsSync(filePath)) { paths.push(`MEDIA:${filePath}`); } } // Also catch plain MEDIA: tags const mediaMatch = msg.content.match(/MEDIA:(\S+)/g); if (mediaMatch) { for (const tag of mediaMatch) { const extractedPath = tag.replace(/^MEDIA:/, ''); if (fs.existsSync(extractedPath) && !paths.includes(tag)) { paths.push(tag); } } } } // Check user/assistant messages for paths mentioned in conversation text // Only include if the file ACTUALLY EXISTS (DeepSeek hallucinates paths) if ((msg.role === 'user' || msg.role === 'assistant') && msg.content) { const content = typeof msg.content === 'string' ? msg.content : ''; const pathRegex = /(\/[^\s<>"']+\.(?:png|jpg|jpeg|webp|gif))/gi; let match; while ((match = pathRegex.exec(content)) !== null) { const filePath = match[1]; if (filePath.startsWith('/') && fs.existsSync(filePath) && !paths.includes(`MEDIA:${filePath}`)) { paths.push(`MEDIA:${filePath}`); } } } } return paths;}
function formatMessages(messages, tools) { let systemPrompt = ''; for (const msg of messages) { if (msg.role === 'system' && msg.content) { systemPrompt += msg.content + '\n'; } } systemPrompt += formatToolDefinitions(tools);
// Build full conversation history for DeepSeek's context let conversation = ''; for (const msg of messages) { if (msg.role === 'system') continue; // already in systemPrompt if (msg.role === 'user' && msg.content) { conversation += `User: ${msg.content}\n\n`; } else if (msg.role === 'assistant') { if (msg.tool_calls && msg.tool_calls.length > 0) { // This was a tool call response from a previous turn for (const tc of msg.tool_calls) { conversation += `Assistant: TOOL_CALL: ${tc.function.name}\narguments: ${tc.function.arguments}\n\n`; } } else if (msg.content) { conversation += `Assistant: ${msg.content}\n\n`; } } else if (msg.role === 'tool' && msg.content) { // Tool execution result — send back to DeepSeek as context const truncated = msg.content.length > 8000 ? msg.content.substring(0, 8000) + '\n...[truncated]' : msg.content; conversation += `[Tool Result]\n${truncated}\n\n`; } } // The last user message + full conversation context return { prompt: conversation.trim(), systemPrompt: systemPrompt.trim() };}
// === HTTP Server ===const server = http.createServer(async (req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
// Health check if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/health')) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'ok', service: 'FreeDeepseekAPI', watermark: FORGETMEAI_WATERMARK, models: SUPPORTED_MODEL_IDS, unsupported_models: Object.keys(MODEL_CONFIGS).filter(id => !MODEL_CONFIGS[id].supported), agents: sessions.size, config_ready: hasAuthConfig() })); return; }
// Models: OpenAI-compatible list exposes only aliases verified to work through this proxy. if (req.method === 'GET' && url.pathname === '/v1/models') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ object: 'list', data: SUPPORTED_MODEL_IDS.map(id => ({ id, object: 'model', created: 1700000000, owned_by: 'deepseek-web', real_model: MODEL_CONFIGS[id].real_model, capabilities: MODEL_CONFIGS[id].capabilities })) })); return; }
// Full mapping, including Web models observed but not currently usable through the direct API. if (req.method === 'GET' && (url.pathname === '/v1/model-capabilities' || url.pathname === '/api/model-capabilities')) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ object: 'model_capabilities', watermark: FORGETMEAI_WATERMARK, data: ALL_MODEL_CAPABILITIES })); return; }
// Sessions status if (req.method === 'GET' && url.pathname === '/v1/sessions') { const agentList = []; for (const [agentId, session] of sessions) { agentList.push({ agent: agentId, session_id: session.id, message_count: session.messageCount, history_size: session.history.length, age_min: session.createdAt ? Math.round((Date.now() - session.createdAt) / 60000) : 0, }); } res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ agents: agentList, total: agentList.length })); return; }
// Reset session for a specific agent (or all if no agent specified) if (req.method === 'POST' && url.pathname === '/reset-session') { const agentId = url.searchParams.get('agent') || 'default'; if (agentId === 'all') { const count = sessions.size; sessions.clear(); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'all_sessions_cleared', count })); return; } const session = sessions.get(agentId); if (!session) { res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: `No session for agent: ${agentId}` })); return; } const historyCount = session.history.length; const historyPreview = session.history.map(e => e.user.substring(0, 40)).join(' | '); session.id = null; session.parentMessageId = null; session.createdAt = null; session.messageCount = 0; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'session_reset', agent: agentId, history_preserved: historyCount, history: historyPreview })); return; }
const apiMode = url.pathname === '/v1/messages' ? 'anthropic' : (url.pathname === '/v1/responses' ? 'responses' : 'openai'); const acceptedPostPaths = ['/v1/chat/completions', '/v1/messages', '/v1/responses']; if (req.method !== 'POST' || !acceptedPostPaths.includes(url.pathname)) { res.writeHead(404); res.end('Not found'); return; }
let body = ''; req.on('data', chunk => body += chunk); req.on('end', async () => { try { const rawParams = JSON.parse(body || '{}'); const params = normalizeApiParams(rawParams, apiMode); const messages = params.messages || []; const tools = params.tools || []; const stream = params.stream === true; const requestedModel = String(params.model || 'deepseek-chat').toLowerCase(); if (!isKnownModel(requestedModel)) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message: `Unknown model: ${requestedModel}`, type: 'invalid_model', supported_models: SUPPORTED_MODEL_IDS, model_capabilities_url: '/v1/model-capabilities' } })); return; } if (!isSupportedModel(requestedModel)) { const cfg = resolveModelConfig(requestedModel); res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message: `${requestedModel} is not currently supported through this DeepSeek Web API path`, type: 'unsupported_model', model: requestedModel, real_model: cfg.real_model, reason: cfg.unavailable_reason, capabilities: cfg.capabilities, supported_models: SUPPORTED_MODEL_IDS } })); return; } // Use remote IP for session isolation (local gets 'dev-agent', external per-IP) const remoteAddr = req.socket.remoteAddress || 'unknown'; const requestedSession = req.headers['x-agent-session'] || params.session || params.user; const agentId = requestedSession ? String(requestedSession) : ((remoteAddr === '127.0.0.1' || remoteAddr === '::1' || remoteAddr === '::ffff:127.0.0.1') ? 'dev-agent' : remoteAddr); const agentTag = `[${agentId}]`; const { prompt, systemPrompt } = formatMessages(messages, tools);
const session = getOrCreateAgentSession(agentId);
// Build history prefix if starting fresh let historyPrefix = ''; if (!session.id && session.history.length > 0) { historyPrefix = '[Previous conversation]\n'; for (const exchange of session.history) { historyPrefix += `User: ${exchange.user}\nAssistant: ${exchange.assistant}\n\n`; } historyPrefix += '[Continue from here]\n\n'; }
const fullPrompt = systemPrompt ? `${systemPrompt}\n\n${historyPrefix}${prompt}` : `${historyPrefix}${prompt}`;
const startTime = Date.now(); const { resp: dsResp } = await askDeepSeekStream(fullPrompt, agentId, requestedModel);
// Process streaming response from DeepSeek — returns { content, reasoningContent, messageId, finishReason } async function readDeepSeekResponse(readable) { let buffer = ''; let lastPath = null; const fragments = []; let fullContent = ''; let reasoningContent = ''; let newMessageId = null; let finishReason = null; let modelError = null;
const rebuildFragmentText = () => { const responseText = fragments .filter(f => f && f.type === 'RESPONSE' && typeof f.content === 'string') .map(f => f.content) .join(''); const thinkText = fragments .filter(f => f && (f.type === 'THINK' || f.type === 'REASONING') && typeof f.content === 'string') .map(f => f.content) .join(''); if (responseText) fullContent = responseText; reasoningContent = thinkText; };
const appendFragments = (value) => { const incoming = Array.isArray(value) ? value : [value]; for (const fragment of incoming) { if (fragment && typeof fragment === 'object') fragments.push({ ...fragment }); } rebuildFragmentText(); };
for await (const chunk of readable) { buffer += new TextDecoder().decode(chunk, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { if (line.startsWith('data: ')) { try { const d = JSON.parse(line.slice(6)); if (d.response_message_id !== undefined && !newMessageId) newMessageId = d.response_message_id; if (d.type === 'error' || d.finish_reason || d.content) { modelError = { type: d.type || 'error', content: d.content || '', finish_reason: d.finish_reason || null }; if (d.finish_reason) finishReason = d.finish_reason; } if (d.p !== undefined) lastPath = d.p; if (d.v && typeof d.v === 'object' && d.v.response) { if (d.v.response.message_id !== undefined) { newMessageId = d.v.response.message_id; } if (d.v.response.content !== undefined) { fullContent = d.v.response.content; } if (Array.isArray(d.v.response.fragments)) { fragments.length = 0; appendFragments(d.v.response.fragments); } if (d.v.response.finish_reason !== undefined) { finishReason = d.v.response.finish_reason; } } if (lastPath === 'response/fragments' && d.v !== undefined) { appendFragments(d.v); } if (lastPath === 'response/fragments/-1/content' && d.v !== undefined && typeof d.v !== 'object') { if (fragments.length > 0) { const lastFragment = fragments[fragments.length - 1]; lastFragment.content = `${lastFragment.content || ''}${d.v}`; rebuildFragmentText(); } } if (lastPath === 'response/content' && d.v !== undefined && typeof d.v !== 'object') { fullContent += d.v; } if (lastPath === 'response/finish_reason' && d.v !== undefined) { finishReason = d.v; } if (lastPath === 'response/status' && d.v !== undefined && d.v !== 'FINISHED') { finishReason = d.v; } } catch (e) { } } } }
if (newMessageId) { session.parentMessageId = newMessageId; session.messageCount++; } else { console.log(`${agentTag} WARNING: could not extract message_id`); }
return { content: fullContent, reasoningContent, messageId: newMessageId, finishReason, modelError }; }
let { content: fullContent, reasoningContent, finishReason, modelError } = await readDeepSeekResponse(dsResp.body); fullContent = sanitizeContent(fullContent); reasoningContent = sanitizeContent(reasoningContent || ''); const elapsed = Date.now() - startTime; console.log(`${agentTag} Got ${fullContent.length} chars (+${reasoningContent.length} reasoning chars) in ${elapsed}ms (msg#${session.messageCount})`);
if ((!fullContent || fullContent.trim().length === 0) && modelError) { res.writeHead(502, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message: modelError.content || 'DeepSeek returned an error without content', type: modelError.finish_reason || modelError.type || 'deepseek_model_error', model: requestedModel, real_model: resolveModelConfig(requestedModel).real_model } })); return; }
// Empty response — retry loop with fresh sessions let retryAttempt = 0; const MAX_RETRIES = 10; while (!fullContent || fullContent.trim().length === 0) { retryAttempt++; if (retryAttempt > MAX_RETRIES) { console.log(`${agentTag} Empty after ${MAX_RETRIES} retries. Giving up.`); res.writeHead(502, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message: `DeepSeek returned empty content after ${MAX_RETRIES} retries`, type: 'empty_response', agent: agentId, session_id: session.id, message_count: session.messageCount, history_length: session.history.length, retry_attempts: retryAttempt - 1, } })); return; } console.log(`${agentTag} Empty response (msg#${session.messageCount}, retry ${retryAttempt}/${MAX_RETRIES}). Resetting session...`); session.id = null; session.parentMessageId = null; session.createdAt = null; session.messageCount = 0; // Brief delay before retry to let DeepSeek breathe await new Promise(r => setTimeout(r, Math.min(1000 * retryAttempt, 5000))); const { resp: retryResp } = await askDeepSeekStream(fullPrompt, agentId, requestedModel); const retryResult = await readDeepSeekResponse(retryResp.body); const retryContent = retryResult && retryResult.content ? sanitizeContent(retryResult.content) : ''; const retryReasoning = retryResult && retryResult.reasoningContent ? sanitizeContent(retryResult.reasoningContent) : ''; if (retryContent && retryContent.trim().length > 0) { console.log(`${agentTag} Retry ${retryAttempt} succeeded`); fullContent = retryContent; reasoningContent = retryReasoning; } }
// Auto-continuation: if finish_reason is 'length' or content is very long (>25000 chars), // send a continuation request to get the rest of the response let continuationRounds = 0; const MAX_CONTINUATION = 2; while ((finishReason === 'length' || fullContent.length > 25000) && continuationRounds < MAX_CONTINUATION) { continuationRounds++; console.log(`${agentTag} Response ${fullContent.length} chars (finish=${finishReason}). Auto-continuing (${continuationRounds}/${MAX_CONTINUATION})...`); await new Promise(r => setTimeout(r, 500)); const { resp: contResp } = await askDeepSeekStream('continue', agentId, requestedModel); const contResult = await readDeepSeekResponse(contResp.body); const contContent = contResult && contResult.content ? sanitizeContent(contResult.content) : ''; const contReasoning = contResult && contResult.reasoningContent ? sanitizeContent(contResult.reasoningContent) : ''; if (contContent && contContent.trim().length > 0 && !contContent.includes('I am an AI')) { fullContent += '\n' + contContent; if (contReasoning) reasoningContent += (reasoningContent ? '\n' : '') + contReasoning; finishReason = contResult.finishReason; console.log(`${agentTag} Continuation added ${contContent.length} chars (total: ${fullContent.length})`); } else { console.log(`${agentTag} Continuation returned nothing useful, stopping`); break; } }
let toolCall = parseToolCall(fullContent); // Retry if TOOL_CALL was found but JSON was truncated/invalid if (!toolCall && /TOOL_CALL:\s*\w/i.test(fullContent)) { console.log(`${agentTag} TOOL_CALL detected but JSON invalid/truncated (${fullContent.length} chars). Retrying with stricter prompt...`); session.id = null; session.parentMessageId = null; session.createdAt = null; session.messageCount = 0; await new Promise(r => setTimeout(r, 1000)); const strictPrompt = fullPrompt + '\n\n[STRICT INSTRUCTION] Your previous response had a TOOL_CALL but the arguments were too long and got cut off. Keep the arguments SHORT — no large file contents. Just use a minimal example or reference the file by name. Output ONLY: TOOL_CALL: <function>\narguments: <short JSON>'; const { resp: retryResp2 } = await askDeepSeekStream(strictPrompt, agentId, requestedModel); const retryResult2 = await readDeepSeekResponse(retryResp2.body); const retryContent2 = retryResult2 && retryResult2.content ? sanitizeContent(retryResult2.content) : ''; if (retryContent2 && retryContent2.trim()) { const retryTc = parseToolCall(retryContent2); if (retryTc) { console.log(`${agentTag} Retry with strict prompt succeeded: ${retryTc.name}`); fullContent = retryContent2; reasoningContent = retryResult2.reasoningContent ? sanitizeContent(retryResult2.reasoningContent) : ''; toolCall = retryTc; } else { console.log(`${agentTag} Retry still has broken JSON. Sending as text.`); reasoningContent = retryResult2.reasoningContent ? sanitizeContent(retryResult2.reasoningContent) : reasoningContent; } } } // Check if any tool results in the current conversation contained a screenshot path. // If so, and the response doesn't already have MEDIA:, inject it so the gateway // delivers the file to Telegram. if (!fullContent.includes('MEDIA:')) { const screenshotPaths = extractScreenshotPaths(messages); if (screenshotPaths.length > 0) { fullContent += '\n\n' + screenshotPaths.join('\n'); console.log(`${agentTag} Injected MEDIA paths into response: ${screenshotPaths.join(', ')}`); } }
storeHistory(agentId, prompt, fullContent, toolCall);
const openaiResponse = toolCall ? buildToolCallResponse(toolCall, requestedModel, fullPrompt, reasoningContent) : buildTextResponse(fullContent, fullPrompt, requestedModel, reasoningContent);
if (stream) { if (apiMode === 'anthropic') { sendAnthropicStream(res, openaiResponse); } else if (apiMode === 'responses') { sendResponsesStream(res, openaiResponse); } else { sendOpenAIStream(res, openaiResponse); } console.log(`${agentTag} Streamed ${apiMode} (tool=${!!toolCall}) in ${elapsed}ms`); } else { res.writeHead(200, { 'Content-Type': 'application/json' }); if (apiMode === 'anthropic') { res.end(JSON.stringify(toAnthropicResponse(openaiResponse))); } else if (apiMode === 'responses') { res.end(JSON.stringify(toResponsesResponse(openaiResponse))); } else { res.end(JSON.stringify(openaiResponse)); } console.log(`${agentTag} Response ${apiMode} (tool=${!!toolCall}, ${elapsed}ms, ${fullContent.length} chars)`); } } catch (e) { console.log('[DS-API] Error:', e.message); res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message: e.message, type: 'server_error' } })); } });});
async function runAuthScript() { const script = path.join(__dirname, 'scripts', 'deepseek_chrome_auth.js'); const result = spawnSync(process.execPath, [script], { stdio: 'inherit', env: process.env }); loadDeepSeekConfig({ fatal: false }); return result.status === 0 && hasAuthConfig();}
function printStatus() { console.log(`\n${formatWatermark()}`); console.log(`Auth: ${hasAuthConfig() ? '✅ OK' : '❌ не найден deepseek-auth.json'}`); console.log(`Auth file: ${DS_CONFIG_PATH}`); console.log(`Рабочие модели: ${SUPPORTED_MODEL_IDS.join(', ')}`); console.log('Нерабочие/скрытые aliases: ' + Object.keys(MODEL_CONFIGS).filter(id => !MODEL_CONFIGS[id].supported).join(', ')); console.log('Capabilities: GET /v1/model-capabilities');}
async function showStartupMenu() { if (isTruthy(process.env.SKIP_ACCOUNT_MENU) || isTruthy(process.env.NON_INTERACTIVE)) { if (!hasAuthConfig()) loadDeepSeekConfig({ fatal: true }); return true; } while (true) { printStatus(); console.log('\n=== Меню ==='); console.log(`ForgetMeAI: ${FORGETMEAI_WATERMARK}`); console.log('1 - Авторизоваться / обновить DeepSeek login'); console.log('2 - Показать модели и статусы'); console.log('3 - Запустить прокси (по умолчанию)'); console.log('4 - Выход'); let choice = await prompt('Ваш выбор (Enter = 3): '); if (!choice) choice = '3'; if (choice === '1') { await runAuthScript(); } else if (choice === '2') { console.log(JSON.stringify(ALL_MODEL_CAPABILITIES, null, 2)); await prompt('\nНажмите Enter, чтобы вернуться в меню...'); } else if (choice === '3') { if (!hasAuthConfig()) { console.log('Нужен deepseek-auth.json. Запустите пункт 1.'); continue; } return true; } else if (choice === '4') { return false; } }}
async function main() { printBanner(); const shouldStart = await showStartupMenu(); if (!shouldStart) process.exit(0); server.listen(PORT, HOST, () => { console.log(`[DS-API] Server on http://${HOST}:${PORT} (multi-agent sessions enabled)`); console.log(`[DS-API] ${formatWatermark()}`); console.log('[DS-API] POST /v1/chat/completions (OpenAI Chat Completions, stream=true|false)'); console.log('[DS-API] POST /v1/messages — Anthropic Messages shim for Claude Code'); console.log('[DS-API] POST /v1/responses — OpenAI Responses API shim'); console.log('[DS-API] GET /v1/models — supported OpenAI-compatible models'); console.log('[DS-API] GET /v1/model-capabilities — real model mapping and capabilities'); console.log('[DS-API] GET /v1/sessions — list active agent sessions'); console.log('[DS-API] POST /reset-session?agent=<id> — reset agent session'); console.log('[DS-API] POST /reset-session?agent=all — reset ALL sessions'); });}
main().catch(err => { console.error('[DS-API] FATAL:', err); process.exit(1); });79 unmodified lines8081828384858687888 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813979 unmodified linesawait BroadcastPresence(boardId);}public async Task SendSignal(string boardId, string receiverUserId, string type, string data){if (string.IsNullOrEmpty(boardId)) return;if (BoardPresences.TryGetValue(boardId, out var groupPresence)){var receiverConns = groupPresence.Values8 unmodified linespublic async Task SendCursor(string boardId, double x, double y){if (string.IsNullOrEmpty(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("CursorMoved", Context.ConnectionId, CurrentUserId.ToString(), x, y);}public async Task MoveNode(string boardId, string nodeId, double x, double y){if (string.IsNullOrEmpty(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeMoved", nodeId, x, y);}public async Task UpdateNodeData(string boardId, string nodeId, string newDataJson){if (string.IsNullOrEmpty(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeDataUpdated", nodeId, newDataJson);}public async Task AddNode(string boardId, string nodeJson){if (string.IsNullOrEmpty(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeAdded", nodeJson);}public async Task DeleteNode(string boardId, string nodeId){if (string.IsNullOrEmpty(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeDeleted", nodeId);}public async Task AddEdge(string boardId, string edgeJson){if (string.IsNullOrEmpty(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("EdgeAdded", edgeJson);}public async Task DeleteEdge(string boardId, string edgeId){if (string.IsNullOrEmpty(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("EdgeDeleted", edgeId);}79 unmodified lines8081828384858687888990919293948 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414579 unmodified linesawait BroadcastPresence(boardId);}// Only connections that passed the access check in JoinBoard may broadcast to a boardprivate bool HasJoined(string boardId) =>!string.IsNullOrEmpty(boardId)&& BoardPresences.TryGetValue(boardId, out var presences)&& presences.ContainsKey(Context.ConnectionId);public async Task SendSignal(string boardId, string receiverUserId, string type, string data){if (!HasJoined(boardId)) return;if (BoardPresences.TryGetValue(boardId, out var groupPresence)){var receiverConns = groupPresence.Values8 unmodified linespublic async Task SendCursor(string boardId, double x, double y){if (!HasJoined(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("CursorMoved", Context.ConnectionId, CurrentUserId.ToString(), x, y);}public async Task MoveNode(string boardId, string nodeId, double x, double y){if (!HasJoined(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeMoved", nodeId, x, y);}public async Task UpdateNodeData(string boardId, string nodeId, string newDataJson){if (!HasJoined(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeDataUpdated", nodeId, newDataJson);}public async Task AddNode(string boardId, string nodeJson){if (!HasJoined(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeAdded", nodeJson);}public async Task DeleteNode(string boardId, string nodeId){if (!HasJoined(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("NodeDeleted", nodeId);}public async Task AddEdge(string boardId, string edgeJson){if (!HasJoined(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("EdgeAdded", edgeJson);}public async Task DeleteEdge(string boardId, string edgeId){if (!HasJoined(boardId)) return;await Clients.OthersInGroup(boardId).SendAsync("EdgeDeleted", edgeId);}
37 unmodified lines38394041424344454647484947 unmodified lines9798991001011021031041051061072 unmodified lines11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617716 unmodified lines19419519619719819933 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542555 unmodified lines26126226326426526626737 unmodified linesbuilder.Services.AddScoped<IEdgeService, EdgeService>();builder.Services.AddScoped<IHabitService, HabitService>();builder.Services.AddScoped<ISyncService, SyncService>();builder.Services.AddScoped<IAIService, AIService>();builder.Services.AddScoped<IPaymentService, PaymentService>();builder.Services.AddScoped<IAchievementService, AchievementService>();// --- Singletons ---builder.Services.AddSingleton<IGeminiBridgeManager, GeminiBridgeManager>();// --- SignalR ---builder.Services.AddSignalR(options =>47 unmodified linesbuilder.Services.AddOpenApi();// --- CORS ---builder.Services.AddCors(options =>{options.AddPolicy("AllowAll", policy =>{policy.SetIsOriginAllowed(origin => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();2 unmodified linesvar app = builder.Build();// --- Start FreeDeepseekAPI proxy in background ---try{var dsPath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "FreeDeepseekAPI", "server.js");if (System.IO.File.Exists(dsPath)){System.Console.WriteLine($"[Main] Starting FreeDeepseekAPI proxy: node {dsPath}...");var processStartInfo = new System.Diagnostics.ProcessStartInfo{FileName = "node",Arguments = dsPath,UseShellExecute = false,CreateNoWindow = true,RedirectStandardOutput = true,RedirectStandardError = true};processStartInfo.EnvironmentVariables["NON_INTERACTIVE"] = "1";processStartInfo.EnvironmentVariables["PORT"] = "9655";// Forward any relevant DeepSeek vars to the proxy processforeach (var key in new[] { "DEEPSEEK_TOKEN", "DEEPSEEK_COOKIE", "DEEPSEEK_HIF_DLIQ", "DEEPSEEK_HIF_LEIM", "DEEPSEEK_WASM_URL" }){var val = System.Environment.GetEnvironmentVariable(key);if (!string.IsNullOrEmpty(val)){processStartInfo.EnvironmentVariables[key] = val;}}var dsProcess = System.Diagnostics.Process.Start(processStartInfo);if (dsProcess != null){// Read output in background to prevent hangingSystem.Threading.Tasks.Task.Run(() => {try {while (!dsProcess.StandardOutput.EndOfStream) {var line = dsProcess.StandardOutput.ReadLine();System.Console.WriteLine($"[DeepSeekProxy-Out] {line}");}} catch {}});System.Threading.Tasks.Task.Run(() => {try {while (!dsProcess.StandardError.EndOfStream) {var line = dsProcess.StandardError.ReadLine();System.Console.WriteLine($"[DeepSeekProxy-Err] {line}");}} catch {}});System.Console.WriteLine("[Main] FreeDeepseekAPI proxy started successfully.");}}else{System.Console.WriteLine($"[Main] FreeDeepseekAPI proxy file not found at: {dsPath}");}}catch (System.Exception ex){System.Console.WriteLine($"[Main] Failed to start FreeDeepseekAPI proxy: {ex.Message}");}// --- Auto-migrate database and seed ---using (var scope = app.Services.CreateScope()){16 unmodified lines}}// Emergency Cleanup & Optimization before Migrationtry{33 unmodified linesdb.Database.SetCommandTimeout(120); // 2 minutesdb.Database.Migrate();// Manual lock clearing — use actual DB path from configtry {var connStrForLock = builder.Configuration.GetConnectionString("DefaultConnection") ?? "";var lockMatch = System.Text.RegularExpressions.Regex.Match(connStrForLock, @"Data Source=(.+?)(?:;|$)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);string dbPath = lockMatch.Success ? lockMatch.Groups[1].Value.Trim() : "/app/taskflow.db";if (File.Exists(dbPath)) {foreach (var s in new[] { "-wal", "-shm", "-journal" }) {if (File.Exists(dbPath + s)) {File.Delete(dbPath + s);Console.WriteLine($"[Startup] Cleared stale lock file: {dbPath + s}");}}}} catch (Exception ex) {Console.WriteLine($"[Startup] Lock clearing failed: {ex.Message}");}// Auto-seed achievementsvar achievementService = scope.ServiceProvider.GetRequiredService<IAchievementService>();achievementService.SeedAchievementsAsync().Wait();5 unmodified linesapp.MapOpenApi();}app.UseCors("AllowAll");// Note: UseHttpsRedirection is intentionally omitted.// HF Space handles TLS termination at the proxy level; the app runs on plain HTTP internally.37 unmodified lines38394041424344454647 unmodified lines9495969798991001011021031041051061071081091102 unmodified lines11311411511611711816 unmodified lines13513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516633 unmodified lines2002012022032042055 unmodified lines21121221321421521621737 unmodified linesbuilder.Services.AddScoped<IEdgeService, EdgeService>();builder.Services.AddScoped<IHabitService, HabitService>();builder.Services.AddScoped<ISyncService, SyncService>();builder.Services.AddScoped<IPaymentService, PaymentService>();builder.Services.AddScoped<IAchievementService, AchievementService>();builder.Services.AddScoped<ITemplateService, TemplateService>();// --- SignalR ---builder.Services.AddSignalR(options =>47 unmodified linesbuilder.Services.AddOpenApi();// --- CORS ---// Only the web client may call the API from a browser. Override with Cors__AllowedOrigins__0=... env vars.var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>()?? new[] { "https://danildrotik-flowweb.hf.space", "http://localhost:5173", "http://127.0.0.1:5173" };builder.Services.AddCors(options =>{options.AddPolicy("WebClient", policy =>{var isDevelopment = builder.Environment.IsDevelopment();policy.SetIsOriginAllowed(origin =>allowedOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase) ||(isDevelopment && Uri.TryCreate(origin, UriKind.Absolute, out var uri) && uri.IsLoopback)).AllowAnyMethod().AllowAnyHeader().AllowCredentials();2 unmodified linesvar app = builder.Build();// --- Auto-migrate database and seed ---using (var scope = app.Services.CreateScope()){16 unmodified lines}}// Clear stale SQLite lock files left by a crashed container. This must run before the// first connection is opened: deleting the journal of an open database corrupts it.if (!string.IsNullOrEmpty(connStr)){var lockMatch = System.Text.RegularExpressions.Regex.Match(connStr, @"Data Source=(.+?)(?:;|$)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);var dbPath = lockMatch.Success ? lockMatch.Groups[1].Value.Trim() : null;if (dbPath != null && File.Exists(dbPath)){foreach (var suffix in new[] { "-wal", "-shm", "-journal" }){try{if (File.Exists(dbPath + suffix)){File.Delete(dbPath + suffix);Console.WriteLine($"[Startup] Cleared stale lock file: {dbPath + suffix}");}}catch (Exception ex){Console.WriteLine($"[Startup] Lock clearing failed: {ex.Message}");}}}}// Emergency Cleanup & Optimization before Migrationtry{33 unmodified linesdb.Database.SetCommandTimeout(120); // 2 minutesdb.Database.Migrate();// Auto-seed achievementsvar achievementService = scope.ServiceProvider.GetRequiredService<IAchievementService>();achievementService.SeedAchievementsAsync().Wait();5 unmodified linesapp.MapOpenApi();}app.UseCors("WebClient");// Note: UseHttpsRedirection is intentionally omitted.// HF Space handles TLS termination at the proxy level; the app runs on plain HTTP internally.
18 unmodified lines1920212223242526272829303118 unmodified lines"Google": {"ClientId": "181646538378-kbabhecenasb8pca0uh95prhk8b0vrbr.apps.googleusercontent.com"},"OpenAI": {"ApiKey": ""},"Gemini": {"ApiKey": "AQ.Ab8RN6KQ0DG4-5LtLVuMUvpOtKcK9nKX6CqyOXue_BVUL0bIeA","Model": "gemini-2.5-flash"},"Stripe": {"SecretKey": "","WebhookSecret": ""18 unmodified lines19202122232418 unmodified lines"Google": {"ClientId": "181646538378-kbabhecenasb8pca0uh95prhk8b0vrbr.apps.googleusercontent.com"},"Stripe": {"SecretKey": "","WebhookSecret": ""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473import sysimport jsonimport timeimport osimport signalimport datetimeimport reimport argparseimport threadingimport base64import ioimport queueimport ctypes
# Win32 ConstantsSW_HIDE = 0SW_SHOW = 5SW_MINIMIZE = 6SW_RESTORE = 9
# Add the current directory to sys.path to ensure we can import modules if neededsys.path.append(os.path.dirname(os.path.abspath(__file__)))
from camoufox.sync_api import Camoufox
def log_message(message): """Log messages to stderr and bridge_log.txt.""" timestamp = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]") log_line = f"{timestamp} [BRIDGE] {message}\n" sys.stderr.write(log_line) sys.stderr.flush() try: with open("bridge_log.txt", "a", encoding="utf-8") as f: f.write(log_line) except: pass
def signal_handler(sig, frame): log_message("Received signal to exit.") sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)signal.signal(signal.SIGTERM, signal_handler)
# --- Browser Logic (Adapted from gemini_agent.py) ---
def get_message_count(page) -> int: return page.locator('div[id^="model-response-message-content"]').count()
def wait_for_new_response(page, previous_count: int, msg_id: str, timeout: int = 120): log_message(f"Waiting for new response (prev count: {previous_count})...") start = time.time() new_msg_detected = False new_count = previous_count # 1. Wait for the new message container to appear while time.time() - start < timeout: try: current_count = get_message_count(page) if current_count > previous_count: new_msg_detected = True new_count = current_count log_message(f"New message detected! Count: {previous_count} -> {current_count}") break except Exception: pass time.sleep(1) if not new_msg_detected: log_message(f"TIMEOUT: No new message after {timeout}s") return False, new_count log_message("Monitoring generation for streaming...") stable_checks = 0 last_len = 0 last_text = "" # 2. Monitor for changes (Streaming) while time.time() - start < timeout: try: # Check for generating indicators (stop button, progress bar, or sparkle) # If these are gone, generation is likely done. generating_selectors = [ '.mat-mdc-progress-bar', 'mat-progress-bar', '.loading-indicator', 'button[aria-label*="Stop"]', 'button[aria-label*="stop"]', 'button[aria-label*="Cancel"]', 'button[aria-label*="cancel"]', 'img[src*="sparkle_thinking"]', '.sparkle-loading' ] is_generating = False for sel in generating_selectors: try: if page.locator(sel).first.is_visible(): is_generating = True break except: pass
els = page.locator('div[id^="model-response-message-content"]').all() if not els: time.sleep(0.5) continue # Get current text of the *last* message curr_text = els[-1].inner_text() curr_len = len(curr_text) # Emit partial if changed if curr_len > last_len: if curr_text.startswith(last_text): diff = curr_text[len(last_text):] if diff: print(json.dumps({ "type": "partial_response", "id": msg_id, "content": diff }), flush=True) last_text = curr_text last_len = curr_len stable_checks = 0 # Reset stability if text changed if not is_generating: # Double check stability if curr_len > 0 and curr_len == last_len: stable_checks += 1 # Robust warm-up protection: if length is very small (< 150 chars), require # 12 stable checks (6.0 seconds of no change) before cut-off to allow the AI to think and start streaming. # Otherwise, require 3 stable checks (1.5 seconds of no change) to finish. required_checks = 12 if curr_len < 150 else 3 if stable_checks >= required_checks: log_message(f"Generation complete (indicator gone). Length: {curr_len}") return True, new_count else: # Still generating, but maybe paused? if curr_len > 0 and curr_len == last_len: stable_checks += 1 if stable_checks >= 10: # 5 seconds of no change even if indicator present? pass else: stable_checks = 0 # Text changing, so active except Exception as e: pass time.sleep(0.5) # Poll every 500ms return True, new_count
def get_specific_response(page, index: int) -> str: try: els = page.locator('div[id^="model-response-message-content"]').all() if len(els) > index: return els[index].inner_text().strip() elif len(els) > 0: return els[-1].inner_text().strip() except: pass return ""
def send_gemini_message(page, message: str) -> bool: try: page.bring_to_front() # Find input box input_el = page.locator('div[contenteditable="true"]').first if not input_el.is_visible(): input_el = page.locator('textarea').first if input_el.is_visible(timeout=5000): input_el.click() time.sleep(0.5) input_el.fill(message) time.sleep(0.5) # Find send button send_btn = page.locator('button[aria-label*="Send"], mat-icon[data-mat-icon-name="send"]').first if send_btn.is_visible(): send_btn.click() else: input_el.press("Enter") return True else: log_message("Input element not found!") except Exception as e: log_message(f"Send failed: {e}") return False
def send_gemini_image_message(page, message: str, image_path: str) -> (bool, str): try: page.bring_to_front() # Check if "Upload files" is already visible (menu open from previous attempt?) upload_btn = page.locator('button[data-test-id="local-images-files-uploader-button"]').first if not upload_btn.is_visible(): upload_btn = page.locator('div.menu-text:has-text("Upload files")').first
if not upload_btn.is_visible(): log_message("Upload button not visible, looking for Plus button...") plus_btn = page.locator('button[aria-label*="Upload files"], button[aria-label*="Add"], button:has(mat-icon[fonticon="add"]), button:has(mat-icon[data-mat-icon-name="add"]), button:has(mat-icon[fonticon="add_circle"]), button:has(mat-icon[fonticon="add_2"]), button:has(mat-icon[data-mat-icon-name="add_2"])').first if plus_btn.is_visible(): log_message(f"Clicking Plus button: {plus_btn.get_attribute('aria-label')}") plus_btn.click() time.sleep(1.0) # Wait for menu animation # Re-check upload button upload_btn = page.locator('button[data-test-id="local-images-files-uploader-button"]').first if not upload_btn.is_visible(): upload_btn = page.locator('div.menu-text:has-text("Upload files")').first else: log_message("Plus button not found with standard selectors.") return False, "Plus/Add button not found" if upload_btn.is_visible(): log_message("Clicking Upload files button...") try: with page.expect_file_chooser(timeout=5000) as fc_info: upload_btn.click() except Exception as e: return False, f"Timeout waiting for file chooser: {e}" file_chooser = fc_info.value log_message(f"Uploading image: {image_path}") file_chooser.set_files(image_path) # Wait for upload to process. time.sleep(4)
if send_gemini_message(page, message): return True, "" else: return False, "Failed to send text message after upload" else: log_message("Upload files button not found in menu!") return False, "Upload files button not found in menu"
except Exception as e: log_message(f"Send image failed: {e}") return False, f"Exception: {str(e)}"
def get_active_page(context, url="https://gemini.google.com/app"): """Finds an existing Gemini page or creates a new one and ensures it's navigated.""" page = None for p in context.pages: try: if not p.is_closed(): page = p break except: continue if not page: log_message("No active page found, creating new one...") page = context.new_page() page.add_init_script("Object.defineProperty(document, 'hidden', { get: () => false });")
try: current_url = page.url # If we are on Google login or account setup, DO NOT redirect/reload! if "accounts.google" in current_url or "google.com/accounts" in current_url: return page
if url not in current_url: log_message(f"Navigating to {url} (current: {current_url})...") page.goto(url, timeout=60000) time.sleep(2) except Exception as e: log_message(f"Navigation check/error: {e}") return page
def stdin_reader(q): """Reads stdin lines in a background thread and puts them in a queue.""" while True: line = sys.stdin.readline() if not line: q.put(None) break q.put(line)
def set_browser_window_visibility(visible): """Находит окно браузера и скрывает/показывает его через Win32 API""" if sys.platform != 'win32': return log_message(f"Starting window search (visibility={visible})...") found_count = [0]
def foreach_window(hwnd, lParam): class_name = ctypes.create_unicode_buffer(256) ctypes.windll.user32.GetClassNameW(hwnd, class_name, 256) length = ctypes.windll.user32.GetWindowTextLengthW(hwnd) title = "" if length > 0: buff = ctypes.create_unicode_buffer(length + 1) ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1) title = buff.value is_browser = (class_name.value == "MozillaWindowClass") if is_browser: log_message(f"Checking window: '{title}' (Class: {class_name.value})") is_match = any(term in title for term in ["Gemini", "Camoufox", "Firefox", "Nightly", "Google"]) if is_match or not title: log_message(f"Found target browser window! Setting visibility: {visible}") found_count[0] += 1 if visible: log_message(f"Restoring window: '{title}'") ctypes.windll.user32.ShowWindow(hwnd, SW_RESTORE) ctypes.windll.user32.SetForegroundWindow(hwnd) else: log_message(f"Minimizing window: '{title}'") ctypes.windll.user32.ShowWindow(hwnd, SW_MINIMIZE) return True
enum_proc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)(foreach_window) ctypes.windll.user32.EnumWindows(enum_proc, 0) log_message(f"Window search finished. Found {found_count[0]} windows.")
def main(): parser = argparse.ArgumentParser() parser.add_argument("--headless", action="store_true", help="Run in headless mode") args_parsed = parser.parse_args()
# Use the profile folder relative to this script's directory profile_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gemini_profile_bridge") headless_to_use = args_parsed.headless log_message(f"Starting Gemini Bridge (Headless: {headless_to_use})...") if not os.path.exists(profile_path): os.makedirs(profile_path, exist_ok=True) log_message(f"Initializing Camoufox with profile: {profile_path}")
try: with Camoufox( headless=headless_to_use, persistent_context=True, user_data_dir=profile_path, viewport={'width': 1280, 'height': 1000}, humanize=False, geoip=False, args=["--no-sandbox", "--disable-setuid-sandbox"] ) as context: page = get_active_page(context) if "accounts.google.com" in page.url: log_message("WARNING: Login required! Please log in manually in the browser window.") log_message("Browser ready. Waiting for input on stdin...") print(json.dumps({"type": "ready"}), flush=True) input_queue = queue.Queue() threading.Thread(target=stdin_reader, args=(input_queue,), daemon=True).start() def delayed_hide(): time.sleep(3) log_message("Attempting initial window hide...") set_browser_window_visibility(False) if not headless_to_use: threading.Thread(target=delayed_hide, daemon=True).start()
# Screenshots disabled while True: try: while not input_queue.empty(): line = input_queue.get_nowait() if line is None: return line = line.strip() if not line: continue log_message(f"Received JSON: {line[:50]}...") try: data = json.loads(line) msg_type = data.get("type") if msg_type == "prompt" or msg_type == "prompt_with_image": prompt, msg_id = data.get("content"), data.get("id") image_path = data.get("image_path") is_new_chat = data.get("new_chat", False) page = get_active_page(context)
if is_new_chat: log_message("Request implies new chat. Searching for 'New Chat' button...") try: new_chat_btn = page.locator('side-nav-action-button[data-test-id="new-chat-button"]').first if new_chat_btn.is_visible(): log_message("Clicking 'New Chat' button.") new_chat_btn.click() # Wait for old messages to disappear log_message("Waiting for old messages to clear...") start_wait = time.time() while time.time() - start_wait < 10: if get_message_count(page) == 0: break time.sleep(0.5) time.sleep(1.0) # Additional settling time else: log_message("'New Chat' button not visible. Assuming already on a fresh chat.") except Exception as e: log_message(f"Warning: Failed to click new chat: {e}")
initial_count = get_message_count(page) sent, error_msg = False, "" if msg_type == "prompt_with_image" and image_path: sent, error_msg = send_gemini_image_message(page, prompt, image_path) else: sent = send_gemini_message(page, prompt) if not sent: error_msg = "Failed to send"
if sent: success, new_count = wait_for_new_response(page, initial_count, msg_id, timeout=120) if success: resp = get_specific_response(page, new_count - 1) print(json.dumps({"type": "response", "id": msg_id, "status": "success", "content": resp}), flush=True) else: print(json.dumps({"type": "response", "id": msg_id, "status": "timeout"}), flush=True) else: print(json.dumps({"type": "response", "id": msg_id, "status": "error", "error": error_msg}), flush=True) elif msg_type == "click": x, y = data.get("x"), data.get("y") if x is not None and y is not None: p = get_active_page(context) if p: p.bring_to_front() p.mouse.move(x, y) time.sleep(0.1) p.mouse.click(x, y) log_message(f"Hover & Click at {x}, {y}")
elif msg_type == "set_visibility": visible = data.get("visible", True) set_browser_window_visibility(visible) log_message(f"Window visibility set to: {visible}")
elif msg_type == "ping": print(json.dumps({"type": "pong"}), flush=True) elif msg_type == "exit": return except Exception as inner_e: log_message(f"Msg error: {inner_e}")
# Periodic screenshot disabled
time.sleep(0.1) except Exception as e: log_message(f"Loop error: {e}") time.sleep(1) except Exception as e: log_message(f"Fatal Error: {e}") print(json.dumps({"type": "fatal_error", "error": str(e)}), flush=True) sys.exit(1)
if __name__ == "__main__": main()