danylokhodus commited on
Commit
d4f2db0
·
1 Parent(s): a09c97b

feat: integrate FreeDeepseekAPI background proxy and routing in AIService

Browse files
Dockerfile CHANGED
@@ -19,8 +19,18 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
19
  WORKDIR /app
20
  ENV ASPNETCORE_URLS=http://+:7860
21
  EXPOSE 7860
 
 
 
 
 
 
 
22
  # Copy published .NET app
23
  COPY --from=build /app/publish .
24
 
 
 
 
25
  # Set entrypoint
26
  ENTRYPOINT ["dotnet", "FlowAPI.dll"]
 
19
  WORKDIR /app
20
  ENV ASPNETCORE_URLS=http://+:7860
21
  EXPOSE 7860
22
+
23
+ # Install Node.js 20
24
+ RUN apt-get update && apt-get install -y curl && \
25
+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
26
+ apt-get install -y nodejs && \
27
+ rm -rf /var/lib/apt/lists/*
28
+
29
  # Copy published .NET app
30
  COPY --from=build /app/publish .
31
 
32
+ # Copy FreeDeepseekAPI proxy
33
+ COPY FlowAPI/FreeDeepseekAPI ./FreeDeepseekAPI
34
+
35
  # Set entrypoint
36
  ENTRYPOINT ["dotnet", "FlowAPI.dll"]
FlowAPI.Application/Services/AIService.cs CHANGED
@@ -122,6 +122,13 @@ namespace FlowAPI.Application.Services
122
 
123
  private async Task<string> CallGeminiApiAsync(object[] contents, string? systemInstruction = null, string? responseSchemaJson = null)
124
  {
 
 
 
 
 
 
 
125
  var apiKey = _config["Gemini:ApiKey"] ?? Environment.GetEnvironmentVariable("GEMINI_API_KEY");
126
  if (string.IsNullOrEmpty(apiKey))
127
  {
@@ -764,5 +771,117 @@ namespace FlowAPI.Application.Services
764
  public List<GeminiNode> NewNodes { get; set; } = new();
765
  public List<GeminiEdge> NewEdges { get; set; } = new();
766
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767
  }
768
  }
 
122
 
123
  private async Task<string> CallGeminiApiAsync(object[] contents, string? systemInstruction = null, string? responseSchemaJson = null)
124
  {
125
+ var deepseekToken = Environment.GetEnvironmentVariable("DEEPSEEK_TOKEN");
126
+ var deepseekCookie = Environment.GetEnvironmentVariable("DEEPSEEK_COOKIE");
127
+ if (!string.IsNullOrEmpty(deepseekToken) && !string.IsNullOrEmpty(deepseekCookie))
128
+ {
129
+ return await CallDeepSeekProxyApiAsync(contents, systemInstruction, responseSchemaJson);
130
+ }
131
+
132
  var apiKey = _config["Gemini:ApiKey"] ?? Environment.GetEnvironmentVariable("GEMINI_API_KEY");
133
  if (string.IsNullOrEmpty(apiKey))
134
  {
 
771
  public List<GeminiNode> NewNodes { get; set; } = new();
772
  public List<GeminiEdge> NewEdges { get; set; } = new();
773
  }
774
+
775
+ private async Task<string> CallDeepSeekProxyApiAsync(object[] contents, string? systemInstruction = null, string? responseSchemaJson = null)
776
+ {
777
+ var messages = new List<object>();
778
+
779
+ if (responseSchemaJson != null)
780
+ {
781
+ 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.";
782
+ if (!string.IsNullOrEmpty(systemInstruction))
783
+ {
784
+ systemInstruction += schemaInstructions;
785
+ }
786
+ else
787
+ {
788
+ systemInstruction = schemaInstructions;
789
+ }
790
+ }
791
+
792
+ if (!string.IsNullOrEmpty(systemInstruction))
793
+ {
794
+ messages.Add(new { role = "system", content = systemInstruction });
795
+ }
796
+
797
+ foreach (var content in contents)
798
+ {
799
+ try
800
+ {
801
+ var json = JsonSerializer.Serialize(content);
802
+ using var doc = JsonDocument.Parse(json);
803
+ var root = doc.RootElement;
804
+
805
+ string role = "user";
806
+ if (root.TryGetProperty("role", out var roleProp))
807
+ {
808
+ var rStr = roleProp.GetString();
809
+ role = rStr == "model" ? "assistant" : (rStr == "system" ? "system" : "user");
810
+ }
811
+
812
+ string text = string.Empty;
813
+ if (root.TryGetProperty("parts", out var partsProp) && partsProp.ValueKind == JsonValueKind.Array && partsProp.GetArrayLength() > 0)
814
+ {
815
+ var firstPart = partsProp[0];
816
+ if (firstPart.TryGetProperty("text", out var textProp))
817
+ {
818
+ text = textProp.GetString() ?? string.Empty;
819
+ }
820
+ }
821
+
822
+ if (!string.IsNullOrEmpty(text))
823
+ {
824
+ messages.Add(new { role = role, content = text });
825
+ }
826
+ }
827
+ catch (Exception ex)
828
+ {
829
+ Console.WriteLine($"[DeepSeekProxy] Error mapping message: {ex.Message}");
830
+ }
831
+ }
832
+
833
+ var requestBody = new
834
+ {
835
+ model = "deepseek-chat",
836
+ messages = messages,
837
+ stream = false
838
+ };
839
+
840
+ using var httpClient = new HttpClient();
841
+ httpClient.Timeout = TimeSpan.FromMinutes(5);
842
+ var jsonPayload = JsonSerializer.Serialize(requestBody);
843
+
844
+ using var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
845
+
846
+ HttpResponseMessage? response = null;
847
+ string responseString = string.Empty;
848
+
849
+ int maxRetries = 3;
850
+ int delayMs = 1500;
851
+
852
+ for (int attempt = 1; attempt <= maxRetries; attempt++)
853
+ {
854
+ response = await httpClient.PostAsync("http://localhost:9655/v1/chat/completions", requestContent);
855
+ responseString = await response.Content.ReadAsStringAsync();
856
+
857
+ if (response.IsSuccessStatusCode)
858
+ {
859
+ break;
860
+ }
861
+
862
+ int statusCode = (int)response.StatusCode;
863
+ if (attempt < maxRetries && (statusCode == 503 || statusCode == 429 || statusCode == 500 || statusCode == 502))
864
+ {
865
+ await Task.Delay(delayMs * attempt);
866
+ continue;
867
+ }
868
+
869
+ throw new Exception($"DeepSeek Proxy API error (Status {response.StatusCode}): {responseString}");
870
+ }
871
+
872
+ using var resDoc = JsonDocument.Parse(responseString);
873
+ var textResponse = resDoc.RootElement
874
+ .GetProperty("choices")[0]
875
+ .GetProperty("message")
876
+ .GetProperty("content")
877
+ .GetString();
878
+
879
+ if (string.IsNullOrEmpty(textResponse))
880
+ {
881
+ throw new Exception("Empty response received from DeepSeek Proxy API.");
882
+ }
883
+
884
+ return textResponse;
885
+ }
886
  }
887
  }
FlowAPI/FlowAPI.csproj CHANGED
@@ -20,4 +20,10 @@
20
  <ProjectReference Include="..\FlowAPI.Infrastructure\FlowAPI.Infrastructure.csproj" />
21
  </ItemGroup>
22
 
 
 
 
 
 
 
23
  </Project>
 
20
  <ProjectReference Include="..\FlowAPI.Infrastructure\FlowAPI.Infrastructure.csproj" />
21
  </ItemGroup>
22
 
23
+ <ItemGroup>
24
+ <None Update="FreeDeepseekAPI\**">
25
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
26
+ </None>
27
+ </ItemGroup>
28
+
29
  </Project>
FlowAPI/FreeDeepseekAPI/package.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "name": "free-deepseek-api",
3
+ "version": "0.1.0",
4
+ "main": "server.js",
5
+ "type": "commonjs"
6
+ }
FlowAPI/FreeDeepseekAPI/server.js ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ /**
3
+ * OpenAI-compatible API server wrapping DeepSeek Web API
4
+ * Supports BOTH streaming (SSE) and non-streaming modes
5
+ * Includes tool calling: injects tool definitions into system prompt,
6
+ * parses LLM text responses for TOOL_CALL patterns, returns OpenAI tool_calls format.
7
+ *
8
+ * Per-agent sessions: each unique `user` field gets its own DeepSeek web session.
9
+ * Auto-reset: sessions reset when message chain > 50 messages or age > 2 hours.
10
+ * Listens on 0.0.0.0:9655
11
+ */
12
+
13
+ const http = require('http');
14
+ const fs = require('fs');
15
+ const os = require('os');
16
+ const path = require('path');
17
+ const readline = require('readline');
18
+ const { spawnSync } = require('child_process');
19
+
20
+ const SERVER_HOST = os.hostname(); // Dynamic hostname detection
21
+ const SERVER_PUBLIC_IP = (() => {
22
+ try {
23
+ const interfaces = os.networkInterfaces();
24
+ for (const name of Object.keys(interfaces)) {
25
+ for (const iface of interfaces[name]) {
26
+ if (iface.family === 'IPv4' && !iface.internal) return iface.address;
27
+ }
28
+ }
29
+ } catch (e) {}
30
+ return 'localhost';
31
+ })();
32
+
33
+ const FORGETMEAI_WATERMARK = 't.me/forgetmeai';
34
+ const PORT = Number(process.env.PORT || 9655);
35
+ const HOST = process.env.HOST || '0.0.0.0';
36
+ function formatWatermark(prefix = 'ForgetMeAI') { return `${prefix}: ${FORGETMEAI_WATERMARK}`; }
37
+ function printBanner() {
38
+ console.log(`
39
+ ███████ ██████ ███████ ███████ ██████ ███████ ███████ ███████ ██ ██
40
+ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
41
+ █████ ██████ █████ █████ ██ ██ █████ █████ █████ █████
42
+ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
43
+ ██ ██ ██ ███████ ███████ ██████ ███████ ███████ ███████ ██ ██
44
+
45
+ FreeDeepseekAPI — API-прокси для DeepSeek Web Chat
46
+ ${formatWatermark()}
47
+ `);
48
+ }
49
+ function prompt(question) {
50
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
51
+ return new Promise(resolve => rl.question(question, ans => { rl.close(); resolve(ans); }));
52
+ }
53
+ function isTruthy(value) { return typeof value === 'string' && ['1','true','yes','on'].includes(value.trim().toLowerCase()); }
54
+
55
+ // === Per-Agent Session Store ===
56
+ const sessions = new Map(); // keyed by agent ID (from `user` field)
57
+ const MAX_HISTORY_LENGTH = 15;
58
+ const MAX_HISTORY_CHARS = 10000;
59
+ const MAX_MESSAGE_DEPTH = 100; // auto-reset after this many messages
60
+ const SESSION_TTL_MS = 2 * 60 * 60 * 1000; // 2 hours
61
+
62
+ // === DeepSeek Web API Config — loaded from external config file ===
63
+ const DS_CONFIG_PATH = process.env.DEEPSEEK_AUTH_PATH || path.join(__dirname, 'deepseek-auth.json');
64
+ let DS_CONFIG = {};
65
+ let BASE_HEADERS = {};
66
+ function buildBaseHeaders() {
67
+ return {
68
+ "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",
69
+ "x-client-platform": "web",
70
+ "x-client-version": "2.0.0",
71
+ "x-client-locale": "ru",
72
+ "x-client-timezone-offset": "14400",
73
+ "x-app-version": "2.0.0",
74
+ "Authorization": `Bearer ${DS_CONFIG.token || ''}`,
75
+ "x-hif-dliq": DS_CONFIG.hif_dliq || '',
76
+ "x-hif-leim": DS_CONFIG.hif_leim || '',
77
+ "Origin": "https://chat.deepseek.com",
78
+ "Referer": "https://chat.deepseek.com/",
79
+ "Cookie": DS_CONFIG.cookie || '',
80
+ "Content-Type": "application/json",
81
+ };
82
+ }
83
+ function loadDeepSeekConfig({ fatal = true } = {}) {
84
+ try {
85
+ if (fs.existsSync(DS_CONFIG_PATH)) {
86
+ const raw = fs.readFileSync(DS_CONFIG_PATH, 'utf8');
87
+ DS_CONFIG = JSON.parse(raw);
88
+ console.log(`[DS-API] Loaded auth config from ${DS_CONFIG_PATH}`);
89
+ } else {
90
+ DS_CONFIG = {
91
+ token: process.env.DEEPSEEK_TOKEN || '',
92
+ cookie: process.env.DEEPSEEK_COOKIE || '',
93
+ hif_dliq: process.env.DEEPSEEK_HIF_DLIQ || '',
94
+ hif_leim: process.env.DEEPSEEK_HIF_LEIM || '',
95
+ wasmUrl: process.env.DEEPSEEK_WASM_URL || 'https://fe-static.deepseek.com/chat/static/sha3_wasm_bg.7b9ca65ddd.wasm',
96
+ };
97
+ console.log(`[DS-API] Loaded auth config from process.env`);
98
+ }
99
+ BASE_HEADERS = buildBaseHeaders();
100
+ return true;
101
+ } catch (e) {
102
+ DS_CONFIG = {};
103
+ BASE_HEADERS = buildBaseHeaders();
104
+ if (fatal) {
105
+ console.error(`[DS-API] FATAL: Could not load auth config: ${e.message}`);
106
+ process.exit(1);
107
+ }
108
+ return false;
109
+ }
110
+ }
111
+ function hasAuthConfig() { return !!(DS_CONFIG.token && DS_CONFIG.cookie); }
112
+ loadDeepSeekConfig({ fatal: false });
113
+
114
+ function createSession() {
115
+ return {
116
+ id: null,
117
+ parentMessageId: null,
118
+ createdAt: null,
119
+ messageCount: 0,
120
+ history: [],
121
+ };
122
+ }
123
+
124
+ function getOrCreateAgentSession(agentId) {
125
+ if (!sessions.has(agentId)) {
126
+ sessions.set(agentId, createSession());
127
+ }
128
+ return sessions.get(agentId);
129
+ }
130
+
131
+ async function solvePOW(challenge) {
132
+ const resp = await fetch(DS_CONFIG.wasmUrl);
133
+ const wasmBytes = await resp.arrayBuffer();
134
+ const mod = await WebAssembly.instantiate(wasmBytes, { wbg: {} });
135
+ const e = mod.instance.exports;
136
+ const encoder = new TextEncoder();
137
+ const prefix = challenge.salt + '_' + challenge.expire_at + '_';
138
+ const cBytes = encoder.encode(challenge.challenge);
139
+ const pBytes = encoder.encode(prefix);
140
+ const cP = e.__wbindgen_export_0(cBytes.length, 1) >>> 0;
141
+ const pP = e.__wbindgen_export_0(pBytes.length, 1) >>> 0;
142
+ new Uint8Array(e.memory.buffer, cP, cBytes.length).set(cBytes);
143
+ new Uint8Array(e.memory.buffer, pP, pBytes.length).set(pBytes);
144
+ const sp = e.__wbindgen_add_to_stack_pointer(-16);
145
+ e.wasm_solve(sp, cP, cBytes.length, pP, pBytes.length, challenge.difficulty);
146
+ const dv = new DataView(e.memory.buffer);
147
+ const code = dv.getInt32(sp, true);
148
+ const ans = dv.getFloat64(sp + 8, true);
149
+ e.__wbindgen_add_to_stack_pointer(16);
150
+ if (code === 0 || !Number.isFinite(ans) || ans <= 0) throw new Error('POW failed');
151
+ return Math.floor(ans);
152
+ }
153
+
154
+ const MODEL_CONFIGS = {
155
+ // DeepSeek Web real model_type: default / UI name: "Быстрый".
156
+ // Public model family: DeepSeek-V3.2-Exp chat mode (fast, no visible reasoning).
157
+ 'deepseek-chat': {
158
+ model_type: 'default', thinking_enabled: false, search_enabled: false,
159
+ real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
160
+ capabilities: { reasoning: false, web_search: false, files: true },
161
+ supported: true,
162
+ },
163
+ 'deepseek-v3': {
164
+ model_type: 'default', thinking_enabled: false, search_enabled: false,
165
+ real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
166
+ capabilities: { reasoning: false, web_search: false, files: true },
167
+ supported: true,
168
+ },
169
+ 'deepseek-default': {
170
+ model_type: 'default', thinking_enabled: false, search_enabled: false,
171
+ real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
172
+ capabilities: { reasoning: false, web_search: false, files: true },
173
+ supported: true,
174
+ },
175
+ // Same DeepSeek Web default model, but with thinking_enabled=true. UI exposes it as thinking/reasoning mode.
176
+ 'deepseek-reasoner': {
177
+ model_type: 'default', thinking_enabled: true, search_enabled: false,
178
+ real_model: 'DeepSeek-V4-Flash thinking mode (DeepSeek Web “Быстрый” + thinking_enabled)',
179
+ capabilities: { reasoning: true, web_search: false, files: true },
180
+ supported: true,
181
+ },
182
+ 'deepseek-r1': {
183
+ model_type: 'default', thinking_enabled: true, search_enabled: false,
184
+ real_model: 'DeepSeek-V4-Flash thinking mode; R1-compatible alias, not a separate R1 model_type in current Web API',
185
+ capabilities: { reasoning: true, web_search: false, files: true },
186
+ supported: true,
187
+ },
188
+ 'deepseek-chat-search': {
189
+ model_type: 'default', thinking_enabled: false, search_enabled: true,
190
+ real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search',
191
+ capabilities: { reasoning: false, web_search: true, files: true },
192
+ supported: true,
193
+ },
194
+ 'deepseek-default-search': {
195
+ model_type: 'default', thinking_enabled: false, search_enabled: true,
196
+ real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search',
197
+ capabilities: { reasoning: false, web_search: true, files: true },
198
+ supported: true,
199
+ },
200
+ 'deepseek-reasoner-search': {
201
+ model_type: 'default', thinking_enabled: true, search_enabled: true,
202
+ real_model: 'DeepSeek-V4-Flash thinking mode + web search',
203
+ capabilities: { reasoning: true, web_search: true, files: true },
204
+ supported: true,
205
+ },
206
+ 'deepseek-r1-search': {
207
+ model_type: 'default', thinking_enabled: true, search_enabled: true,
208
+ real_model: 'DeepSeek-V4-Flash thinking mode + web search; R1-compatible alias',
209
+ capabilities: { reasoning: true, web_search: true, files: true },
210
+ supported: true,
211
+ },
212
+ // DeepSeek Web UI name: “Эксперт”. Requires current web client headers (x-client-version=2.0.0).
213
+ 'deepseek-expert': {
214
+ model_type: 'expert', thinking_enabled: false, search_enabled: false,
215
+ real_model: 'DeepSeek Web “Эксперт” (limited resources)',
216
+ capabilities: { reasoning: false, web_search: false, files: false },
217
+ supported: true,
218
+ },
219
+ 'deepseek-v4-pro': {
220
+ model_type: 'expert', thinking_enabled: true, search_enabled: false,
221
+ real_model: 'DeepSeek Web “Эксперт” + thinking mode (exposed as deepseek-v4-pro alias)',
222
+ capabilities: { reasoning: true, web_search: false, files: false },
223
+ supported: true,
224
+ },
225
+ 'deepseek-expert-search': {
226
+ model_type: 'expert', thinking_enabled: false, search_enabled: true,
227
+ real_model: 'DeepSeek Web “Эксперт” + search requested, but Expert has search_feature=null in remote config',
228
+ capabilities: { reasoning: false, web_search: false, files: false },
229
+ supported: false,
230
+ unavailable_reason: 'Expert mode is rejected; remote config says search is not available for Expert.',
231
+ },
232
+ 'deepseek-vision': {
233
+ model_type: 'vision', thinking_enabled: false, search_enabled: false,
234
+ real_model: 'DeepSeek Web “Распознавание” / image understanding beta',
235
+ capabilities: { reasoning: false, web_search: false, files: true, vision: true },
236
+ supported: false,
237
+ unavailable_reason: 'Current Web API returns: Vision is temporarily unavailable (backend_err_by_model).',
238
+ },
239
+ };
240
+
241
+ const SUPPORTED_MODEL_IDS = Object.keys(MODEL_CONFIGS).filter(id => MODEL_CONFIGS[id].supported);
242
+ const ALL_MODEL_CAPABILITIES = Object.fromEntries(Object.entries(MODEL_CONFIGS).map(([id, cfg]) => [id, {
243
+ id,
244
+ real_model: cfg.real_model,
245
+ model_type: cfg.model_type,
246
+ thinking_enabled: cfg.thinking_enabled,
247
+ search_enabled: cfg.search_enabled,
248
+ capabilities: cfg.capabilities,
249
+ supported: cfg.supported,
250
+ unavailable_reason: cfg.unavailable_reason || null,
251
+ }]));
252
+
253
+ function resolveModelConfig(model) {
254
+ const requested = String(model || 'deepseek-chat').toLowerCase();
255
+ return MODEL_CONFIGS[requested] || MODEL_CONFIGS['deepseek-chat'];
256
+ }
257
+ function isKnownModel(model) { return Object.prototype.hasOwnProperty.call(MODEL_CONFIGS, String(model || '').toLowerCase()); }
258
+ function isSupportedModel(model) { return resolveModelConfig(model).supported === true; }
259
+
260
+ async function askDeepSeekStream(prompt, agentId, model = 'deepseek-default') {
261
+ const modelCfg = resolveModelConfig(model);
262
+ const session = getOrCreateAgentSession(agentId);
263
+ const agentTag = `[${agentId}]`;
264
+
265
+ // Auto-reset on deep message chain
266
+ if (session.id && session.messageCount >= MAX_MESSAGE_DEPTH) {
267
+ console.log(`${agentTag} Session ${session.id} hit ${session.messageCount} messages. Auto-resetting.`);
268
+ session.id = null;
269
+ session.parentMessageId = null;
270
+ session.createdAt = null;
271
+ session.messageCount = 0;
272
+ // History preserved for context injection
273
+ }
274
+
275
+ // Reset expired sessions (DeepSeek web sessions last ~1-2 hours)
276
+ if (session.id && session.createdAt && (Date.now() - session.createdAt > SESSION_TTL_MS)) {
277
+ console.log(`${agentTag} Session ${session.id} expired (age: ${Math.round((Date.now() - session.createdAt) / 60000)}min). Creating new...`);
278
+ session.id = null;
279
+ session.parentMessageId = null;
280
+ session.createdAt = null;
281
+ session.messageCount = 0;
282
+ }
283
+
284
+ const cr = await fetch('https://chat.deepseek.com/api/v0/chat/create_pow_challenge', {
285
+ method: 'POST', headers: BASE_HEADERS,
286
+ body: JSON.stringify({ target_path: '/api/v0/chat/completion' })
287
+ });
288
+ const chalJson = JSON.parse(await cr.text());
289
+ const challenge = chalJson.data.biz_data.challenge;
290
+ const answer = await solvePOW(challenge);
291
+
292
+ if (!session.id) {
293
+ const sr = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', {
294
+ method: 'POST', headers: BASE_HEADERS, body: '{}'
295
+ });
296
+ const sessionData = await sr.json();
297
+ session.id = sessionData.data.biz_data.chat_session?.id || sessionData.data.biz_data.id;
298
+ session.parentMessageId = null;
299
+ session.createdAt = Date.now();
300
+ session.messageCount = 0;
301
+ console.log(`${agentTag} Created new session: ${session.id}`);
302
+ } else {
303
+ console.log(`${agentTag} Reusing session: ${session.id} (parent: ${session.parentMessageId}, msg#${session.messageCount})`);
304
+ }
305
+
306
+ const powB64 = Buffer.from(JSON.stringify({
307
+ algorithm: challenge.algorithm, challenge: challenge.challenge,
308
+ salt: challenge.salt, answer: answer,
309
+ signature: challenge.signature, target_path: '/api/v0/chat/completion'
310
+ })).toString('base64');
311
+ const resp = await fetch('https://chat.deepseek.com/api/v0/chat/completion', {
312
+ method: 'POST',
313
+ headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': powB64 },
314
+ body: JSON.stringify({
315
+ chat_session_id: session.id,
316
+ parent_message_id: session.parentMessageId,
317
+ model_type: modelCfg.model_type,
318
+ prompt: prompt, ref_file_ids: [],
319
+ thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled,
320
+ action: null, preempt: false,
321
+ })
322
+ });
323
+
324
+ // If session expired, reset and retry once
325
+ if (resp.status !== 200) {
326
+ const errText = await resp.text();
327
+ console.log(`${agentTag} Session error (${resp.status}): ${errText.substring(0, 100)}`);
328
+ if (resp.status === 400 || resp.status === 404 || resp.status === 500) {
329
+ console.log(`${agentTag} Session ${session.id} expired. Creating new session...`);
330
+ session.id = null;
331
+ session.parentMessageId = null;
332
+ session.createdAt = null;
333
+ session.messageCount = 0;
334
+
335
+ const sr2 = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', {
336
+ method: 'POST', headers: BASE_HEADERS, body: '{}'
337
+ });
338
+ const sessionData2 = await sr2.json();
339
+ session.id = sessionData2.data.biz_data.chat_session?.id || sessionData2.data.biz_data.id;
340
+ session.parentMessageId = null;
341
+ session.createdAt = Date.now();
342
+ console.log(`${agentTag} Created new session: ${session.id}`);
343
+
344
+ const newPowB64 = Buffer.from(JSON.stringify({
345
+ algorithm: challenge.algorithm, challenge: challenge.challenge,
346
+ salt: challenge.salt, answer: answer,
347
+ signature: challenge.signature, target_path: '/api/v0/chat/completion'
348
+ })).toString('base64');
349
+ const resp2 = await fetch('https://chat.deepseek.com/api/v0/chat/completion', {
350
+ method: 'POST',
351
+ headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': newPowB64 },
352
+ body: JSON.stringify({
353
+ chat_session_id: session.id,
354
+ parent_message_id: null,
355
+ model_type: modelCfg.model_type,
356
+ prompt: prompt, ref_file_ids: [],
357
+ thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled,
358
+ action: null, preempt: false,
359
+ })
360
+ });
361
+ return { resp: resp2, agentId };
362
+ }
363
+ }
364
+
365
+ return { resp, agentId };
366
+ }
367
+
368
+ // === Tool Calling Support ===
369
+
370
+ function formatToolDefinitions(tools) {
371
+ if (!tools || tools.length === 0) return '';
372
+ let text = '\n\n--- TOOL REQUEST SYSTEM ---\n';
373
+ text += 'You are an AI that ONLY REASONS and REQUESTS tool executions. You do NOT run any commands yourself.\n';
374
+ text += 'When you need data from the local server, REQUEST exactly one tool call. Prefer strict JSON:\n';
375
+ text += '{"tool_call":{"name":"<function_name>","arguments":{...}}}\n\n';
376
+ text += 'Legacy format is also accepted: TOOL_CALL: <function_name>\narguments: <JSON arguments>\n\n';
377
+ 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';
378
+ text += 'RULES:\n';
379
+ text += '1. You ONLY output the tool request — you never run anything yourself\n';
380
+ text += '2. Do NOT simulate, guess, or fabricate command output — wait for the actual result\n';
381
+ text += '3. The tool runs on ' + SERVER_HOST + ' (' + SERVER_PUBLIC_IP + '), the local server — NOT on DeepSeek\n';
382
+ text += '4. After the tool executes, the result will be sent to you as a new user/tool message\n';
383
+ text += '5. Never add explanation before or after the tool request when requesting a tool\n';
384
+ text += '6. Keep arguments compact. Do not include large file contents unless the tool schema requires it.\n\n';
385
+ text += 'Available functions:\n';
386
+ for (const tool of tools) {
387
+ if (tool.type === 'function' && tool.function) {
388
+ const fn = tool.function;
389
+ text += `\n## ${fn.name}\n`;
390
+ text += `${fn.description || ''}\n`;
391
+ if (fn.parameters) {
392
+ text += `Parameters: ${JSON.stringify(fn.parameters)}\n`;
393
+ }
394
+ }
395
+ }
396
+ text += '\n--- END TOOL REQUEST SYSTEM ---\n';
397
+ text += '\nREMEMBER: Request tools only with strict JSON or TOOL_CALL legacy format. Never simulate results.';
398
+ return text;
399
+ }
400
+
401
+ function extractBalancedJsonAt(text, startIndex) {
402
+ let braceDepth = 0;
403
+ let inString = false;
404
+ let escape = false;
405
+ for (let i = startIndex; i < text.length; i++) {
406
+ const ch = text[i];
407
+ if (escape) { escape = false; continue; }
408
+ if (ch === '\\' && inString) { escape = true; continue; }
409
+ if (ch === '"') { inString = !inString; continue; }
410
+ if (!inString) {
411
+ if (ch === '{') braceDepth++;
412
+ if (ch === '}') {
413
+ braceDepth--;
414
+ if (braceDepth === 0) return text.substring(startIndex, i + 1);
415
+ }
416
+ }
417
+ }
418
+ return null;
419
+ }
420
+
421
+ function coerceToolCallObject(obj) {
422
+ if (!obj || typeof obj !== 'object') return null;
423
+ const candidate = obj.tool_call || obj.tool || obj.function_call || obj;
424
+ if (!candidate || typeof candidate !== 'object') return null;
425
+ const fn = candidate.function && typeof candidate.function === 'object' ? candidate.function : candidate;
426
+ const name = fn.name || candidate.name || obj.name;
427
+ let args = fn.arguments ?? candidate.arguments ?? candidate.input ?? obj.arguments ?? obj.input ?? {};
428
+ if (!name || typeof name !== 'string') return null;
429
+ if (typeof args === 'string') {
430
+ try { args = JSON.parse(args); } catch (e) { args = { raw: args }; }
431
+ }
432
+ if (!args || typeof args !== 'object' || Array.isArray(args)) args = { value: args };
433
+ return { name, arguments: JSON.stringify(args) };
434
+ }
435
+
436
+ function parseJsonToolCandidate(raw, label = 'json') {
437
+ if (!raw) return null;
438
+ try {
439
+ const parsed = JSON.parse(raw);
440
+ const tc = coerceToolCallObject(parsed);
441
+ if (tc) {
442
+ console.log(`[parseToolCall] SUCCESS ${label}: ${tc.name} (args=${tc.arguments.length} chars)`);
443
+ return tc;
444
+ }
445
+ } catch (e) {
446
+ console.log(`[parseToolCall] ${label} JSON.parse failed: ${e.message.substring(0, 100)}`);
447
+ }
448
+ return null;
449
+ }
450
+
451
+ function parseToolCall(text) {
452
+ if (!text || typeof text !== 'string') return null;
453
+
454
+ // XML-ish wrappers used by some agent prompts.
455
+ const xmlMatch = text.match(/<tool_call[^>]*>([\s\S]*?)<\/tool_call>/i);
456
+ if (xmlMatch) {
457
+ const inner = xmlMatch[1].trim();
458
+ const tc = parseJsonToolCandidate(inner, 'xml');
459
+ if (tc) return tc;
460
+ }
461
+
462
+ // Fenced JSON blocks.
463
+ const fenceRe = /```(?:json)?\s*([\s\S]*?)```/gi;
464
+ let fence;
465
+ while ((fence = fenceRe.exec(text)) !== null) {
466
+ const tc = parseJsonToolCandidate(fence[1].trim(), 'fenced');
467
+ if (tc) return tc;
468
+ }
469
+
470
+ // Legacy TOOL_CALL: name + first balanced JSON object after it.
471
+ const match = text.match(/TOOL_CALL:\s*([\w-]+)\s*/i);
472
+ if (match) {
473
+ const name = match[1];
474
+ const afterMatch = text.substring(match.index + match[0].length);
475
+ const braceIdx = afterMatch.indexOf('{');
476
+ if (braceIdx !== -1) {
477
+ const rawJson = extractBalancedJsonAt(afterMatch, braceIdx);
478
+ if (rawJson) {
479
+ try {
480
+ const args = JSON.parse(rawJson);
481
+ console.log(`[parseToolCall] SUCCESS legacy: ${name} (args=${rawJson.length} chars)`);
482
+ return { name, arguments: JSON.stringify(args) };
483
+ } catch (e) {
484
+ console.log(`[parseToolCall] legacy JSON.parse failed: ${e.message.substring(0,100)}`);
485
+ }
486
+ } else {
487
+ console.log(`[parseToolCall] TOOL_CALL:${name} found but JSON braces are unbalanced`);
488
+ }
489
+ } else {
490
+ console.log(`[parseToolCall] TOOL_CALL:${name} found but no { after it`);
491
+ }
492
+ }
493
+
494
+ // First balanced JSON object in the whole response. Supports:
495
+ // {"tool_call":{"name":"...","arguments":{...}}}, {"name":"...","arguments":{...}}, etc.
496
+ for (let i = 0; i < text.length; i++) {
497
+ if (text[i] !== '{') continue;
498
+ const rawJson = extractBalancedJsonAt(text, i);
499
+ if (!rawJson) continue;
500
+ const tc = parseJsonToolCandidate(rawJson, 'inline');
501
+ if (tc) return tc;
502
+ }
503
+
504
+ console.log(`[parseToolCall] No tool call match in ${text.length} chars`);
505
+ return null;
506
+ }
507
+
508
+ /**
509
+ * Strip surrogate characters and other problematic Unicode from text
510
+ * to prevent httpx/urlencode crashes when the gateway sends to Telegram.
511
+ */
512
+ function sanitizeContent(text) {
513
+ return text.replace(/[\ud800-\udfff]/g, '');
514
+ }
515
+
516
+ function estimateTokens(text) {
517
+ return text ? Math.ceil(String(text).length / 4) : 0;
518
+ }
519
+
520
+ function buildUsage(prompt, content, reasoningContent = '') {
521
+ const promptTokens = estimateTokens(prompt);
522
+ const contentTokens = estimateTokens(content);
523
+ const reasoningTokens = estimateTokens(reasoningContent);
524
+ const completionTokens = contentTokens + reasoningTokens;
525
+ return {
526
+ prompt_tokens: promptTokens,
527
+ completion_tokens: completionTokens,
528
+ total_tokens: promptTokens + completionTokens,
529
+ completion_tokens_details: {
530
+ reasoning_tokens: reasoningTokens
531
+ }
532
+ };
533
+ }
534
+
535
+ function buildToolCallResponse(toolCall, model = 'deepseek-default', prompt = '', reasoningContent = '') {
536
+ const id = 'call_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8);
537
+ const message = {
538
+ role: 'assistant',
539
+ content: null,
540
+ tool_calls: [{
541
+ id: id,
542
+ type: 'function',
543
+ function: { name: toolCall.name, arguments: toolCall.arguments }
544
+ }]
545
+ };
546
+ // Do not attach reasoning to tool-call turns. Some agent clients treat any
547
+ // reasoning/text payload as a final assistant answer and stop their tool loop.
548
+ return {
549
+ id: 'ds-' + Date.now(),
550
+ object: 'chat.completion',
551
+ created: Math.floor(Date.now() / 1000),
552
+ model,
553
+ choices: [{
554
+ index: 0,
555
+ message,
556
+ finish_reason: 'tool_calls'
557
+ }],
558
+ usage: buildUsage(prompt, '', reasoningContent),
559
+ watermark: FORGETMEAI_WATERMARK
560
+ };
561
+ }
562
+
563
+ function buildTextResponse(content, prompt, model = 'deepseek-default', reasoningContent = '') {
564
+ const message = { role: 'assistant', content };
565
+ if (reasoningContent) message.reasoning_content = reasoningContent;
566
+ return {
567
+ id: 'ds-' + Date.now(),
568
+ object: 'chat.completion',
569
+ created: Math.floor(Date.now() / 1000),
570
+ model,
571
+ choices: [{
572
+ index: 0,
573
+ message,
574
+ finish_reason: 'stop'
575
+ }],
576
+ usage: buildUsage(prompt, content, reasoningContent),
577
+ watermark: FORGETMEAI_WATERMARK
578
+ };
579
+ }
580
+
581
+ function normalizeMessageContent(content) {
582
+ if (content === null || content === undefined) return '';
583
+ if (typeof content === 'string') return content;
584
+ if (Array.isArray(content)) {
585
+ return content.map(part => {
586
+ if (typeof part === 'string') return part;
587
+ if (!part || typeof part !== 'object') return '';
588
+ if (part.type === 'text' || part.type === 'input_text' || part.type === 'output_text') return part.text || '';
589
+ if (part.type === 'tool_result') return `[Tool Result ${part.tool_use_id || ''}]\n${normalizeMessageContent(part.content)}`;
590
+ if (part.type === 'image_url') return `[Image: ${part.image_url?.url || ''}]`;
591
+ return part.text || part.content || JSON.stringify(part);
592
+ }).filter(Boolean).join('\n');
593
+ }
594
+ return String(content);
595
+ }
596
+
597
+ function normalizeAnthropicTools(tools = []) {
598
+ return (tools || []).map(tool => ({
599
+ type: 'function',
600
+ function: {
601
+ name: tool.name,
602
+ description: tool.description || '',
603
+ parameters: tool.input_schema || tool.parameters || { type: 'object', properties: {} }
604
+ }
605
+ })).filter(tool => tool.function.name);
606
+ }
607
+
608
+ function normalizeResponsesTools(tools = []) {
609
+ return (tools || []).map(tool => {
610
+ if (tool.type === 'function' && tool.function) return tool;
611
+ if (tool.type === 'function' && tool.name) {
612
+ return { type: 'function', function: { name: tool.name, description: tool.description || '', parameters: tool.parameters || { type: 'object', properties: {} } } };
613
+ }
614
+ return null;
615
+ }).filter(Boolean);
616
+ }
617
+
618
+ function normalizeResponsesInput(input) {
619
+ if (typeof input === 'string') return [{ role: 'user', content: input }];
620
+ if (!Array.isArray(input)) return [];
621
+ const messages = [];
622
+ for (const item of input) {
623
+ if (!item || typeof item !== 'object') continue;
624
+ if (item.type === 'message') {
625
+ messages.push({ role: item.role || 'user', content: normalizeMessageContent(item.content) });
626
+ } else if (item.role) {
627
+ messages.push({ role: item.role, content: normalizeMessageContent(item.content) });
628
+ } else if (item.type === 'function_call_output') {
629
+ messages.push({ role: 'tool', tool_call_id: item.call_id, content: item.output || '' });
630
+ } else if (item.type === 'input_text') {
631
+ messages.push({ role: 'user', content: item.text || '' });
632
+ }
633
+ }
634
+ return messages;
635
+ }
636
+
637
+ function normalizeApiParams(params, apiMode) {
638
+ if (apiMode === 'anthropic') {
639
+ const messages = [];
640
+ if (params.system) messages.push({ role: 'system', content: normalizeMessageContent(params.system) });
641
+ for (const msg of params.messages || []) {
642
+ if (msg.role === 'assistant' && Array.isArray(msg.content)) {
643
+ const toolUses = msg.content.filter(part => part && part.type === 'tool_use');
644
+ const text = normalizeMessageContent(msg.content.filter(part => !part || part.type !== 'tool_use'));
645
+ if (text) messages.push({ role: 'assistant', content: text });
646
+ for (const tu of toolUses) {
647
+ messages.push({ role: 'assistant', content: null, tool_calls: [{ id: tu.id, type: 'function', function: { name: tu.name, arguments: JSON.stringify(tu.input || {}) } }] });
648
+ }
649
+ } else if (msg.role === 'user' && Array.isArray(msg.content) && msg.content.some(part => part && part.type === 'tool_result')) {
650
+ for (const part of msg.content) {
651
+ if (part && part.type === 'tool_result') messages.push({ role: 'tool', tool_call_id: part.tool_use_id, content: normalizeMessageContent(part.content) });
652
+ else messages.push({ role: 'user', content: normalizeMessageContent(part) });
653
+ }
654
+ } else {
655
+ messages.push({ role: msg.role || 'user', content: normalizeMessageContent(msg.content) });
656
+ }
657
+ }
658
+ return {
659
+ ...params,
660
+ model: params.model || 'deepseek-chat',
661
+ messages,
662
+ tools: normalizeAnthropicTools(params.tools || []),
663
+ stream: params.stream === true,
664
+ user: params.metadata?.user_id || params.user,
665
+ };
666
+ }
667
+ if (apiMode === 'responses') {
668
+ const messages = normalizeResponsesInput(params.input);
669
+ if (params.instructions) messages.unshift({ role: 'system', content: params.instructions });
670
+ return {
671
+ ...params,
672
+ model: params.model || 'deepseek-chat',
673
+ messages,
674
+ tools: normalizeResponsesTools(params.tools || []),
675
+ stream: params.stream === true,
676
+ user: params.user,
677
+ };
678
+ }
679
+ return params;
680
+ }
681
+
682
+ function safeJsonParseObject(text, fallback = {}) {
683
+ try {
684
+ const parsed = JSON.parse(text || '{}');
685
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback;
686
+ } catch (e) {
687
+ return fallback;
688
+ }
689
+ }
690
+
691
+ function toAnthropicResponse(openaiResp) {
692
+ const choice = openaiResp.choices[0];
693
+ const msg = choice.message || {};
694
+ const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
695
+ const content = [];
696
+ if (hasToolCalls) {
697
+ for (const tc of msg.tool_calls) {
698
+ content.push({ type: 'tool_use', id: tc.id, name: tc.function.name, input: safeJsonParseObject(tc.function.arguments) });
699
+ }
700
+ } else {
701
+ content.push({ type: 'text', text: msg.content || '' });
702
+ }
703
+ const response = {
704
+ id: 'msg_' + openaiResp.id,
705
+ type: 'message',
706
+ role: 'assistant',
707
+ model: openaiResp.model,
708
+ content,
709
+ stop_reason: choice.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn',
710
+ stop_sequence: null,
711
+ usage: {
712
+ input_tokens: openaiResp.usage?.prompt_tokens || 0,
713
+ output_tokens: openaiResp.usage?.completion_tokens || 0,
714
+ },
715
+ watermark: FORGETMEAI_WATERMARK,
716
+ };
717
+ if (!hasToolCalls && msg.reasoning_content) response.reasoning_content = msg.reasoning_content;
718
+ return response;
719
+ }
720
+
721
+ function writeSse(res, event, data) {
722
+ if (event) res.write(`event: ${event}\n`);
723
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
724
+ }
725
+
726
+ function sendAnthropicStream(res, openaiResp) {
727
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
728
+ const choice = openaiResp.choices[0];
729
+ const msg = choice.message || {};
730
+ const message = toAnthropicResponse(openaiResp);
731
+ const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
732
+ writeSse(res, 'message_start', { type: 'message_start', message: { ...message, content: [] } });
733
+
734
+ // Anthropic-compatible clients expect a tool turn to be made of tool_use
735
+ // content blocks. If we emit DeepSeek reasoning as a text block before the
736
+ // tool_use block, some agents treat the turn as a normal text answer and do
737
+ // not execute the tool. Keep tool streaming clean: tool_use blocks only.
738
+ if (hasToolCalls) {
739
+ msg.tool_calls.forEach((tc, i) => {
740
+ writeSse(res, 'content_block_start', { type: 'content_block_start', index: i, content_block: { type: 'tool_use', id: tc.id, name: tc.function.name, input: {} } });
741
+ writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: i, delta: { type: 'input_json_delta', partial_json: tc.function.arguments || '{}' } });
742
+ writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: i });
743
+ });
744
+ writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: message.usage });
745
+ } else {
746
+ if (msg.reasoning_content) {
747
+ writeSse(res, 'content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } });
748
+ writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: `[reasoning]\n${msg.reasoning_content}\n[/reasoning]\n` } });
749
+ writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: 0 });
750
+ }
751
+ const offset = msg.reasoning_content ? 1 : 0;
752
+ writeSse(res, 'content_block_start', { type: 'content_block_start', index: offset, content_block: { type: 'text', text: '' } });
753
+ const text = msg.content || '';
754
+ for (let i = 0; i < text.length; i += 80) {
755
+ writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: offset, delta: { type: 'text_delta', text: text.substring(i, i + 80) } });
756
+ }
757
+ writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: offset });
758
+ writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: message.usage });
759
+ }
760
+ writeSse(res, 'message_stop', { type: 'message_stop' });
761
+ res.end();
762
+ }
763
+
764
+ function toResponsesResponse(openaiResp) {
765
+ const choice = openaiResp.choices[0];
766
+ const msg = choice.message || {};
767
+ const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
768
+ const output = [];
769
+ if (!hasToolCalls && msg.reasoning_content) {
770
+ output.push({ id: 'rs_' + Date.now(), type: 'reasoning', summary: [{ type: 'summary_text', text: msg.reasoning_content }] });
771
+ }
772
+ if (hasToolCalls) {
773
+ for (const tc of msg.tool_calls) {
774
+ output.push({ type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}' });
775
+ }
776
+ } else {
777
+ output.push({ id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: msg.content || '', annotations: [] }] });
778
+ }
779
+ return {
780
+ id: openaiResp.id.replace(/^ds-/, 'resp_'),
781
+ object: 'response',
782
+ created_at: openaiResp.created,
783
+ status: 'completed',
784
+ model: openaiResp.model,
785
+ output,
786
+ output_text: msg.content || '',
787
+ usage: {
788
+ input_tokens: openaiResp.usage?.prompt_tokens || 0,
789
+ output_tokens: openaiResp.usage?.completion_tokens || 0,
790
+ total_tokens: openaiResp.usage?.total_tokens || 0,
791
+ output_tokens_details: { reasoning_tokens: openaiResp.usage?.completion_tokens_details?.reasoning_tokens || 0 },
792
+ },
793
+ watermark: FORGETMEAI_WATERMARK,
794
+ };
795
+ }
796
+
797
+ function sendResponsesStream(res, openaiResp) {
798
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
799
+ const response = toResponsesResponse(openaiResp);
800
+ const choice = openaiResp.choices[0];
801
+ const msg = choice.message || {};
802
+ const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
803
+ writeSse(res, 'response.created', { type: 'response.created', response: { ...response, status: 'in_progress', output: [] } });
804
+ writeSse(res, 'response.in_progress', { type: 'response.in_progress', response: { ...response, status: 'in_progress', output: [] } });
805
+ let outputIndex = 0;
806
+ if (!hasToolCalls && msg.reasoning_content) {
807
+ const reasoningItem = { id: 'rs_' + Date.now(), type: 'reasoning', summary: [], status: 'completed' };
808
+ writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...reasoningItem, status: 'in_progress' } });
809
+ writeSse(res, 'response.reasoning_summary_text.delta', { type: 'response.reasoning_summary_text.delta', output_index: outputIndex, summary_index: 0, delta: msg.reasoning_content });
810
+ writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item: { ...reasoningItem, summary: [{ type: 'summary_text', text: msg.reasoning_content }] } });
811
+ outputIndex++;
812
+ }
813
+ if (hasToolCalls) {
814
+ msg.tool_calls.forEach((tc) => {
815
+ const item = { type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}', status: 'completed' };
816
+ writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, arguments: '', status: 'in_progress' } });
817
+ writeSse(res, 'response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', output_index: outputIndex, item_id: item.id, delta: item.arguments });
818
+ writeSse(res, 'response.function_call_arguments.done', { type: 'response.function_call_arguments.done', output_index: outputIndex, item_id: item.id, arguments: item.arguments });
819
+ writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item });
820
+ outputIndex++;
821
+ });
822
+ } else {
823
+ const text = msg.content || '';
824
+ const item = { id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text, annotations: [] }] };
825
+ writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, status: 'in_progress', content: [] } });
826
+ 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: [] } });
827
+ for (let i = 0; i < text.length; i += 80) {
828
+ 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) });
829
+ }
830
+ writeSse(res, 'response.output_text.done', { type: 'response.output_text.done', output_index: outputIndex, content_index: 0, item_id: item.id, text });
831
+ 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] });
832
+ writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item });
833
+ }
834
+ writeSse(res, 'response.completed', { type: 'response.completed', response });
835
+ res.write('data: [DONE]\n\n');
836
+ res.end();
837
+ }
838
+
839
+ function sendOpenAIStream(res, openaiResp) {
840
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
841
+ const choice = openaiResp.choices[0];
842
+ const msg = choice.message || {};
843
+ const id = openaiResp.id;
844
+ const created = openaiResp.created;
845
+ const model = openaiResp.model;
846
+ const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
847
+ if (!hasToolCalls && msg.reasoning_content) {
848
+ for (let i = 0; i < msg.reasoning_content.length; i += 50) {
849
+ const chunk = msg.reasoning_content.substring(i, i + 50);
850
+ res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { reasoning_content: chunk }, finish_reason: null }] })}\n\n`);
851
+ }
852
+ }
853
+ if (hasToolCalls) {
854
+ 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`);
855
+ 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`);
856
+ } else {
857
+ for (let i = 0; i < (msg.content || '').length; i += 50) {
858
+ const chunk = msg.content.substring(i, i + 50);
859
+ res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { content: chunk }, finish_reason: null }] })}\n\n`);
860
+ }
861
+ res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`);
862
+ }
863
+ res.end();
864
+ }
865
+
866
+ function storeHistory(agentId, prompt, content, toolCall) {
867
+ const session = getOrCreateAgentSession(agentId);
868
+ const assistantResponse = toolCall
869
+ ? `TOOL_CALL: ${toolCall.name}\narguments: ${toolCall.arguments}`
870
+ : content;
871
+ // Save last 500 chars of the prompt for history context
872
+ const shortPrompt = prompt.length > 500 ? '...' + prompt.substring(prompt.length - 500) : prompt;
873
+ session.history.push({ user: shortPrompt, assistant: assistantResponse });
874
+ while (session.history.length > MAX_HISTORY_LENGTH) session.history.shift();
875
+ let historyChars = session.history.reduce((sum, e) => sum + e.user.length + e.assistant.length, 0);
876
+ while (historyChars > MAX_HISTORY_CHARS && session.history.length > 1) {
877
+ const removed = session.history.shift();
878
+ historyChars -= removed.user.length + removed.assistant.length;
879
+ }
880
+ }
881
+
882
+ // Extract MEDIA: paths from tool results that contain screenshot paths
883
+ function extractScreenshotPaths(messages) {
884
+ const paths = [];
885
+ const fs = require('fs');
886
+ for (const msg of messages) {
887
+ if (msg.role === 'tool' && msg.content) {
888
+ // Look for screenshot_path or path fields in JSON tool results
889
+ // These come DIRECTLY from browser_vision — always the real path
890
+ const pngMatch = msg.content.match(/["'](screenshot_path|path)["']\s*:\s*["']([^"']+\.(?:png|jpg|jpeg|webp|gif))["']/i);
891
+ if (pngMatch) {
892
+ const filePath = pngMatch[2];
893
+ if (filePath.startsWith('/') && fs.existsSync(filePath)) {
894
+ paths.push(`MEDIA:${filePath}`);
895
+ }
896
+ }
897
+ // Also catch plain MEDIA: tags
898
+ const mediaMatch = msg.content.match(/MEDIA:(\S+)/g);
899
+ if (mediaMatch) {
900
+ for (const tag of mediaMatch) {
901
+ const extractedPath = tag.replace(/^MEDIA:/, '');
902
+ if (fs.existsSync(extractedPath) && !paths.includes(tag)) {
903
+ paths.push(tag);
904
+ }
905
+ }
906
+ }
907
+ }
908
+ // Check user/assistant messages for paths mentioned in conversation text
909
+ // Only include if the file ACTUALLY EXISTS (DeepSeek hallucinates paths)
910
+ if ((msg.role === 'user' || msg.role === 'assistant') && msg.content) {
911
+ const content = typeof msg.content === 'string' ? msg.content : '';
912
+ const pathRegex = /(\/[^\s<>"']+\.(?:png|jpg|jpeg|webp|gif))/gi;
913
+ let match;
914
+ while ((match = pathRegex.exec(content)) !== null) {
915
+ const filePath = match[1];
916
+ if (filePath.startsWith('/') && fs.existsSync(filePath) && !paths.includes(`MEDIA:${filePath}`)) {
917
+ paths.push(`MEDIA:${filePath}`);
918
+ }
919
+ }
920
+ }
921
+ }
922
+ return paths;
923
+ }
924
+
925
+ function formatMessages(messages, tools) {
926
+ let systemPrompt = '';
927
+ for (const msg of messages) {
928
+ if (msg.role === 'system' && msg.content) {
929
+ systemPrompt += msg.content + '\n';
930
+ }
931
+ }
932
+ systemPrompt += formatToolDefinitions(tools);
933
+
934
+ // Build full conversation history for DeepSeek's context
935
+ let conversation = '';
936
+ for (const msg of messages) {
937
+ if (msg.role === 'system') continue; // already in systemPrompt
938
+ if (msg.role === 'user' && msg.content) {
939
+ conversation += `User: ${msg.content}\n\n`;
940
+ } else if (msg.role === 'assistant') {
941
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
942
+ // This was a tool call response from a previous turn
943
+ for (const tc of msg.tool_calls) {
944
+ conversation += `Assistant: TOOL_CALL: ${tc.function.name}\narguments: ${tc.function.arguments}\n\n`;
945
+ }
946
+ } else if (msg.content) {
947
+ conversation += `Assistant: ${msg.content}\n\n`;
948
+ }
949
+ } else if (msg.role === 'tool' && msg.content) {
950
+ // Tool execution result — send back to DeepSeek as context
951
+ const truncated = msg.content.length > 8000
952
+ ? msg.content.substring(0, 8000) + '\n...[truncated]'
953
+ : msg.content;
954
+ conversation += `[Tool Result]\n${truncated}\n\n`;
955
+ }
956
+ }
957
+ // The last user message + full conversation context
958
+ return { prompt: conversation.trim(), systemPrompt: systemPrompt.trim() };
959
+ }
960
+
961
+ // === HTTP Server ===
962
+ const server = http.createServer(async (req, res) => {
963
+ res.setHeader('Access-Control-Allow-Origin', '*');
964
+ res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
965
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
966
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
967
+
968
+ const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
969
+
970
+ // Health check
971
+ if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/health')) {
972
+ res.writeHead(200, { 'Content-Type': 'application/json' });
973
+ 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() }));
974
+ return;
975
+ }
976
+
977
+ // Models: OpenAI-compatible list exposes only aliases verified to work through this proxy.
978
+ if (req.method === 'GET' && url.pathname === '/v1/models') {
979
+ res.writeHead(200, { 'Content-Type': 'application/json' });
980
+ 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 })) }));
981
+ return;
982
+ }
983
+
984
+ // Full mapping, including Web models observed but not currently usable through the direct API.
985
+ if (req.method === 'GET' && (url.pathname === '/v1/model-capabilities' || url.pathname === '/api/model-capabilities')) {
986
+ res.writeHead(200, { 'Content-Type': 'application/json' });
987
+ res.end(JSON.stringify({ object: 'model_capabilities', watermark: FORGETMEAI_WATERMARK, data: ALL_MODEL_CAPABILITIES }));
988
+ return;
989
+ }
990
+
991
+ // Sessions status
992
+ if (req.method === 'GET' && url.pathname === '/v1/sessions') {
993
+ const agentList = [];
994
+ for (const [agentId, session] of sessions) {
995
+ agentList.push({
996
+ agent: agentId,
997
+ session_id: session.id,
998
+ message_count: session.messageCount,
999
+ history_size: session.history.length,
1000
+ age_min: session.createdAt ? Math.round((Date.now() - session.createdAt) / 60000) : 0,
1001
+ });
1002
+ }
1003
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1004
+ res.end(JSON.stringify({ agents: agentList, total: agentList.length }));
1005
+ return;
1006
+ }
1007
+
1008
+ // Reset session for a specific agent (or all if no agent specified)
1009
+ if (req.method === 'POST' && url.pathname === '/reset-session') {
1010
+ const agentId = url.searchParams.get('agent') || 'default';
1011
+ if (agentId === 'all') {
1012
+ const count = sessions.size;
1013
+ sessions.clear();
1014
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1015
+ res.end(JSON.stringify({ status: 'all_sessions_cleared', count }));
1016
+ return;
1017
+ }
1018
+ const session = sessions.get(agentId);
1019
+ if (!session) {
1020
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1021
+ res.end(JSON.stringify({ error: `No session for agent: ${agentId}` }));
1022
+ return;
1023
+ }
1024
+ const historyCount = session.history.length;
1025
+ const historyPreview = session.history.map(e => e.user.substring(0, 40)).join(' | ');
1026
+ session.id = null;
1027
+ session.parentMessageId = null;
1028
+ session.createdAt = null;
1029
+ session.messageCount = 0;
1030
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1031
+ res.end(JSON.stringify({ status: 'session_reset', agent: agentId, history_preserved: historyCount, history: historyPreview }));
1032
+ return;
1033
+ }
1034
+
1035
+ const apiMode = url.pathname === '/v1/messages'
1036
+ ? 'anthropic'
1037
+ : (url.pathname === '/v1/responses' ? 'responses' : 'openai');
1038
+ const acceptedPostPaths = ['/v1/chat/completions', '/v1/messages', '/v1/responses'];
1039
+ if (req.method !== 'POST' || !acceptedPostPaths.includes(url.pathname)) {
1040
+ res.writeHead(404); res.end('Not found'); return;
1041
+ }
1042
+
1043
+ let body = '';
1044
+ req.on('data', chunk => body += chunk);
1045
+ req.on('end', async () => {
1046
+ try {
1047
+ const rawParams = JSON.parse(body || '{}');
1048
+ const params = normalizeApiParams(rawParams, apiMode);
1049
+ const messages = params.messages || [];
1050
+ const tools = params.tools || [];
1051
+ const stream = params.stream === true;
1052
+ const requestedModel = String(params.model || 'deepseek-chat').toLowerCase();
1053
+ if (!isKnownModel(requestedModel)) {
1054
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1055
+ res.end(JSON.stringify({ error: { message: `Unknown model: ${requestedModel}`, type: 'invalid_model', supported_models: SUPPORTED_MODEL_IDS, model_capabilities_url: '/v1/model-capabilities' } }));
1056
+ return;
1057
+ }
1058
+ if (!isSupportedModel(requestedModel)) {
1059
+ const cfg = resolveModelConfig(requestedModel);
1060
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1061
+ 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 } }));
1062
+ return;
1063
+ }
1064
+ // Use remote IP for session isolation (local gets 'dev-agent', external per-IP)
1065
+ const remoteAddr = req.socket.remoteAddress || 'unknown';
1066
+ const requestedSession = req.headers['x-agent-session'] || params.session || params.user;
1067
+ const agentId = requestedSession
1068
+ ? String(requestedSession)
1069
+ : ((remoteAddr === '127.0.0.1' || remoteAddr === '::1' || remoteAddr === '::ffff:127.0.0.1') ? 'dev-agent' : remoteAddr);
1070
+ const agentTag = `[${agentId}]`;
1071
+ const { prompt, systemPrompt } = formatMessages(messages, tools);
1072
+
1073
+ const session = getOrCreateAgentSession(agentId);
1074
+
1075
+ // Build history prefix if starting fresh
1076
+ let historyPrefix = '';
1077
+ if (!session.id && session.history.length > 0) {
1078
+ historyPrefix = '[Previous conversation]\n';
1079
+ for (const exchange of session.history) {
1080
+ historyPrefix += `User: ${exchange.user}\nAssistant: ${exchange.assistant}\n\n`;
1081
+ }
1082
+ historyPrefix += '[Continue from here]\n\n';
1083
+ }
1084
+
1085
+ const fullPrompt = systemPrompt
1086
+ ? `${systemPrompt}\n\n${historyPrefix}${prompt}`
1087
+ : `${historyPrefix}${prompt}`;
1088
+
1089
+ const startTime = Date.now();
1090
+ const { resp: dsResp } = await askDeepSeekStream(fullPrompt, agentId, requestedModel);
1091
+
1092
+ // Process streaming response from DeepSeek — returns { content, reasoningContent, messageId, finishReason }
1093
+ async function readDeepSeekResponse(readable) {
1094
+ let buffer = '';
1095
+ let lastPath = null;
1096
+ const fragments = [];
1097
+ let fullContent = '';
1098
+ let reasoningContent = '';
1099
+ let newMessageId = null;
1100
+ let finishReason = null;
1101
+ let modelError = null;
1102
+
1103
+ const rebuildFragmentText = () => {
1104
+ const responseText = fragments
1105
+ .filter(f => f && f.type === 'RESPONSE' && typeof f.content === 'string')
1106
+ .map(f => f.content)
1107
+ .join('');
1108
+ const thinkText = fragments
1109
+ .filter(f => f && (f.type === 'THINK' || f.type === 'REASONING') && typeof f.content === 'string')
1110
+ .map(f => f.content)
1111
+ .join('');
1112
+ if (responseText) fullContent = responseText;
1113
+ reasoningContent = thinkText;
1114
+ };
1115
+
1116
+ const appendFragments = (value) => {
1117
+ const incoming = Array.isArray(value) ? value : [value];
1118
+ for (const fragment of incoming) {
1119
+ if (fragment && typeof fragment === 'object') fragments.push({ ...fragment });
1120
+ }
1121
+ rebuildFragmentText();
1122
+ };
1123
+
1124
+ for await (const chunk of readable) {
1125
+ buffer += new TextDecoder().decode(chunk, { stream: true });
1126
+ const lines = buffer.split('\n');
1127
+ buffer = lines.pop() || '';
1128
+ for (const line of lines) {
1129
+ if (line.startsWith('data: ')) {
1130
+ try {
1131
+ const d = JSON.parse(line.slice(6));
1132
+ if (d.response_message_id !== undefined && !newMessageId) newMessageId = d.response_message_id;
1133
+ if (d.type === 'error' || d.finish_reason || d.content) {
1134
+ modelError = { type: d.type || 'error', content: d.content || '', finish_reason: d.finish_reason || null };
1135
+ if (d.finish_reason) finishReason = d.finish_reason;
1136
+ }
1137
+ if (d.p !== undefined) lastPath = d.p;
1138
+ if (d.v && typeof d.v === 'object' && d.v.response) {
1139
+ if (d.v.response.message_id !== undefined) {
1140
+ newMessageId = d.v.response.message_id;
1141
+ }
1142
+ if (d.v.response.content !== undefined) {
1143
+ fullContent = d.v.response.content;
1144
+ }
1145
+ if (Array.isArray(d.v.response.fragments)) {
1146
+ fragments.length = 0;
1147
+ appendFragments(d.v.response.fragments);
1148
+ }
1149
+ if (d.v.response.finish_reason !== undefined) {
1150
+ finishReason = d.v.response.finish_reason;
1151
+ }
1152
+ }
1153
+ if (lastPath === 'response/fragments' && d.v !== undefined) {
1154
+ appendFragments(d.v);
1155
+ }
1156
+ if (lastPath === 'response/fragments/-1/content' && d.v !== undefined && typeof d.v !== 'object') {
1157
+ if (fragments.length > 0) {
1158
+ const lastFragment = fragments[fragments.length - 1];
1159
+ lastFragment.content = `${lastFragment.content || ''}${d.v}`;
1160
+ rebuildFragmentText();
1161
+ }
1162
+ }
1163
+ if (lastPath === 'response/content' && d.v !== undefined && typeof d.v !== 'object') {
1164
+ fullContent += d.v;
1165
+ }
1166
+ if (lastPath === 'response/finish_reason' && d.v !== undefined) {
1167
+ finishReason = d.v;
1168
+ }
1169
+ if (lastPath === 'response/status' && d.v !== undefined && d.v !== 'FINISHED') {
1170
+ finishReason = d.v;
1171
+ }
1172
+ } catch (e) { }
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ if (newMessageId) {
1178
+ session.parentMessageId = newMessageId;
1179
+ session.messageCount++;
1180
+ } else {
1181
+ console.log(`${agentTag} WARNING: could not extract message_id`);
1182
+ }
1183
+
1184
+ return { content: fullContent, reasoningContent, messageId: newMessageId, finishReason, modelError };
1185
+ }
1186
+
1187
+ let { content: fullContent, reasoningContent, finishReason, modelError } = await readDeepSeekResponse(dsResp.body);
1188
+ fullContent = sanitizeContent(fullContent);
1189
+ reasoningContent = sanitizeContent(reasoningContent || '');
1190
+ const elapsed = Date.now() - startTime;
1191
+ console.log(`${agentTag} Got ${fullContent.length} chars (+${reasoningContent.length} reasoning chars) in ${elapsed}ms (msg#${session.messageCount})`);
1192
+
1193
+ if ((!fullContent || fullContent.trim().length === 0) && modelError) {
1194
+ res.writeHead(502, { 'Content-Type': 'application/json' });
1195
+ 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 } }));
1196
+ return;
1197
+ }
1198
+
1199
+ // Empty response — retry loop with fresh sessions
1200
+ let retryAttempt = 0;
1201
+ const MAX_RETRIES = 10;
1202
+ while (!fullContent || fullContent.trim().length === 0) {
1203
+ retryAttempt++;
1204
+ if (retryAttempt > MAX_RETRIES) {
1205
+ console.log(`${agentTag} Empty after ${MAX_RETRIES} retries. Giving up.`);
1206
+ res.writeHead(502, { 'Content-Type': 'application/json' });
1207
+ res.end(JSON.stringify({
1208
+ error: {
1209
+ message: `DeepSeek returned empty content after ${MAX_RETRIES} retries`,
1210
+ type: 'empty_response',
1211
+ agent: agentId,
1212
+ session_id: session.id,
1213
+ message_count: session.messageCount,
1214
+ history_length: session.history.length,
1215
+ retry_attempts: retryAttempt - 1,
1216
+ }
1217
+ }));
1218
+ return;
1219
+ }
1220
+ console.log(`${agentTag} Empty response (msg#${session.messageCount}, retry ${retryAttempt}/${MAX_RETRIES}). Resetting session...`);
1221
+ session.id = null;
1222
+ session.parentMessageId = null;
1223
+ session.createdAt = null;
1224
+ session.messageCount = 0;
1225
+ // Brief delay before retry to let DeepSeek breathe
1226
+ await new Promise(r => setTimeout(r, Math.min(1000 * retryAttempt, 5000)));
1227
+ const { resp: retryResp } = await askDeepSeekStream(fullPrompt, agentId, requestedModel);
1228
+ const retryResult = await readDeepSeekResponse(retryResp.body);
1229
+ const retryContent = retryResult && retryResult.content ? sanitizeContent(retryResult.content) : '';
1230
+ const retryReasoning = retryResult && retryResult.reasoningContent ? sanitizeContent(retryResult.reasoningContent) : '';
1231
+ if (retryContent && retryContent.trim().length > 0) {
1232
+ console.log(`${agentTag} Retry ${retryAttempt} succeeded`);
1233
+ fullContent = retryContent;
1234
+ reasoningContent = retryReasoning;
1235
+ }
1236
+ }
1237
+
1238
+ // Auto-continuation: if finish_reason is 'length' or content is very long (>25000 chars),
1239
+ // send a continuation request to get the rest of the response
1240
+ let continuationRounds = 0;
1241
+ const MAX_CONTINUATION = 2;
1242
+ while ((finishReason === 'length' || fullContent.length > 25000) && continuationRounds < MAX_CONTINUATION) {
1243
+ continuationRounds++;
1244
+ console.log(`${agentTag} Response ${fullContent.length} chars (finish=${finishReason}). Auto-continuing (${continuationRounds}/${MAX_CONTINUATION})...`);
1245
+ await new Promise(r => setTimeout(r, 500));
1246
+ const { resp: contResp } = await askDeepSeekStream('continue', agentId, requestedModel);
1247
+ const contResult = await readDeepSeekResponse(contResp.body);
1248
+ const contContent = contResult && contResult.content ? sanitizeContent(contResult.content) : '';
1249
+ const contReasoning = contResult && contResult.reasoningContent ? sanitizeContent(contResult.reasoningContent) : '';
1250
+ if (contContent && contContent.trim().length > 0 && !contContent.includes('I am an AI')) {
1251
+ fullContent += '\n' + contContent;
1252
+ if (contReasoning) reasoningContent += (reasoningContent ? '\n' : '') + contReasoning;
1253
+ finishReason = contResult.finishReason;
1254
+ console.log(`${agentTag} Continuation added ${contContent.length} chars (total: ${fullContent.length})`);
1255
+ } else {
1256
+ console.log(`${agentTag} Continuation returned nothing useful, stopping`);
1257
+ break;
1258
+ }
1259
+ }
1260
+
1261
+ let toolCall = parseToolCall(fullContent);
1262
+
1263
+ // Retry if TOOL_CALL was found but JSON was truncated/invalid
1264
+ if (!toolCall && /TOOL_CALL:\s*\w/i.test(fullContent)) {
1265
+ console.log(`${agentTag} TOOL_CALL detected but JSON invalid/truncated (${fullContent.length} chars). Retrying with stricter prompt...`);
1266
+ session.id = null;
1267
+ session.parentMessageId = null;
1268
+ session.createdAt = null;
1269
+ session.messageCount = 0;
1270
+ await new Promise(r => setTimeout(r, 1000));
1271
+ 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>';
1272
+ const { resp: retryResp2 } = await askDeepSeekStream(strictPrompt, agentId, requestedModel);
1273
+ const retryResult2 = await readDeepSeekResponse(retryResp2.body);
1274
+ const retryContent2 = retryResult2 && retryResult2.content ? sanitizeContent(retryResult2.content) : '';
1275
+ if (retryContent2 && retryContent2.trim()) {
1276
+ const retryTc = parseToolCall(retryContent2);
1277
+ if (retryTc) {
1278
+ console.log(`${agentTag} Retry with strict prompt succeeded: ${retryTc.name}`);
1279
+ fullContent = retryContent2;
1280
+ reasoningContent = retryResult2.reasoningContent ? sanitizeContent(retryResult2.reasoningContent) : '';
1281
+ toolCall = retryTc;
1282
+ } else {
1283
+ console.log(`${agentTag} Retry still has broken JSON. Sending as text.`);
1284
+ reasoningContent = retryResult2.reasoningContent ? sanitizeContent(retryResult2.reasoningContent) : reasoningContent;
1285
+ }
1286
+ }
1287
+ }
1288
+
1289
+ // Check if any tool results in the current conversation contained a screenshot path.
1290
+ // If so, and the response doesn't already have MEDIA:, inject it so the gateway
1291
+ // delivers the file to Telegram.
1292
+ if (!fullContent.includes('MEDIA:')) {
1293
+ const screenshotPaths = extractScreenshotPaths(messages);
1294
+ if (screenshotPaths.length > 0) {
1295
+ fullContent += '\n\n' + screenshotPaths.join('\n');
1296
+ console.log(`${agentTag} Injected MEDIA paths into response: ${screenshotPaths.join(', ')}`);
1297
+ }
1298
+ }
1299
+
1300
+ storeHistory(agentId, prompt, fullContent, toolCall);
1301
+
1302
+ const openaiResponse = toolCall
1303
+ ? buildToolCallResponse(toolCall, requestedModel, fullPrompt, reasoningContent)
1304
+ : buildTextResponse(fullContent, fullPrompt, requestedModel, reasoningContent);
1305
+
1306
+ if (stream) {
1307
+ if (apiMode === 'anthropic') {
1308
+ sendAnthropicStream(res, openaiResponse);
1309
+ } else if (apiMode === 'responses') {
1310
+ sendResponsesStream(res, openaiResponse);
1311
+ } else {
1312
+ sendOpenAIStream(res, openaiResponse);
1313
+ }
1314
+ console.log(`${agentTag} Streamed ${apiMode} (tool=${!!toolCall}) in ${elapsed}ms`);
1315
+ } else {
1316
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1317
+ if (apiMode === 'anthropic') {
1318
+ res.end(JSON.stringify(toAnthropicResponse(openaiResponse)));
1319
+ } else if (apiMode === 'responses') {
1320
+ res.end(JSON.stringify(toResponsesResponse(openaiResponse)));
1321
+ } else {
1322
+ res.end(JSON.stringify(openaiResponse));
1323
+ }
1324
+ console.log(`${agentTag} Response ${apiMode} (tool=${!!toolCall}, ${elapsed}ms, ${fullContent.length} chars)`);
1325
+ }
1326
+ } catch (e) {
1327
+ console.log('[DS-API] Error:', e.message);
1328
+ res.writeHead(500, { 'Content-Type': 'application/json' });
1329
+ res.end(JSON.stringify({ error: { message: e.message, type: 'server_error' } }));
1330
+ }
1331
+ });
1332
+ });
1333
+
1334
+ async function runAuthScript() {
1335
+ const script = path.join(__dirname, 'scripts', 'deepseek_chrome_auth.js');
1336
+ const result = spawnSync(process.execPath, [script], { stdio: 'inherit', env: process.env });
1337
+ loadDeepSeekConfig({ fatal: false });
1338
+ return result.status === 0 && hasAuthConfig();
1339
+ }
1340
+
1341
+ function printStatus() {
1342
+ console.log(`\n${formatWatermark()}`);
1343
+ console.log(`Auth: ${hasAuthConfig() ? '✅ OK' : '❌ не найден deepseek-auth.json'}`);
1344
+ console.log(`Auth file: ${DS_CONFIG_PATH}`);
1345
+ console.log(`Рабочие модели: ${SUPPORTED_MODEL_IDS.join(', ')}`);
1346
+ console.log('Нерабочие/скрытые aliases: ' + Object.keys(MODEL_CONFIGS).filter(id => !MODEL_CONFIGS[id].supported).join(', '));
1347
+ console.log('Capabilities: GET /v1/model-capabilities');
1348
+ }
1349
+
1350
+ async function showStartupMenu() {
1351
+ if (isTruthy(process.env.SKIP_ACCOUNT_MENU) || isTruthy(process.env.NON_INTERACTIVE)) {
1352
+ if (!hasAuthConfig()) loadDeepSeekConfig({ fatal: true });
1353
+ return true;
1354
+ }
1355
+ while (true) {
1356
+ printStatus();
1357
+ console.log('\n=== Меню ===');
1358
+ console.log(`ForgetMeAI: ${FORGETMEAI_WATERMARK}`);
1359
+ console.log('1 - Авторизоваться / обновить DeepSeek login');
1360
+ console.log('2 - Показать модели и статусы');
1361
+ console.log('3 - Запустить прокси (по умолчанию)');
1362
+ console.log('4 - Выход');
1363
+ let choice = await prompt('Ваш выбор (Enter = 3): ');
1364
+ if (!choice) choice = '3';
1365
+ if (choice === '1') {
1366
+ await runAuthScript();
1367
+ } else if (choice === '2') {
1368
+ console.log(JSON.stringify(ALL_MODEL_CAPABILITIES, null, 2));
1369
+ await prompt('\nНажмите Enter, чтобы вернуться в меню...');
1370
+ } else if (choice === '3') {
1371
+ if (!hasAuthConfig()) {
1372
+ console.log('Нужен deepseek-auth.json. Запустите пункт 1.');
1373
+ continue;
1374
+ }
1375
+ return true;
1376
+ } else if (choice === '4') {
1377
+ return false;
1378
+ }
1379
+ }
1380
+ }
1381
+
1382
+ async function main() {
1383
+ printBanner();
1384
+ const shouldStart = await showStartupMenu();
1385
+ if (!shouldStart) process.exit(0);
1386
+ server.listen(PORT, HOST, () => {
1387
+ console.log(`[DS-API] Server on http://${HOST}:${PORT} (multi-agent sessions enabled)`);
1388
+ console.log(`[DS-API] ${formatWatermark()}`);
1389
+ console.log('[DS-API] POST /v1/chat/completions (OpenAI Chat Completions, stream=true|false)');
1390
+ console.log('[DS-API] POST /v1/messages — Anthropic Messages shim for Claude Code');
1391
+ console.log('[DS-API] POST /v1/responses — OpenAI Responses API shim');
1392
+ console.log('[DS-API] GET /v1/models — supported OpenAI-compatible models');
1393
+ console.log('[DS-API] GET /v1/model-capabilities — real model mapping and capabilities');
1394
+ console.log('[DS-API] GET /v1/sessions — list active agent sessions');
1395
+ console.log('[DS-API] POST /reset-session?agent=<id> — reset agent session');
1396
+ console.log('[DS-API] POST /reset-session?agent=all — reset ALL sessions');
1397
+ });
1398
+ }
1399
+
1400
+ main().catch(err => { console.error('[DS-API] FATAL:', err); process.exit(1); });
FlowAPI/Program.cs CHANGED
@@ -109,6 +109,68 @@ namespace FlowAPI
109
 
110
  var app = builder.Build();
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  // --- Auto-migrate database and seed ---
113
  using (var scope = app.Services.CreateScope())
114
  {
 
109
 
110
  var app = builder.Build();
111
 
112
+ // --- Start FreeDeepseekAPI proxy in background ---
113
+ try
114
+ {
115
+ var dsPath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "FreeDeepseekAPI", "server.js");
116
+ if (System.IO.File.Exists(dsPath))
117
+ {
118
+ System.Console.WriteLine($"[Main] Starting FreeDeepseekAPI proxy: node {dsPath}...");
119
+ var processStartInfo = new System.Diagnostics.ProcessStartInfo
120
+ {
121
+ FileName = "node",
122
+ Arguments = dsPath,
123
+ UseShellExecute = false,
124
+ CreateNoWindow = true,
125
+ RedirectStandardOutput = true,
126
+ RedirectStandardError = true
127
+ };
128
+ processStartInfo.EnvironmentVariables["NON_INTERACTIVE"] = "1";
129
+ processStartInfo.EnvironmentVariables["PORT"] = "9655";
130
+
131
+ // Forward any relevant DeepSeek vars to the proxy process
132
+ foreach (var key in new[] { "DEEPSEEK_TOKEN", "DEEPSEEK_COOKIE", "DEEPSEEK_HIF_DLIQ", "DEEPSEEK_HIF_LEIM", "DEEPSEEK_WASM_URL" })
133
+ {
134
+ var val = System.Environment.GetEnvironmentVariable(key);
135
+ if (!string.IsNullOrEmpty(val))
136
+ {
137
+ processStartInfo.EnvironmentVariables[key] = val;
138
+ }
139
+ }
140
+
141
+ var dsProcess = System.Diagnostics.Process.Start(processStartInfo);
142
+ if (dsProcess != null)
143
+ {
144
+ // Read output in background to prevent hanging
145
+ System.Threading.Tasks.Task.Run(() => {
146
+ try {
147
+ while (!dsProcess.StandardOutput.EndOfStream) {
148
+ var line = dsProcess.StandardOutput.ReadLine();
149
+ System.Console.WriteLine($"[DeepSeekProxy-Out] {line}");
150
+ }
151
+ } catch {}
152
+ });
153
+ System.Threading.Tasks.Task.Run(() => {
154
+ try {
155
+ while (!dsProcess.StandardError.EndOfStream) {
156
+ var line = dsProcess.StandardError.ReadLine();
157
+ System.Console.WriteLine($"[DeepSeekProxy-Err] {line}");
158
+ }
159
+ } catch {}
160
+ });
161
+ System.Console.WriteLine("[Main] FreeDeepseekAPI proxy started successfully.");
162
+ }
163
+ }
164
+ else
165
+ {
166
+ System.Console.WriteLine($"[Main] FreeDeepseekAPI proxy file not found at: {dsPath}");
167
+ }
168
+ }
169
+ catch (System.Exception ex)
170
+ {
171
+ System.Console.WriteLine($"[Main] Failed to start FreeDeepseekAPI proxy: {ex.Message}");
172
+ }
173
+
174
  // --- Auto-migrate database and seed ---
175
  using (var scope = app.Services.CreateScope())
176
  {