aegiscode 7.0.14 → 7.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
@@ -1,2182 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
5
- // Conveying a modified copy, or running one as a network service, owes the
6
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
7
- /**
8
- * AEGIS thin client — zero-dependency transport to aegiscloud.org.
9
- *
10
- * This file is the ONLY public surface that talks to the AEGIS backend. It
11
- * forwards requests and normalises responses; it contains NO engine, brain,
12
- * orchestration, routing, or tier logic. All of that lives in the private
13
- * ae-guix product and behind aegiscloud.org.
14
- *
15
- * Runs unchanged under four hosts:
16
- * - mcp/server.js (Claude Code MCP plugin) — CommonJS require
17
- * - desktop/ (thin Electron shell) — CommonJS require
18
- * (vendored byte-identical copy at desktop/vendor/aegis.js)
19
- * - cli/ (aegiscode terminal host) — CommonJS require
20
- * (vendored byte-identical copy at
21
- * cli/vendor/client/aegis.js)
22
- * - aegis-online (browser SPA, vendored copy) — <script> tag →
23
- * window.AegisClient
24
- *
25
- * Usage (Node):
26
- * const { createClient } = require('./client/aegis.js');
27
- * const aegis = createClient(); // reads AEGIS_API_KEY from env
28
- * const aegis = createClient({ apiBase, apiKey, memoryToken });
29
- *
30
- * Usage (browser):
31
- * <script src="/static/vendor/aegis.js"></script>
32
- * const aegis = window.AegisClient.createClient({ apiKey });
33
- *
34
- * BYOK note: byokChatCompletion() takes the provider key per request (or from
35
- * opts.providerKey) and sends it as X-Provider-Key — it is relayed to the
36
- * provider for that request only and never stored server-side.
37
- */
38
-
39
- 'use strict';
40
-
41
- // ---------------------------------------------------------------------------
42
- // Environment-agnostic preamble. This file must parse in Node AND in a plain
43
- // browser <script> tag, so no bare require/process/window/module references
44
- // may appear at load time.
45
- // ---------------------------------------------------------------------------
46
-
47
- /** Read an env var, treating unexpanded "${VAR}" templates as absent. */
48
- function envVar(name) {
49
- if (typeof process === 'undefined' || !process.env) return '';
50
- const v = process.env[name];
51
- return v && !/^\$\{[A-Z_]+\}$/.test(v) ? v : '';
52
- }
53
-
54
- /**
55
- * Read a positive millisecond count from the environment, or 0 for "unset".
56
- *
57
- * Used only for the two stream watchdogs below. Non-positive and unparseable
58
- * values are IGNORED rather than honoured — deliberately not the rule the
59
- * engine's host cooldown uses, where `AEGIS_HOST_COOLDOWN_MS=0` meaning "no
60
- * cooldown" is a coherent thing to ask for. Here `0` would mean "the stream is
61
- * dead before its first byte", which is a typo rather than a preference, and
62
- * silently killing every turn is a far worse failure than ignoring a bad
63
- * number. A test that genuinely wants a sub-second watchdog passes
64
- * `idleTimeoutMs` per call (test/autonomous-mode.test.mjs does exactly that).
65
- */
66
- function envIdleMs(name) {
67
- const raw = envVar(name);
68
- if (!raw) return 0;
69
- const n = Number(raw);
70
- return Number.isFinite(n) && n > 0 ? n : 0;
71
- }
72
-
73
- /**
74
- * DeepSeek emits its tool calls as DSML — an XML-ish dialect of its chat
75
- * template that the OpenAI-compatible wire format does NOT structure for us:
76
- *
77
- * <|DSML|tool_calls>
78
- * <|DSML|invoke name="write">
79
- * <|DSML|parameter name="path" string="true">src/app.js</|DSML|parameter>
80
- * <|DSML|parameter name="content" string="true">…the file body…</|DSML|parameter>
81
- * </|DSML|invoke>
82
- * </|DSML|tool_calls>
83
- *
84
- * It arrives as plain `delta.content` text, and that produces two failures:
85
- * the markup rendering verbatim (reported as the pasted "||DSML||" envelope),
86
- * and the call itself never running because text is not a tool call. Ported
87
- * from aegiscodex-dev's src/backend.js, which carries the full history of this
88
- * grammar's quirks (provider/template/model revision disagree about the exact
89
- * identifier, angle brackets sometimes absent, tag names drift under
90
- * sampling) — every part of the pattern below is deliberately optional and
91
- * spacing-insensitive for that reason. `string="false"` marks a JSON
92
- * parameter; `string="true"` (or an absent attribute) is the literal value,
93
- * kept verbatim so a multi-line `content` is never mangled by a JSON
94
- * round-trip.
95
- */
96
- // `\b` after each tag-name alternative matters: without it, "call" matches as
97
- // a bare PREFIX of a drifted wrapper tag like "calls" (observed verbatim —
98
- // `<|| calls>`, no "tool_"/"function_" prefix at all), swallowing everything
99
- // up to the next real `</invoke>` as that spurious match's unnamed body and
100
- // silently discarding a whole tool call with it. "call" and "calls" are both
101
- // word characters, so plain alternation order cannot tell them apart.
102
- const DSML_RE_INVOKE = /<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g;
103
- const DSML_RE_PARAM = /<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g;
104
- const DSML_RE_LEADER = /<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi;
105
- const DSML_RE_ANY_TAG = /<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g;
106
- const DSML_RE_SKELETON = /<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi;
107
- const DSML_RE_JSON_CALLS = /|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi;
108
- // The leader/closer halves of DSML_RE_JSON_CALLS above, split out so the hold
109
- // logic can detect "the leader arrived but its closer has not" — an arbitrary
110
- // JSON blob sits between them with no '<' or recognizable structure of its
111
- // own, so nothing else below would otherwise hold it back.
112
- const DSML_RE_JSON_CALLS_OPEN = /|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi;
113
- const DSML_RE_JSON_CALLS_CLOSE = /|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi;
114
- const DSML_RE_ENVELOPE_TOKEN = /|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g;
115
- const DSML_RE_DRIFT_INVOKE = /<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi;
116
- const DSML_RE_DRIFT_PARAM = /<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi;
117
- const DSML_RE_PARAM_CLOSE = /<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi;
118
- const DSML_RE_ATTR = /([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
119
- const DSML_RE_STRUCT_TAG = /<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi;
120
- const DSML_RE_STRUCT_CLOSER = /<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi;
121
- /**
122
- * A COMPLETE (its own '>' has arrived) wrapper/leader tag that carries no
123
- * call of its own — observed verbatim: a bare `<||calls>`, with neither a
124
- * "tool_"/"function_" prefix (so DSML_RE_LEADER above misses it) nor a JSON
125
- * envelope pair. Safe to drop the moment it closes, UNLIKE invoke/parameter —
126
- * excluded here via negative lookahead so a *partial* invoke/parameter head is
127
- * never erased before its own close has a chance to pair it up with
128
- * DSML_RE_INVOKE/DSML_RE_PARAM on a later call once more of it has arrived.
129
- */
130
- const DSML_RE_WRAPPER_TAG = /<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g;
131
- /** A '<' (or '</') at the tail: the head of a tag whose pipe is still in flight. */
132
- const DSML_RE_TRAILING_LT = /<\s*\/?\s*$/;
133
- /** An in-flight identifier token: a pipe whose partner has not arrived yet. */
134
- const DSML_RE_OPEN_TOKEN = /^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/;
135
- /** Past this much buffered markup, a held tail is released as-is. */
136
- const DSML_HOLD_MAX = 4 * 1024 * 1024;
137
-
138
- /** The attributes of one tag head, lower-cased: name="write" → { name: 'write' }. */
139
- function dsmlAttrs(text) {
140
- const out = {};
141
- if (!text) return out;
142
- DSML_RE_ATTR.lastIndex = 0;
143
- let m;
144
- while ((m = DSML_RE_ATTR.exec(text))) out[m[1].toLowerCase()] = m[2] != null ? m[2] : m[3];
145
- return out;
146
- }
147
-
148
- /** A JSON parameter — or, when it is not JSON after all, the text it came as. */
149
- function dsmlJson(raw) {
150
- const s = String(raw == null ? '' : raw).trim();
151
- try {
152
- const v = JSON.parse(s);
153
- return v === undefined ? s : v;
154
- } catch {
155
- return s;
156
- }
157
- }
158
-
159
- /** The `parameter` tags of one `invoke` body, as a tool call's args object. */
160
- function dsmlArgs(body) {
161
- const args = {};
162
- DSML_RE_PARAM.lastIndex = 0;
163
- let p;
164
- while ((p = DSML_RE_PARAM.exec(body))) {
165
- const a = dsmlAttrs(p[1]);
166
- const key = a.name || a.key || `arg${Object.keys(args).length}`;
167
- const isJson = String(a.string || '').toLowerCase() === 'false' || String(a.json || '').toLowerCase() === 'true';
168
- args[key] = isJson ? dsmlJson(p[2]) : p[2];
169
- }
170
- return args;
171
- }
172
-
173
- /**
174
- * Decode every DSML tool call in `text` and return the two things a caller
175
- * needs: what may be shown, and what must be executed — `{ text, calls }`.
176
- * The generic `|…|` tokens are deliberately left in place here: an `invoke`
177
- * block still arriving is identified by its delimiters on the next pass, and
178
- * eating them early would lose the call's name and arguments. They are
179
- * removed from the *released* text instead (see dsmlResidue).
180
- */
181
- function decodeDeepSeekDSML(input) {
182
- if (typeof input !== 'string' || !input || input.indexOf('|') === -1) {
183
- return { text: input || '', calls: [] };
184
- }
185
- const calls = [];
186
- let text = input;
187
-
188
- // 1. One `invoke` block per call, the well-formed spelling.
189
- DSML_RE_INVOKE.lastIndex = 0;
190
- const spans = [];
191
- let m;
192
- while ((m = DSML_RE_INVOKE.exec(text))) {
193
- const a = dsmlAttrs(m[1]);
194
- const name = a.name || a.function || a.tool || '';
195
- if (name) calls.push({ name, args: dsmlArgs(m[2]) });
196
- spans.push([m.index, m.index + m[0].length]);
197
- }
198
- for (let i = spans.length - 1; i >= 0; i--) {
199
- text = text.slice(0, spans[i][0]) + text.slice(spans[i][1]);
200
- }
201
-
202
- // 2. The older spelling: a JSON array wrapped in envelope tokens.
203
- text = text.replace(DSML_RE_JSON_CALLS, (full, body) => {
204
- const parsed = dsmlJson(body);
205
- const list = Array.isArray(parsed) ? parsed : (parsed && Array.isArray(parsed.tool_calls) ? parsed.tool_calls : []);
206
- for (const c of list) {
207
- const fn = (c && c.function) || c || {};
208
- const name = fn.name || (c && c.name) || '';
209
- if (!name) continue;
210
- let args = fn.arguments != null ? fn.arguments : (c && c.arguments);
211
- if (typeof args === 'string') args = dsmlJson(args);
212
- calls.push({ name, args: args && typeof args === 'object' ? args : {} });
213
- }
214
- return '';
215
- });
216
-
217
- // 3. The wrapper tags carry no call of their own.
218
- text = text.replace(DSML_RE_LEADER, '');
219
- return { text, calls };
220
- }
221
-
222
- /**
223
- * Last-resort decode for markup that drifted out of well-formedness: a missing
224
- * closing tag, or a stream cut mid-call. The call still names a tool and its
225
- * parameters are still readable, so it is decoded rather than deleted — a call
226
- * that reached the wire must not vanish because its closing tag did.
227
- */
228
- function decodeDeepSeekDSMLDrift(input) {
229
- if (typeof input !== 'string' || !input || input.indexOf('|') === -1) return { text: input || '', calls: [] };
230
- const opens = [];
231
- DSML_RE_DRIFT_INVOKE.lastIndex = 0;
232
- let m;
233
- while ((m = DSML_RE_DRIFT_INVOKE.exec(input))) {
234
- opens.push({ at: m.index, attrs: m[1], body: DSML_RE_DRIFT_INVOKE.lastIndex });
235
- }
236
- if (!opens.length) return { text: input, calls: [] };
237
- const calls = [];
238
- let text = '';
239
- let cursor = 0;
240
- for (let i = 0; i < opens.length; i++) {
241
- // One call runs to the next `invoke` head, or to the end of the text.
242
- const end = i + 1 < opens.length ? opens[i + 1].at : input.length;
243
- const body = input.slice(opens[i].body, end);
244
- const a = dsmlAttrs(opens[i].attrs);
245
- const name = a.name || a.function || a.tool || '';
246
- const args = {};
247
- const params = [];
248
- DSML_RE_DRIFT_PARAM.lastIndex = 0;
249
- let pm;
250
- while ((pm = DSML_RE_DRIFT_PARAM.exec(body))) {
251
- params.push({ at: pm.index, attrs: pm[1], from: DSML_RE_DRIFT_PARAM.lastIndex });
252
- }
253
- for (let k = 0; k < params.length; k++) {
254
- // A value runs to the next parameter tag — its closing tag may be the
255
- // thing that never arrived.
256
- const stop = k + 1 < params.length ? params[k + 1].at : body.length;
257
- const raw = body.slice(params[k].from, stop).replace(DSML_RE_PARAM_CLOSE, '');
258
- const pa = dsmlAttrs(params[k].attrs);
259
- const key = pa.name || pa.key || `arg${Object.keys(args).length}`;
260
- const isJson = String(pa.string || '').toLowerCase() === 'false';
261
- args[key] = isJson ? dsmlJson(raw) : raw;
262
- }
263
- text += input.slice(cursor, opens[i].at);
264
- cursor = end;
265
- if (name) calls.push({ name, args });
266
- }
267
- text += input.slice(cursor);
268
- return { text, calls };
269
- }
270
-
271
- /**
272
- * Residue removal for text that is about to be shown. Two spellings have to go:
273
- * a leftover envelope token (`|DSML|`, `|tool▁calls▁begin|`, `|Assistant|`),
274
- * and the skeleton an earlier release left behind by stripping the delimiters
275
- * out of a DSML block — `<tool_calls> <invoke name="write"> <parameter …>`,
276
- * which is exactly what a user pasted back at us.
277
- */
278
- function dsmlResidue(text) {
279
- if (!text) return text;
280
- if (text.indexOf('|') === -1) return text.replace(DSML_RE_SKELETON, '');
281
- return text.replace(DSML_RE_ANY_TAG, '').replace(DSML_RE_SKELETON, '').replace(DSML_RE_ENVELOPE_TOKEN, '');
282
- }
283
-
284
- /**
285
- * Is the buffer, read from the first `|` in it, a construct that is still
286
- * arriving? Only two shapes may be held back: a pipe whose partner has not
287
- * arrived, and a DSML opener whose matching close has not landed. Everything
288
- * else is prose — a `|` in an answer is a character, not a promise of markup,
289
- * and holding the rest of the answer behind it would swallow the reply.
290
- */
291
- function dsmlUnterminated(s) {
292
- if (DSML_RE_OPEN_TOKEN.test(s)) return true;
293
- const openers = (s.match(DSML_RE_STRUCT_TAG) || []).length;
294
- const closers = (s.match(DSML_RE_STRUCT_CLOSER) || []).length;
295
- return openers > closers;
296
- }
297
-
298
- /**
299
- * Where, if anywhere, an in-flight DSML construct still needs the rest of the
300
- * buffer held back from view. By the time this runs, decodeDeepSeekDSML() has
301
- * already removed every COMPLETE invoke/parameter span and the caller has
302
- * already removed every complete non-invoke wrapper tag (DSML_RE_WRAPPER_TAG),
303
- * so whatever is left can only be: clean prose, or the start of exactly ONE
304
- * incomplete construct running to the end of the buffer — an opener whose own
305
- * '|' has arrived but not its '>' (`<\s*\/?\s*|`, found wherever it starts,
306
- * not just at the tail: a Write's `content` can be arbitrarily long, so the
307
- * unresolved opener is usually far behind the cursor, not at it), a '<' that
308
- * arrived with no '|' yet (the chunk boundary landed first), or a bare pipe
309
- * token still accumulating its identifier (the plain envelope-leak case, e.g.
310
- * '|tool▁cal'). Returns -1 when none apply — safe to release in full.
311
- */
312
- function dsmlHoldFrom(buf) {
313
- const tagStart = buf.search(/<\s*\/?\s*|/);
314
- if (tagStart !== -1) return tagStart;
315
- // The older JSON-array envelope (DSML_RE_JSON_CALLS): once its leader token
316
- // has arrived, hold everything until the matching closer token lands. An
317
- // arbitrary JSON blob sits between them with no '<' and no recognizable
318
- // per-character structure, so without this check it streams straight
319
- // through as visible prose the instant the leader's own closing '|'
320
- // arrives — the hold rule below only looks at ONE pipe token at a time and
321
- // has no notion of "waiting for a second, different token later on".
322
- const jsonOpenIdx = buf.search(DSML_RE_JSON_CALLS_OPEN);
323
- if (jsonOpenIdx !== -1 && buf.slice(jsonOpenIdx).search(DSML_RE_JSON_CALLS_CLOSE) === -1) {
324
- return jsonOpenIdx;
325
- }
326
- const lt = DSML_RE_TRAILING_LT.exec(buf);
327
- if (lt) return lt.index;
328
- const openIdx = buf.indexOf('|');
329
- if (openIdx !== -1 && dsmlUnterminated(buf.slice(openIdx))) return openIdx;
330
- return -1;
331
- }
332
-
333
- /**
334
- * The per-stream stripper the transports share. Feed it each `delta.content`
335
- * chunk: it returns the text that is safe to show, holds back whatever is
336
- * still arriving (a Write's `content` parameter is a whole file — it belongs
337
- * to the call, not to the screen), and collects the tool calls the model made
338
- * in text form. `flush()` releases the tail once the stream is drained, and
339
- * `calls()` returns everything decoded so far, which the caller merges into
340
- * the turn's tool calls so a Write that arrived as DSML is executed like any
341
- * other.
342
- */
343
- function makeDeepSeekEnvelopeStripper() {
344
- let buf = '';
345
- const calls = [];
346
- const strip = (chunk) => {
347
- buf += typeof chunk === 'string' ? chunk : '';
348
- const dec = decodeDeepSeekDSML(buf);
349
- buf = dec.text;
350
- for (const c of dec.calls) calls.push(c);
351
- buf = buf.replace(DSML_RE_WRAPPER_TAG, '');
352
- const hold = dsmlHoldFrom(buf);
353
- let out;
354
- if (hold !== -1 && buf.length - hold <= DSML_HOLD_MAX) {
355
- out = buf.slice(0, hold);
356
- buf = buf.slice(hold);
357
- } else {
358
- out = buf;
359
- buf = '';
360
- }
361
- return dsmlResidue(out);
362
- };
363
- // Unconditional release of whatever is left buffered — called once the
364
- // stream is fully drained, when a held-back construct is known to never
365
- // close (dropped connection, or it was real prose all along) rather than an
366
- // in-progress token.
367
- strip.flush = () => {
368
- const dec = decodeDeepSeekDSML(buf);
369
- buf = '';
370
- for (const c of dec.calls) calls.push(c);
371
- const drift = decodeDeepSeekDSMLDrift(dec.text);
372
- for (const c of drift.calls) calls.push(c);
373
- return dsmlResidue(drift.text);
374
- };
375
- /** Every tool call decoded from text so far, as `{ name, args }`. */
376
- strip.calls = () => calls.slice();
377
- return strip;
378
- }
379
-
380
- /**
381
- * UUID v4 that works everywhere: Web Crypto first (browsers, Node ≥ 19),
382
- * then Node's CJS crypto module (Node < 19), then a Math.random fallback for
383
- * sandboxed contexts (e.g. a VM or an opaque browser context) that expose no
384
- * crypto API at all. Used by hosts for session/conversation ids only.
385
- */
386
- function randomUUID() {
387
- const root =
388
- (typeof globalThis !== 'undefined' && globalThis) ||
389
- (typeof self !== 'undefined' && self) ||
390
- null;
391
- const c = root && root.crypto;
392
- if (c && typeof c.randomUUID === 'function') {
393
- try {
394
- return c.randomUUID();
395
- } catch (_) {
396
- /* fall through */
397
- }
398
- }
399
- if (c && typeof c.getRandomValues === 'function') {
400
- try {
401
- const b = new Uint8Array(16);
402
- c.getRandomValues(b);
403
- b[6] = (b[6] & 0x0f) | 0x40; // version 4
404
- b[8] = (b[8] & 0x3f) | 0x80; // variant 10
405
- const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
406
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
407
- } catch (_) {
408
- /* fall through */
409
- }
410
- }
411
- if (typeof require === 'function') {
412
- try {
413
- const nodeCrypto = require('crypto');
414
- if (nodeCrypto && typeof nodeCrypto.randomUUID === 'function') {
415
- return nodeCrypto.randomUUID();
416
- }
417
- } catch (_) {
418
- /* not Node — keep going */
419
- }
420
- }
421
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
422
- const r = (Math.random() * 16) | 0;
423
- const v = ch === 'x' ? r : (r & 0x3) | 0x8;
424
- return v.toString(16);
425
- });
426
- }
427
-
428
- const DEFAULT_API_BASE = 'https://aegiscloud.org';
429
- const CLIENT_VERSION = '3.2.0';
430
-
431
- /**
432
- * Every non-streaming request to aegis1 is bounded, and so is its body.
433
- *
434
- * The stream path has always had an idle watchdog (`readWithIdleTimeout`), but
435
- * the plain `apiPost`/`apiGet` calls — account state, memory, models, billing —
436
- * had none: `fetch` on a connection the server accepted and then never answered
437
- * waits forever. That is not hypothetical for this backend. aegis1 runs under
438
- * `gunicorn --worker-class gevent`, where a greenlet blocked on an upstream
439
- * provider call can hold a request open with no reply and no error, and the
440
- * host that called it hangs with no way out but force-quit. A caller-supplied
441
- * signal (if any) still works; this only adds a ceiling where there was none.
442
- */
443
- const DEFAULT_TIMEOUT_MS = 60000;
444
- /**
445
- * Cap on a single response body. A non-streaming endpoint that answers with an
446
- * unbounded body (a misrouted download, a proxy error page echoing a request
447
- * loop) would otherwise be read entirely into memory by `res.text()`.
448
- */
449
- const MAX_BODY_BYTES = 8 * 1024 * 1024;
450
-
451
- /**
452
- * 429 back-off. aegis1 rate-limits the BYOK relay per IP —
453
- * `rate_limit(f"byok:{ip}", max_calls=20, window=60)` in app.py — so a single
454
- * agentic turn (24–48 tool rounds, each one a relay call) bursts straight
455
- * through 20 requests in a minute and the turn dies mid-flight on a message
456
- * the user reads as a broken backend. The limit is the server's to set; what
457
- * this transport owes the caller is to treat a 429 as "slow down", not as a
458
- * fatal turn.
459
- *
460
- * Retries are bounded and the wait is capped, because the alternative to a
461
- * bounded back-off is a turn that hangs forever on a window that never opens.
462
- */
463
- const RATE_LIMIT_RETRIES = 4;
464
- /** Ceiling on a single wait, so a hostile/huge `Retry-After` cannot hang a turn. */
465
- const RATE_LIMIT_MAX_WAIT_MS = 30000;
466
- /** Base for the exponential fallback when the server sends no `Retry-After`. */
467
- const RATE_LIMIT_BASE_WAIT_MS = 1000;
468
-
469
- /**
470
- * aegis1's chat-completions generator (`app.py` `nexus_chat_completions`'s
471
- * `generate()`) wraps the whole upstream provider call in one `except
472
- * Exception`, and on ANY failure forwards `str(e)` as a mid-stream SSE error
473
- * frame: `{"error": {"message": str(e)[:200], "type": "server_error"}}`.
474
- * Headers are already sent 200 OK by then, so there is no status code to
475
- * tell a reset upstream socket apart from a real bug — both arrive as
476
- * `postStream` throwing with `status: 200` and the CLI/desktop host showing
477
- * `(backend error: [Errno 104] Connection reset by peer)` mid-turn.
478
- *
479
- * Narrowed to the Python exception messages a dropped TCP connection
480
- * actually produces (ConnectionResetError/BrokenPipeError/ConnectionAbortedError
481
- * and their usual Errno numbers), not every empty-turn error — a model that
482
- * legitimately returned nothing must still fail on the first try, not retry
483
- * forever. Only safe to retry when nothing streamed yet (`fullText` empty at
484
- * the throw site below): no visible content can be duplicated by redoing the
485
- * whole request from scratch.
486
- */
487
- const TRANSIENT_STREAM_ERROR_PATTERN =
488
- /connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i;
489
- const TRANSIENT_STREAM_RETRIES = 2;
490
- const TRANSIENT_STREAM_BASE_WAIT_MS = 500;
491
-
492
- /**
493
- * The sentence aegis1 puts in a mid-stream error frame when the UPSTREAM
494
- * provider call it was relaying hit its own deadline. Deliberately kept out of
495
- * TRANSIENT_STREAM_ERROR_PATTERN: a socket reset is worth re-issuing at once,
496
- * but a provider timeout has already spent a full deadline, so the same retry
497
- * would make a stuck upstream cost three of them before anything was said.
498
- *
499
- * It still has to be CLASSIFIED, not passed through raw. The frame arrives
500
- * after the stream's own 200 OK, so `res.status` is 200 — the throw used to be
501
- * stamped with that and reached the desktop host as `{ status: 200 }`, which
502
- * reads as a success to every downstream branch (engine.js keys its recovery
503
- * on `status === 402`/`400`; the renderer keys "waited too long" on status 0).
504
- */
505
- const SSE_UPSTREAM_TIMEOUT_PATTERN = /request timed out|timed out waiting|upstream timeout/i;
506
-
507
- /**
508
- * The message for a provider timeout, stating whose deadline expired.
509
- *
510
- * This used to read "the provider returned no answer within the 60s stream
511
- * budget (raise AEGIS_SSE_IDLE_TIMEOUT_MS for a slower provider)". Measured
512
- * live, that sentence was false in the one case it fired: the provider gave up
513
- * in ~11-13s and aegis1 relayed it, so the client's own watchdog never fired at
514
- * all — `sseError` is only ever set from a `json.error` frame, and our stall
515
- * raises its own `stream stalled - …` error from `readWithIdleTimeout` instead.
516
- * The advice pointed at an env var that provably cannot help, which is worse
517
- * than saying nothing: a user follows it, restarts, and the turn still fails.
518
- *
519
- * So the message separates the two deadlines and names elapsed time, which is
520
- * the fact that tells a reader which one it was without trusting the prose.
521
- * `elapsedMs` is omitted when the caller has no measured start (the
522
- * non-streaming path), rather than inventing one.
523
- */
524
- function upstreamTimeoutMessage(base, elapsedMs) {
525
- const took = Number(elapsedMs) > 0 ? ` after ${(Number(elapsedMs) / 1000).toFixed(1)}s` : '';
526
- return (
527
- `${base} — the upstream provider gave up before answering${took}. ` +
528
- "That is the provider's own deadline, not this client's stream budget, so " +
529
- 'raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help'
530
- );
531
- }
532
-
533
- /**
534
- * .mcp.json / Electron pass config as "${VAR}" template refs. When the var is
535
- * unset, hosts have been observed to leave the template literally unexpanded
536
- * (e.g. "${AEGIS_API_BASE}") instead of omitting it — which defeats a plain
537
- * `|| default` fallback since the literal string is truthy. Treat anything
538
- * shaped like an unexpanded template as absent.
539
- */
540
- function createClient(opts = {}) {
541
- const apiBase = (
542
- opts.apiBase ||
543
- envVar('AEGIS_API_BASE') ||
544
- DEFAULT_API_BASE
545
- ).replace(/\/+$/, '');
546
- let apiKey = opts.apiKey !== undefined ? opts.apiKey : envVar('AEGIS_API_KEY');
547
- // Optional: a memory token supplied directly, bypassing the api_key exchange.
548
- const memoryToken =
549
- opts.memoryToken !== undefined ? opts.memoryToken : envVar('AEGIS_MEMORY_TOKEN');
550
- const clientVersion = opts.clientVersion || CLIENT_VERSION;
551
- // Which host is asking, purely so an upgrade prompt raised from inside this
552
- // shared client is filed against the right product. aegis1 stores an
553
- // unrecognised source as NULL and reports it as `direct`, so an unknown
554
- // value here is a silently destroyed datapoint rather than a visible error —
555
- // hence the allowlist rather than trusting the caller.
556
- const channel = opts.channel === 'cli' ? 'cli' : 'desktop';
557
-
558
- /**
559
- * Strip the live API key out of anything on its way to a message, a log or a
560
- * renderer. Server error bodies echo the offending request often enough that
561
- * this is not theoretical: a 400 that repeats the request payload puts the
562
- * key into `err.message`, which hosts print to a terminal, a log file, and
563
- * (desktop) across an IPC boundary. The key is the one value in this module
564
- * whose leak is unrecoverable, so it is scrubbed at the boundary rather than
565
- * trusted not to appear.
566
- */
567
- function redact(value) {
568
- if (!apiKey || typeof value !== 'string') return value;
569
- return value.split(apiKey).join('[redacted]');
570
- }
571
-
572
- /**
573
- * Transport failure codes → what actually happened, in words that point at
574
- * the culprit. Names, not errno numbers, because "ECONNRESET" tells a user
575
- * nothing while "the connection was reset mid-request" tells them to retry.
576
- */
577
- const AEGIS_NETWORK_ERROR_HINTS = {
578
- ECONNRESET: 'connection reset by the backend',
579
- ECONNREFUSED: 'connection refused — is the backend running?',
580
- EPIPE: 'connection closed while sending the request',
581
- ETIMEDOUT: 'connection timed out',
582
- ENOTFOUND: 'host not found — check the endpoint URL',
583
- EAI_AGAIN: 'DNS lookup failed temporarily',
584
- EHOSTUNREACH: 'host unreachable',
585
- ENETUNREACH: 'network unreachable',
586
- CERT_HAS_EXPIRED: 'TLS certificate has expired',
587
- DEPTH_ZERO_SELF_SIGNED_CERT: 'TLS certificate is self-signed',
588
- UND_ERR_SOCKET: 'the socket closed before the response finished',
589
- UND_ERR_CLOSED: 'the connection was closed',
590
- UND_ERR_CONNECT_TIMEOUT: 'timed out connecting to the backend',
591
- UND_ERR_HEADERS_TIMEOUT: 'the backend accepted the connection but never sent a response',
592
- UND_ERR_BODY_TIMEOUT: 'the backend stalled mid-response',
593
- UND_ERR_ABORTED: 'the request was aborted',
594
- };
595
-
596
- /**
597
- * Turn a raw transport failure into something a person can act on.
598
- *
599
- * Node's undici raises `TypeError: fetch failed` for every socket-level
600
- * fault and puts the real reason on `err.cause` (`ECONNRESET`,
601
- * `UND_ERR_SOCKET`, `HeadersTimeoutError`, `ENOTFOUND`, …). Rethrown
602
- * untouched, the user sees the literal string `fetch failed`, which names
603
- * no component, no cause and no next step — and, worse, hides the fact that
604
- * the backend is the thing that dropped us rather than a bad request.
605
- *
606
- * The cause code, when there is one, is the single most useful fact here,
607
- * so it is promoted into `message` and kept on `cause`/`networkCode` for
608
- * callers that want to branch on it. Everything else about the error is
609
- * left alone.
610
- */
611
- function networkFailureError(err, base) {
612
- const reraised = err instanceof Error ? err : new Error(String(err));
613
- // The caller's own cancellation is not a failure and must stay untouched.
614
- const name = reraised && reraised.name;
615
- if (name === 'AbortError' || name === 'TimeoutError') return err;
616
- const detail = describeNetworkCause(reraised);
617
- const target = base || 'the backend';
618
- const e = new Error(
619
- detail
620
- ? `Could not reach ${target} (${detail}).`
621
- : `Could not reach ${target}: ${reraised.message || 'network failure'}.`
622
- );
623
- e.status = 0;
624
- e.code = 'network';
625
- e.networkCode = detail || null;
626
- e.data = null;
627
- e.cause = reraised;
628
- return e;
629
- }
630
-
631
- /** The innermost human-meaningful reason from an undici error chain. */
632
- function describeNetworkCause(err, depth = 0) {
633
- if (!err || depth > 4) return null;
634
- const code = err.code || (err.cause && err.cause.code);
635
- const inner = err.cause;
636
- const innerDetail = inner ? describeNetworkCause(inner, depth + 1) : null;
637
- if (AEGIS_NETWORK_ERROR_HINTS[code]) return AEGIS_NETWORK_ERROR_HINTS[code];
638
- if (innerDetail) return innerDetail;
639
- // An undici cause often carries only a message ("other side closed").
640
- if (inner && inner.message && inner.message !== err.message) return inner.message;
641
- return code || null;
642
- }
643
-
644
- /**
645
- * A bounded `fetch`: caller signal where there is one, an aborting timeout
646
- * where there is not. Returns the caller's abort untouched (so a host that
647
- * cancelled a turn still sees its own cancellation, not a timeout), and
648
- * raises a typed `timeout` error for the ceiling it added itself.
649
- */
650
- async function boundedFetch(url, init) {
651
- const callerSignal = init && init.signal;
652
- const controller = typeof AbortController === 'function' ? new AbortController() : null;
653
- let timer = null;
654
- const onAbort = () => {
655
- if (controller) controller.abort();
656
- };
657
- if (controller) {
658
- // `unref` where available: a pending timeout must never be the reason a
659
- // short-lived CLI process (`aegiscode -p "..."`) refuses to exit.
660
- timer = setTimeout(() => controller.abort(), timeoutMs);
661
- if (timer && typeof timer.unref === 'function') timer.unref();
662
- if (callerSignal) {
663
- if (callerSignal.aborted) controller.abort();
664
- else if (typeof callerSignal.addEventListener === 'function') {
665
- callerSignal.addEventListener('abort', onAbort, { once: true });
666
- }
667
- }
668
- }
669
- try {
670
- return await fetch(url, {
671
- ...(init || {}),
672
- signal: controller ? controller.signal : callerSignal,
673
- });
674
- } catch (err) {
675
- // Only claim a timeout when *we* aborted. A caller-originated abort is
676
- // the caller's business and is rethrown as-is.
677
- const ours =
678
- controller && controller.signal.aborted && !(callerSignal && callerSignal.aborted);
679
- if (ours) {
680
- const e = new Error(
681
- `Timed out after ${timeoutMs / 1000}s waiting for ${apiBase}.`
682
- );
683
- e.status = 0;
684
- e.code = 'timeout';
685
- e.data = null;
686
- throw e;
687
- }
688
- throw networkFailureError(err, apiBase);
689
- } finally {
690
- // The timeout is time-to-*headers* only, so it is cleared the moment the
691
- // response resolves: a long generation must never be cut off by it.
692
- if (timer) clearTimeout(timer);
693
- // …but the caller's abort bridge is deliberately NOT removed here.
694
- //
695
- // `fetch` resolves at the status line, while the RESPONSE BODY is still
696
- // bound to `controller.signal` and keeps being read long after this
697
- // function has returned. Unhooking the caller's signal at that point
698
- // detached Stop/Escape from the stream it was supposed to stop: the
699
- // engine's own controller really did abort — `engine.cancel()` answered
700
- // `{ ok: true }`, so the right controller was found and `abort()` was
701
- // really called — and nothing happened, because the only thing wired to
702
- // the live body had already been told to stop listening. The turn then
703
- // streamed to completion while the UI sat on "stopping…", never settled,
704
- // and never produced the salvaged bubble, because no error ever reached
705
- // the caller's catch.
706
- //
707
- // `once: true` plus one signal per turn bounds the cost of leaving it
708
- // attached to a single listener per turn — a far smaller price than a
709
- // cancel button that does nothing.
710
- }
711
- }
712
-
713
- /**
714
- * How long to hold off after a 429. The server's `Retry-After` wins when it
715
- * sends one, since only the server knows when the window actually opens; both
716
- * the delta-seconds and the HTTP-date form are accepted because either is
717
- * legal. Without the header — which is the case for aegis1's BYOK relay today,
718
- * it answers the bare 429 body — we back off exponentially from
719
- * RATE_LIMIT_BASE_WAIT_MS. Either way the wait is capped: an unclamped
720
- * `Retry-After` (or a hostile one) would otherwise be a turn that hangs.
721
- */
722
- function rateLimitDelayMs(res, attempt) {
723
- const header =
724
- res && res.headers && typeof res.headers.get === 'function'
725
- ? res.headers.get('retry-after')
726
- : null;
727
- let delay = 0;
728
- if (header) {
729
- const secs = Number(header);
730
- if (Number.isFinite(secs) && secs >= 0) {
731
- delay = secs * 1000;
732
- } else {
733
- const when = Date.parse(header);
734
- if (Number.isFinite(when)) delay = when - Date.now();
735
- }
736
- }
737
- if (!delay) delay = rateLimitBaseWaitMs * Math.pow(2, attempt);
738
- return Math.min(delay, rateLimitMaxWaitMs);
739
- }
740
-
741
- /**
742
- * Wait out a back-off. A mid-wait abort resolves rather than rejecting: the
743
- * retry that follows is issued on the caller's now-aborted signal, so `fetch`
744
- * rejects the way it would have anyway. Synthesising a second abort error here
745
- * would race the real one to the caller's catch and decide which of the two
746
- * they see — not this helper's call to make.
747
- */
748
- function sleep(ms, signal) {
749
- return new Promise((resolve) => {
750
- const timer = setTimeout(resolve, ms);
751
- if (timer && typeof timer.unref === 'function') timer.unref();
752
- if (!signal || typeof signal.addEventListener !== 'function') return;
753
- if (signal.aborted) {
754
- clearTimeout(timer);
755
- resolve();
756
- return;
757
- }
758
- signal.addEventListener(
759
- 'abort',
760
- () => {
761
- clearTimeout(timer);
762
- resolve();
763
- },
764
- { once: true }
765
- );
766
- });
767
- }
768
-
769
- /**
770
- * `boundedFetch` with a 429 back-off. Retries are bounded (RATE_LIMIT_RETRIES)
771
- * so a window that never opens still fails — and fails with the server's own
772
- * 429 body, since the last response is returned unread to `parseResponse`
773
- * rather than being replaced by a home-made "gave up" error. The caller keeps
774
- * the message the user was already seeing; it just arrives after the transport
775
- * did what it could.
776
- */
777
- async function fetchWithRateLimitRetry(url, init) {
778
- let res = await boundedFetch(url, init);
779
- for (let attempt = 0; res && res.status === 429 && attempt < rateLimitRetries; attempt++) {
780
- const wait = rateLimitDelayMs(res, attempt);
781
- try {
782
- // The 429 body is discarded unread either way — releasing it is what
783
- // keeps a long back-off from pinning the socket.
784
- if (res.body) await res.body.cancel();
785
- } catch {
786
- /* discarded anyway */
787
- }
788
- await sleep(wait, init && init.signal);
789
- res = await boundedFetch(url, init);
790
- }
791
- // The NON-streaming twin of postStream's mid-stream transient retry below:
792
- // aegis1's chat-completions route drains the same generate() generator
793
- // itself when the caller sent `stream: false`, and on the SAME exception
794
- // (a reset socket to the provider) returns it as a plain 503 —
795
- // `{"error":{"message":"[Errno 104] Connection reset by peer","type":
796
- // "server_error"}}` — not a 200 SSE frame, because no response has been
797
- // sent yet on this branch. Peeked via a clone so a non-matching body (a
798
- // real 503 — insufficient balance, "not configured" — is untouched for
799
- // `parseResponse` to read and surface normally, unretried.
800
- for (
801
- let attempt = 0;
802
- res && res.status >= 500 && res.status < 600 && attempt < TRANSIENT_STREAM_RETRIES;
803
- attempt++
804
- ) {
805
- let text = '';
806
- try {
807
- text = await readCappedText(res.clone());
808
- } catch {
809
- break; // body already disturbed or unclonable — surface res as-is
810
- }
811
- if (!TRANSIENT_STREAM_ERROR_PATTERN.test(text)) break;
812
- await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, attempt), init && init.signal);
813
- res = await boundedFetch(url, init);
814
- }
815
- return res;
816
- }
817
-
818
- /** Read a response body, refusing to buffer more than MAX_BODY_BYTES. */
819
- async function readCappedText(res) {
820
- if (!res || !res.body || typeof res.body.getReader !== 'function') {
821
- const text = await res.text();
822
- return text.length > maxBodyBytes ? text.slice(0, maxBodyBytes) : text;
823
- }
824
- const reader = res.body.getReader();
825
- const decoder = new TextDecoder();
826
- let out = '';
827
- let total = 0;
828
- try {
829
- for (;;) {
830
- const { done, value } = await reader.read();
831
- if (done) break;
832
- total += value ? value.byteLength : 0;
833
- if (total > maxBodyBytes) {
834
- const e = new Error(
835
- `Response from ${apiBase} exceeded the ${maxBodyBytes / (1024 * 1024)}MB cap.`
836
- );
837
- e.status = res.status;
838
- e.code = 'body_too_large';
839
- e.data = null;
840
- throw e;
841
- }
842
- out += decoder.decode(value, { stream: true });
843
- }
844
- out += decoder.decode();
845
- return out;
846
- } finally {
847
- // Release the socket on every path, including the cap trip and any
848
- // decoder throw — otherwise a rejected body keeps the connection alive.
849
- try {
850
- await reader.cancel();
851
- } catch {
852
- /* already released */
853
- }
854
- }
855
- }
856
-
857
- let memoryTokenCache = null;
858
-
859
- // Injectable ceilings. A guard that can only be exercised by sleeping for a
860
- // minute, or by allocating 9MB, is a guard that quietly rots — so the
861
- // transport takes both limits as options (and an env override, so a host can
862
- // tighten them without a code change). The defaults are the production ones.
863
- const timeoutMs =
864
- Number(opts.timeoutMs) > 0
865
- ? Number(opts.timeoutMs)
866
- : Number(envVar('AEGIS_HTTP_TIMEOUT_MS')) > 0
867
- ? Number(envVar('AEGIS_HTTP_TIMEOUT_MS'))
868
- : DEFAULT_TIMEOUT_MS;
869
- const maxBodyBytes =
870
- Number(opts.maxBodyBytes) > 0 ? Number(opts.maxBodyBytes) : MAX_BODY_BYTES;
871
- // The 429 back-off is injectable for the same reason as the two ceilings
872
- // above: a guard that can only be exercised by sleeping out a real
873
- // 15-second window is a guard that quietly rots. Defaults are the production
874
- // values (the RATE_LIMIT_* constants at the top of this module).
875
- const rateLimitRetries =
876
- Number(opts.rateLimitRetries) >= 0 ? Number(opts.rateLimitRetries) : RATE_LIMIT_RETRIES;
877
- const rateLimitBaseWaitMs =
878
- Number(opts.rateLimitBaseWaitMs) >= 0
879
- ? Number(opts.rateLimitBaseWaitMs)
880
- : RATE_LIMIT_BASE_WAIT_MS;
881
- const rateLimitMaxWaitMs =
882
- Number(opts.rateLimitMaxWaitMs) > 0
883
- ? Number(opts.rateLimitMaxWaitMs)
884
- : RATE_LIMIT_MAX_WAIT_MS;
885
-
886
- /**
887
- * A campaign-tagged upgrade link. Never hand-build a `/subscribe` URL in a
888
- * prompt: the bare form carries no attribution, so the click arrives as
889
- * `direct` and the surface that produced it can never be credited.
890
- * The campaign must be one of the ids fixed in `docs/upgrade-conversion-plan.md`
891
- * §1 (`welcome_cloud`, `queue_cap`, `memory_quota`, `status_card`,
892
- * `topup_bank`) — a sixth id invented here is a row no report or allowlist
893
- * knows about, which is the same destroyed datapoint as an untagged link.
894
- * The slug is checked against aegis1's `_sanitize_signup_slug` shape rather
895
- * than an allowlist, because this module is shared by every host and cannot
896
- * know the server's current list.
897
- * Returns '' if the base is not a parseable absolute URL, so a caller can
898
- * fall back to plain text instead of rendering "undefined" at a user.
899
- */
900
- function promptUrl(page, campaign) {
901
- try {
902
- const url = new URL(`/go/${String(page || 'upgrade').replace(/^\/+|\/+$/g, '')}`, apiBase);
903
- url.searchParams.set('s', channel);
904
- const c = String(campaign || '').trim().toLowerCase();
905
- if (/^[a-z0-9][a-z0-9_-]{0,63}$/.test(c)) url.searchParams.set('c', c);
906
- return url.toString();
907
- } catch (e) {
908
- return '';
909
- }
910
- }
911
-
912
- // -------------------------------------------------------------------------
913
- // HTTP helpers
914
- // -------------------------------------------------------------------------
915
-
916
- /** Base headers every request carries (version gate + key when present). */
917
- function authHeaders(extra) {
918
- const headers = {
919
- 'Content-Type': 'application/json',
920
- 'X-AEGIS-Version': clientVersion,
921
- ...extra,
922
- };
923
- // Keys are optional per-client (a BYOK-only browser page has none); when
924
- // absent, omit the auth headers entirely so no empty values are sent.
925
- if (apiKey) {
926
- headers['X-API-Key'] = apiKey;
927
- headers.Authorization = `Bearer ${apiKey}`;
928
- }
929
- return headers;
930
- }
931
-
932
- async function apiPost(path, body, headers, opts) {
933
- const res = await fetchWithRateLimitRetry(`${apiBase}${path}`, {
934
- method: 'POST',
935
- headers: headers || authHeaders(),
936
- body: JSON.stringify(body || {}),
937
- signal: opts && opts.signal,
938
- });
939
- return parseResponse(res);
940
- }
941
-
942
- async function apiGet(path, headers, opts) {
943
- const res = await fetchWithRateLimitRetry(`${apiBase}${path}`, {
944
- method: 'GET',
945
- headers: headers || authHeaders(),
946
- signal: opts && opts.signal,
947
- });
948
- return parseResponse(res);
949
- }
950
-
951
- /**
952
- * A 426 `version_mismatch` from either server gate: this client is too old
953
- * to be served. The body carries the minimum it failed (`required`), the
954
- * npm dist-tags to move to (`latest_cli`/`latest_desktop`) and where to get
955
- * them, so a host can show an upgrade prompt naming a target instead of a
956
- * bare "connection refused".
957
- *
958
- * Surfaced as a typed error (`code` + `upgrade`) rather than only a message
959
- * so hosts can branch on it without parsing prose, and so the desktop/MCP
960
- * shells can open the upgrade panel with a version already filled in.
961
- *
962
- * The upgrade link is rebuilt through promptUrl() rather than trusting
963
- * `update_url` verbatim: a server-supplied bare URL carries no `?s=`/`?c=`,
964
- * so the click is filed as `direct` and the surface that hit the gate can
965
- * never be credited for the conversion it caused. The server value is kept
966
- * as a fallback for hosts reaching a base we cannot parse.
967
- */
968
- function versionGateError(data, status) {
969
- const body = data || {};
970
- const latestCli = body.latest_cli || '';
971
- const latestDesktop = body.latest_desktop || '';
972
- // Prefer a real published version; fall back to the minimum so the
973
- // message always names something the user can act on.
974
- const target = latestCli || latestDesktop || body.required || '';
975
- const err = new Error(
976
- target
977
- ? `This client (v${clientVersion}) is out of date — upgrade to v${target}.`
978
- : `This client (v${clientVersion}) is out of date.`
979
- );
980
- err.status = status;
981
- err.code = 'version_mismatch';
982
- err.data = body;
983
- err.upgrade = {
984
- required: body.required || '',
985
- latestCli,
986
- latestDesktop,
987
- // Campaign is `version_gate`: a refusal to serve is its own reason to
988
- // pay, distinct from a quota wall, and summing them hides which lever
989
- // the upgrade prompt is actually pulling.
990
- //
991
- // Guarded on typeof, not called directly: the attribution helper is a
992
- // separate concern from the gate, and a gate that throws because the
993
- // campaign tagger is absent would turn "your client is old" into
994
- // "undefined is not a function" on the one path whose whole job is to
995
- // tell the user what to do. Falls back to the server's own update_url.
996
- url: (typeof promptUrl === 'function' ? promptUrl('upgrade', 'version_gate') : '')
997
- || body.update_url
998
- || '',
999
- };
1000
- return err;
1001
- }
1002
-
1003
- /** Is this error body the version gate rather than a normal failure? */
1004
- function isVersionGate(status, data) {
1005
- return status === 426 || (data && data.code === 'version_mismatch');
1006
- }
1007
-
1008
- async function parseResponse(res) {
1009
- const text = await readCappedText(res);
1010
- let data;
1011
- try {
1012
- data = text ? JSON.parse(text) : {};
1013
- } catch {
1014
- // An unparseable body is often a proxy/error page that quotes the
1015
- // request, so it goes through redaction too.
1016
- data = { raw: redact(text) };
1017
- }
1018
- if (!res.ok) {
1019
- if (isVersionGate(res.status, data)) {
1020
- throw versionGateError(data, res.status);
1021
- }
1022
- const msg =
1023
- (data && (data.error?.message || data.error || data.message)) ||
1024
- `HTTP ${res.status}`;
1025
- const err = new Error(redact(typeof msg === 'string' ? msg : JSON.stringify(msg)));
1026
- // The buffered twin of postStream's upstream-timeout classification.
1027
- //
1028
- // Aegis1 answers a NON-streaming request by draining the same generator
1029
- // itself, so the provider's deadline arrives here as a plain 503 carrying
1030
- // the same sentence a streaming caller gets as an error frame. Without
1031
- // this the one failure had two shapes depending on wire form: the stream
1032
- // path said `status 0 / code timeout` with an explanation, while the
1033
- // buffered path said `status 503 / code undefined` and nothing else —
1034
- // measured live, same provider, same 10s wall, ~10.8s either way. A host
1035
- // gating on `code === 'timeout'` therefore saw it on one path only.
1036
- //
1037
- // Status becomes 0 for the same reason as the stream path: this is
1038
- // "waited too long", which every downstream branch already reads as
1039
- // status 0 + code, and a 5xx would instead be taken as a server fault.
1040
- // The server's own number is preserved on `serverStatus`, because 5xx is
1041
- // worth knowing even when it means the same thing to the caller.
1042
- const upstreamTimeout =
1043
- res.status >= 500 && res.status < 600 && SSE_UPSTREAM_TIMEOUT_PATTERN.test(err.message);
1044
- if (upstreamTimeout) {
1045
- err.serverStatus = res.status;
1046
- err.status = 0;
1047
- err.code = 'timeout';
1048
- err.message = upstreamTimeoutMessage(err.message);
1049
- } else {
1050
- err.status = res.status;
1051
- }
1052
- err.data = data;
1053
- throw err;
1054
- }
1055
- // A 2xx carrying a version gate body: some streaming endpoints answer
1056
- // JSON with a real status mid-stream. Without this the gate would be
1057
- // invisible on exactly those paths.
1058
- if (data && data.code === 'version_mismatch') {
1059
- throw versionGateError(data, res.status);
1060
- }
1061
- return data;
1062
- }
1063
-
1064
- /** Extract a human message from a structured backend error body. */
1065
- function errorMessageOf(data) {
1066
- if (!data) return '';
1067
- const e = data.error;
1068
- if (typeof e === 'string') return e;
1069
- if (e && typeof e.message === 'string') return e.message;
1070
- if (e && typeof e.error === 'string') return e.error;
1071
- if (typeof data.message === 'string') return data.message;
1072
- if (typeof data.error_message === 'string') return data.error_message;
1073
- return '';
1074
- }
1075
-
1076
- /** Throw an Error carrying status/data from a 2xx body that still has an
1077
- * error field (seen on streaming endpoints that answer JSON mid-stream). */
1078
- function throwErrorFrom(data, status) {
1079
- // Keep the gate typed on this path too: it is the one that carries JSON
1080
- // errors inside an otherwise-successful stream, which is where a gate
1081
- // response would otherwise be flattened into a generic message.
1082
- if (data && data.code === 'version_mismatch') {
1083
- throw versionGateError(data, status || 426);
1084
- }
1085
- const msg = redact(errorMessageOf(data));
1086
- if (!msg) return;
1087
- const err = new Error(msg);
1088
- err.status = status || 500;
1089
- err.data = data;
1090
- throw err;
1091
- }
1092
-
1093
- // Memory endpoints authenticate with a memory_token, not the API key.
1094
- async function getMemoryToken() {
1095
- if (memoryToken) return memoryToken;
1096
- if (memoryTokenCache) return memoryTokenCache;
1097
- const info = await apiPost('/api/verify-api-key', { api_key: apiKey });
1098
- if (!info || !info.memory_token) {
1099
- // The campaign is Phase 1's `memory_quota`, not a new `memory_token`: the
1100
- // prompt family (memory cap notice, memory list, memory view) files under
1101
- // one id so the funnel keeps one row per prompt intent, and the plan's
1102
- // five ids are what the telemetry allowlist and the baseline table carry.
1103
- const link = promptUrl('upgrade', 'memory_quota');
1104
- throw new Error(
1105
- 'This AEGIS account has no memory token. '
1106
- + (link
1107
- ? `Enable cloud memory at ${link}`
1108
- : 'Enable cloud memory in your AEGIS account settings.')
1109
- );
1110
- }
1111
- memoryTokenCache = info.memory_token;
1112
- return memoryTokenCache;
1113
- }
1114
-
1115
- function memoryHeaders(token) {
1116
- return {
1117
- 'Content-Type': 'application/json',
1118
- 'X-AEGIS-Version': clientVersion,
1119
- Authorization: `Bearer ${token}`,
1120
- };
1121
- }
1122
-
1123
- /**
1124
- * Replace the API key at runtime (desktop in-app key entry). Clears the
1125
- * cached memory token so the next memory/account call re-exchanges with the
1126
- * new key. Returns the trimmed raw key — main-process only; hosts must mask
1127
- * it before returning anything to a renderer.
1128
- */
1129
- function setApiKey(key) {
1130
- apiKey = typeof key === 'string' ? key.trim() : '';
1131
- memoryTokenCache = null;
1132
- return apiKey;
1133
- }
1134
-
1135
- // -------------------------------------------------------------------------
1136
- // High-level API (returns raw backend data; hosts decide how to format it)
1137
- // -------------------------------------------------------------------------
1138
-
1139
- async function verifyApiKey() {
1140
- return apiPost('/api/verify-api-key', { api_key: apiKey });
1141
- }
1142
-
1143
- /**
1144
- * Ask aegis1 for a free device key when the caller has none configured yet
1145
- * (`POST /api/v1/auth/register-device`). Idempotent server-side on
1146
- * `fingerprint` — the same fingerprint always returns the same account's
1147
- * key rather than minting a new one. A BRAND-NEW fingerprint (first call
1148
- * ever for this machine) is additionally granted aegis1's 30-day
1149
- * welcome-trial `unlimited` entitlement in the SAME request that mints the
1150
- * key — a token-bank credit of UNLIMITED_CLOUD_ALLOWANCE_MICROS plus a
1151
- * time-boxed `subscriptions` row (aegis1 commit 4372830), so a fresh
1152
- * install can use pooled cloud models immediately instead of starting at a
1153
- * zero balance. Re-registering an already-known fingerprint does NOT
1154
- * re-grant it; the pool balance gate still applies once the allowance is
1155
- * spent or the 30 days lapse. Sends no API key of its own — there isn't
1156
- * one yet. `opts.app` names the host ('cli' | 'desktop' | 'mcp') so the
1157
- * server files this machine under its real name, not 'other'.
1158
- */
1159
- async function registerDevice(fingerprint, opts) {
1160
- return apiPost('/api/v1/auth/register-device', { fingerprint, app: opts && opts.app }, undefined, opts);
1161
- }
1162
-
1163
- /** Build the OpenAI-style messages array from either a full history or the
1164
- * single-shot { system, prompt } shorthand.
1165
- *
1166
- * The history is no longer returned verbatim when present: doing so dropped
1167
- * `system` entirely, so the agent loop's ported persona disappeared on this
1168
- * transport alone. The system turn is prepended unless the caller already
1169
- * supplied one, and a non-empty `prompt` is appended as a final user turn
1170
- * (skipped when the history already ends with that same turn). */
1171
- function buildMessages(messages, system, prompt) {
1172
- const history = Array.isArray(messages) ? messages.filter(Boolean) : [];
1173
- const out = [];
1174
- if (system && !history.some((m) => m && m.role === 'system')) {
1175
- out.push({ role: 'system', content: system });
1176
- }
1177
- out.push(...history);
1178
- if (prompt != null && prompt !== '') {
1179
- const last = out[out.length - 1];
1180
- if (!(last && last.role === 'user' && last.content === prompt)) {
1181
- out.push({ role: 'user', content: prompt });
1182
- }
1183
- }
1184
- return out;
1185
- }
1186
-
1187
- /**
1188
- * Chat completion against the AEGIS pool (API key auth). Non-streaming by
1189
- * default (structured JSON error bodies — this is what the MCP host relies
1190
- * on). When `stream: true` AND `onStream` is a function, the request is sent
1191
- * with `stream: true` and each SSE delta is delivered as `onStream({ delta })`.
1192
- * The resolved value is normalised to the same shape as the non-streaming
1193
- * response either way, so hosts can reconcile final text after the last chunk.
1194
- *
1195
- * Additive options shared with byokChatCompletion():
1196
- * - `messages` full OpenAI-format history (supersedes prompt/system)
1197
- * - `extra` extra body fields merged verbatim (e.g. { aegis_memory,
1198
- * session } for the online host's synced-memory writeback)
1199
- * - `onReasoning` receives `delta.reasoning_content` text as it streams
1200
- * (pool-brain worker findings). Kept off the answer channel
1201
- * so a reasoning-only stream still counts as unanswered.
1202
- * - `idleTimeoutMs` override the stalled-stream watchdog for this call
1203
- * (a worker fan-out is legitimately silent between passes)
1204
- * - `maxTokens` output ceiling. Omitted from the body when absent so the
1205
- * server's own budget applies — on a pooled request that is
1206
- * the `effort` ladder, and a number sent from here caps it.
1207
- * - `effort` / `workers` pooled-brain budget rung and fan-out size.
1208
- * Forwarded only inside `extra`, as the server reads them off
1209
- * the body (aegis1 services/pool_brain.py parse_brain_request)
1210
- * and sizes the budget from them.
1211
- */
1212
- async function chatCompletion({
1213
- prompt,
1214
- system,
1215
- messages,
1216
- model,
1217
- mode,
1218
- maxTokens,
1219
- stream = false,
1220
- onStream,
1221
- onReasoning,
1222
- idleTimeoutMs,
1223
- includeUsage,
1224
- signal,
1225
- extra,
1226
- // Opt-in only: the caller (the agent loop, which already knows whether
1227
- // the tools it just attached to `extra` are code-capable) decides
1228
- // whether this turn needs one — this file has no policy of its own for
1229
- // when to attach it, only how. See aegis1 services/agent_gate.py
1230
- // CODE_TOOLS for the server-side verb list a caller should mirror.
1231
- agentKey,
1232
- } = {}) {
1233
- // Model-first: an explicit `model` pins that provider id verbatim; with no
1234
- // model the server picks its default (no client-invented tier id). `mode`
1235
- // is a legacy server-side shorthand — forwarded verbatim only when the
1236
- // caller supplies it, never defaulted, never built into a model id.
1237
- //
1238
- // `max_tokens` is omitted entirely when the caller states none, rather than
1239
- // defaulted here. The server has its own budget ladder (`mode`/`effort` on
1240
- // the pooled path) and treats a body max_tokens as a *ceiling* over it, so
1241
- // an invented 4096 was not a harmless default: it capped every pass of a
1242
- // pooled-brain fan-out at 4096 and overrode the ladder the caller's effort
1243
- // selected. Omitting it is the documented way to say "server default" (see
1244
- // mcp/tools.js's max_tokens description).
1245
- const body = {
1246
- messages: buildMessages(messages, system, prompt),
1247
- ...(maxTokens ? { max_tokens: maxTokens } : {}),
1248
- ...(extra || {}),
1249
- };
1250
- if (model) body.model = model;
1251
- else if (mode) body.mode = mode;
1252
- const headers = authHeaders(agentKey ? { 'X-AEGIS-Agent-Key': agentKey } : undefined);
1253
- if (!stream || typeof onStream !== 'function') {
1254
- // `signal` must be forwarded here. It was not, and the consequence was
1255
- // silent: a caller that aborted a non-streaming turn saw the abort
1256
- // ignored, the request ran on to its timeout, and the eventual error was
1257
- // a timeout the user never asked for. postStream's own fallback at the
1258
- // bottom of this function always forwarded it — only this branch did not.
1259
- return decodeDsmlInResult(
1260
- await apiPost('/api/v1/chat/completions', { ...body, stream: false }, headers, { signal })
1261
- );
1262
- }
1263
- // An OpenAI-compatible SSE response carries no `usage` unless the caller
1264
- // asks for it (`stream_options.include_usage`). Without this the streamed
1265
- // AEGIS pool call — the only path the desktop uses for the Nexus brain —
1266
- // resolved with no usage at all, so a pooled turn could report its text but
1267
- // never what it spent, while the same model through the non-streaming MCP
1268
- // path reported both. Only the streaming request sets it: `stream_options`
1269
- // is invalid alongside `stream:false`, so the non-stream branch above and
1270
- // every non-stream fallback must stay clean.
1271
- if (includeUsage) body.stream_options = { include_usage: true };
1272
- return postStream('/api/v1/chat/completions', body, headers, onStream, signal, {
1273
- onReasoning,
1274
- idleTimeoutMs,
1275
- // A server that predates `stream_options` 400s the whole request; the
1276
- // stream is worth more than the token count, so retry on the wire without
1277
- // the hint before sacrificing streaming for the non-stream fallback.
1278
- retryWithoutStreamOptions: Boolean(includeUsage),
1279
- });
1280
- }
1281
-
1282
- /**
1283
- * BYOK chat completion: relay a provider request through
1284
- * /api/v1/byok/chat/completions using a per-request X-Provider-Key. The
1285
- * provider key never touches AEGIS storage — it is forwarded straight to the
1286
- * provider for this request only. Mirrors chatCompletion()'s streaming /
1287
- * fallback semantics exactly.
1288
- *
1289
- * The caller's *AEGIS* key is sent alongside the provider key as X-AEGIS-Key.
1290
- * Two credentials, two headers, on purpose: the provider key authenticates the
1291
- * upstream call, the AEGIS key says whose bank pays the handling fee —
1292
- * `_byok_identify_user` on the server resolves the payer from it, and nothing
1293
- * else. With no AEGIS key the header is omitted and the call is anonymous;
1294
- * THIS function still sends it, because it is a transport and the route is
1295
- * unauthenticated by design (aegis1 tests/test_byok_fee.py pins the anonymous
1296
- * path as allowed) — refusing here would break every other caller of a
1297
- * published endpoint.
1298
- *
1299
- * Attribution is the whole game, because an unattributed turn is the one way
1300
- * a BYOK call escapes the fee: the relay serves it, `charge_byok` never runs
1301
- * (`app.py` charges only `if _byok_user_id:`), and the call is logged against
1302
- * user 0 as uncollected — a free ride. So the shipped HOSTS refuse a keyless
1303
- * BYOK send before the relay is reached: desktop/lib/local/engine.js raises
1304
- * 401, and the desktop app and the CLI share that engine (the CLI stages it
1305
- * as cli/vendor/desktop/lib/local/engine.js), so one gate covers both. Every
1306
- * turn is then attributable, and therefore billable: a funded balance is
1307
- * debited, an unfunded one is recorded as owed — `charge_byok` clamps the
1308
- * debit at zero and never refuses the call, so "cannot pay" and "must not be
1309
- * billed" stop being the same thing. `AEGIS_BYOK_REQUIRE_BALANCE` (off by
1310
- * default) remains the server's own, separate 402 gate and is not what makes
1311
- * the fee land.
1312
- */
1313
- async function byokChatCompletion({
1314
- provider = 'openai',
1315
- model,
1316
- messages,
1317
- prompt,
1318
- system,
1319
- maxTokens,
1320
- effort,
1321
- reasoningEffort,
1322
- tools,
1323
- toolChoice,
1324
- stream = false,
1325
- onStream,
1326
- signal,
1327
- providerKey,
1328
- baseURL,
1329
- } = {}) {
1330
- const key = providerKey !== undefined ? providerKey : opts.providerKey;
1331
- // `custom` is the one catalog provider whose address the server does NOT
1332
- // know: every other id maps to a host aegis1 has baked in, and `custom`
1333
- // travels as `base_url` on each request instead. So a custom call that
1334
- // names no endpoint is not "a provider we can guess a default for" — there
1335
- // is no default to guess, and aegis1 answers 400 (`_byok_custom_base_url`
1336
- // refuses it). Refusing HERE turns that server-side 400 into a client-side
1337
- // sentence naming the missing half, which is the difference between "custom
1338
- // is broken" and "you saved a key but never saved the endpoint".
1339
- //
1340
- // Reachable without the card: `/byok-key custom <key>` saves a key alone,
1341
- // and a hand-edited row can hold a key with no address. Guarded on the
1342
- // value actually being absent (`!baseURL`), never on the provider alone, so
1343
- // a correctly-saved custom row is untouched.
1344
- if (provider === 'custom' && !baseURL) {
1345
- const err = new Error(
1346
- 'the "custom" provider dials the endpoint you name, and this call names none — ' +
1347
- 'save the address first: /model-add custom <https-base-url> <api-key> <model-id>, ' +
1348
- 'or the endpoint field in Settings › Provider (custom).'
1349
- );
1350
- err.status = 400;
1351
- err.code = 'custom_endpoint_missing';
1352
- throw err;
1353
- }
1354
- // Same rule as the pooled path above: omit `max_tokens` entirely when the
1355
- // caller states none, rather than inventing a default. The server treats a
1356
- // body max_tokens as a ceiling *over* its own ladder, so a defaulted 4096
1357
- // was not a harmless floor — it capped the call at 4k and overrode the
1358
- // budget the caller's effort selected, exactly as on the pooled path.
1359
- //
1360
- // This survived the earlier fix (which only touched chatCompletion) and the
1361
- // guard meant to catch it, because test/budget.test.mjs searched for a
1362
- // direct assignment of 4096 to maxTokens while the defect here is a
1363
- // fallback expression inside the body literal — the verifier could not see
1364
- // the shape it was written to forbid. (The guard now reads this file as
1365
- // text, comments included, so this note names no forbidden literal.)
1366
- const body = {
1367
- provider,
1368
- messages: buildMessages(messages, system, prompt),
1369
- ...(maxTokens ? { max_tokens: maxTokens } : {}),
1370
- // Native effort knobs, forwarded verbatim and ONLY when a caller states
1371
- // one — never invented here, because a made-up level overrides the
1372
- // vendor's own default. The field name is not portable: DeepSeek's
1373
- // Anthropic-compatible surface takes `effort` (low|high|max), while the
1374
- // OpenAI-shaped vendors take `reasoning_effort` (low|medium|high). The
1375
- // caller translates the rung per dialect and names the field, so neither
1376
- // field is ever sent blind to a strict validator — Groq answers 400 for
1377
- // any level outside a model's supported set, so a misfiled knob is a
1378
- // failed turn, not a harmless extra key.
1379
- ...(effort ? { effort } : {}),
1380
- ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
1381
- // Forwarded only when the caller actually supplied a schema — aegis1's
1382
- // byok_chat_completions (app.py) reads `tools`/`tool_choice` off the body
1383
- // and passes each to the provider only `if tools:`, so an empty array
1384
- // here would still be a behavioural change for a provider that treats
1385
- // `tools: []` differently from the field's plain absence.
1386
- ...(Array.isArray(tools) && tools.length ? { tools } : {}),
1387
- ...(toolChoice ? { tool_choice: toolChoice } : {}),
1388
- // Read server-side ONLY for provider "custom" (aegis1 app.py
1389
- // byok_chat_completions) — every other provider's upstream host is a
1390
- // constant the server already knows, so sending this for them is a
1391
- // no-op rather than a behaviour change.
1392
- ...(baseURL ? { base_url: baseURL } : {}),
1393
- };
1394
- if (model) body.model = model;
1395
- const headers = {
1396
- 'Content-Type': 'application/json',
1397
- 'X-AEGIS-Version': clientVersion,
1398
- 'X-Provider-Key': key,
1399
- };
1400
- // Identify the payer. Absent key => anonymous call, which the server
1401
- // accepts but cannot bill; sending it is what turns a BYOK turn into
1402
- // billable traffic instead of a free ride.
1403
- if (apiKey) headers['X-AEGIS-Key'] = apiKey;
1404
- if (!stream || typeof onStream !== 'function') {
1405
- return decodeDsmlInResult(await apiPost('/api/v1/byok/chat/completions', { ...body, stream: false }, headers));
1406
- }
1407
- return postStream('/api/v1/byok/chat/completions', body, headers, onStream, signal);
1408
- }
1409
-
1410
- /** Extract the assistant text from a full (non-streamed) completion JSON. */
1411
- function textOf(data) {
1412
- const choice = data && data.choices && data.choices[0];
1413
- const content = choice && (choice.message && choice.message.content);
1414
- return typeof content === 'string' ? content : '';
1415
- }
1416
-
1417
- /**
1418
- * One-shot DSML decode for a non-streamed completion: the whole answer
1419
- * already arrived in one JSON payload, so there is no partial-token hold-
1420
- * back to do — just decode, drift-decode what the well-formed pass missed,
1421
- * and strip whatever residue would otherwise render as garble. Mutates and
1422
- * returns `data` so every non-stream return site in this module can wrap
1423
- * its result the same way the streaming path's `message.content` is clean.
1424
- */
1425
- function decodeDsmlInResult(data) {
1426
- const choice = data && data.choices && data.choices[0];
1427
- const content = choice && choice.message && choice.message.content;
1428
- if (typeof content !== 'string' || content.indexOf('|') === -1) return data;
1429
- const once = decodeDeepSeekDSML(content);
1430
- const drift = decodeDeepSeekDSMLDrift(once.text);
1431
- choice.message.content = dsmlResidue(drift.text);
1432
- const calls = [...once.calls, ...drift.calls];
1433
- if (calls.length) {
1434
- data.toolCalls = [
1435
- ...(Array.isArray(data.toolCalls) ? data.toolCalls : []),
1436
- ...calls.map((c) => ({ id: '', name: c.name, args: c.args || {} })),
1437
- ];
1438
- }
1439
- return data;
1440
- }
1441
-
1442
- /**
1443
- * POST body with `stream: true` and forward SSE deltas to onStream.
1444
- * Shared by the AEGIS pool and the BYOK relay so every host parses exactly
1445
- * one wire format.
1446
- *
1447
- * Handles two servers gracefully:
1448
- * - a real SSE endpoint -> incremental deltas, normalised final result
1449
- * - an endpoint that ignores `stream` and replies with plain JSON (or
1450
- * rejects `stream: true` outright) -> one-shot fallback: deliver the full
1451
- * text as a single delta and resolve the parsed JSON, unchanged.
1452
- * This keeps streaming purely additive for hosts that opt in.
1453
- */
1454
- async function postStream(path, body, headers, onStream, signal, streamOpts) {
1455
- const {
1456
- onReasoning, idleTimeoutMs, retryWithoutStreamOptions,
1457
- _transientStreamAttempt: transientStreamAttempt = 0,
1458
- } = streamOpts || {};
1459
- const request = (payload) =>
1460
- // `boundedFetch` here bounds time-to-*headers* only: fetch resolves when
1461
- // the status line lands, and the timer is cleared in its `finally`, so a
1462
- // legitimately long generation is never cut off by it. What it does fix is
1463
- // the gap the idle watchdog cannot reach — a server that accepts the
1464
- // socket and never sends response headers, where `reader.read()` has not
1465
- // been reached yet and so nothing is watching at all.
1466
- fetchWithRateLimitRetry(`${apiBase}${path}`, {
1467
- method: 'POST',
1468
- headers,
1469
- body: JSON.stringify({ ...payload, stream: true }),
1470
- signal,
1471
- });
1472
- let res;
1473
- try {
1474
- res = await request(body);
1475
- } catch (err) {
1476
- throw err; // network-level failure; nothing to fall back to
1477
- }
1478
-
1479
- // A version gate is a pre-flight refusal, not a schema complaint: the
1480
- // server rejects *every* shape of this request with 426, so the
1481
- // `stream_options` retry below and the `stream: false` fallback after it
1482
- // each buy a wasted round-trip and then report an opaque status. Fail on
1483
- // the first one. Checked by status alone (no body read) so the happy path
1484
- // pays nothing for this.
1485
- if (!res.ok && res.status === 426) {
1486
- let gateData = {};
1487
- try {
1488
- // Capped like every other body read: a gate response is still a
1489
- // response from a host we do not control the size of.
1490
- const t = await readCappedText(res);
1491
- gateData = t ? JSON.parse(t) : {};
1492
- } catch {
1493
- gateData = {}; // a gate with an unreadable body is still a gate
1494
- }
1495
- throw versionGateError(gateData, res.status);
1496
- }
1497
-
1498
- // Ask for the token count, but never at the cost of the stream: a server
1499
- // that predates `stream_options` rejects the request outright, so drop that
1500
- // one hint and put it back on the wire before falling back to a non-stream
1501
- // response (which would answer in one lump and end the live paint).
1502
- if (!res.ok && retryWithoutStreamOptions && body.stream_options) {
1503
- try {
1504
- if (res.body) await res.body.cancel();
1505
- } catch {
1506
- /* the failed response is being discarded anyway */
1507
- }
1508
- const cleanBody = { ...body };
1509
- delete cleanBody.stream_options;
1510
- body = cleanBody;
1511
- try {
1512
- res = await request(body);
1513
- } catch (err) {
1514
- throw err;
1515
- }
1516
- }
1517
-
1518
- if (!res.ok) {
1519
- // The endpoint may not accept `stream: true`. Retry once without it so
1520
- // the caller gets the normal structured JSON (result or error). Strip
1521
- // `stream_options` too — it is only legal with `stream: true`, so leaving
1522
- // it on would turn this graceful fallback into a second rejection.
1523
- const cleanBody = { ...body };
1524
- delete cleanBody.stream_options;
1525
- // `signal` is forwarded here too: this is the *non-stream fallback* of a
1526
- // stream call, i.e. the path taken when the server answered a streaming
1527
- // request with plain JSON. Dropping the signal here meant an aborted turn
1528
- // kept waiting on a request nobody was listening for any more — the
1529
- // caller had already moved on, and the host held the socket.
1530
- const data = decodeDsmlInResult(await apiPost(path, { ...cleanBody, stream: false }, headers, { signal }));
1531
- const fullText = textOf(data);
1532
- if (fullText) onStream({ delta: fullText });
1533
- return data;
1534
- }
1535
-
1536
- const contentType = res.headers.get('content-type') || '';
1537
- if (!contentType.includes('text/event-stream')) {
1538
- // Server ignored the stream flag and answered with plain JSON.
1539
- const data = decodeDsmlInResult(await parseResponse(res));
1540
- const fullText = textOf(data);
1541
- if (fullText) {
1542
- onStream({ delta: fullText });
1543
- } else {
1544
- throwErrorFrom(data, res.status);
1545
- }
1546
- return data;
1547
- }
1548
-
1549
- // Real SSE: parse `data:` lines incrementally, OpenAI-chunk shape.
1550
- const reader = res.body.getReader();
1551
- const decoder = new TextDecoder();
1552
- let buffer = '';
1553
- let fullText = '';
1554
- // Mirrors fullText for the reasoning channel so a reasoning SNAPSHOT is
1555
- // deduplicated the same way a content snapshot is.
1556
- let reasoningText = '';
1557
- let resultModel = body.model;
1558
- let usage = null;
1559
- let sseError = '';
1560
- // Tool-call fragments, keyed by the provider's index. The pool forwards
1561
- // the provider's own `delta.tool_calls` chunks verbatim when the caller
1562
- // sent `tools`, so the shared client has to reassemble them the same way
1563
- // the non-streaming branch does — otherwise a tool-calling turn would
1564
- // resolve with text only and the caller could never see the calls.
1565
- const toolCallsByIndex = new Map();
1566
- let finishReason = null;
1567
- // `fullText` above stays RAW (it is also the `seen` cursor the snapshot
1568
- // reconciliation below compares against the provider's own un-stripped
1569
- // snapshots); `cleanText` is what the caller actually receives — the same
1570
- // stream, with DeepSeek's chat-template envelope removed — and is what the
1571
- // final `message.content` below is built from, so a non-streaming caller
1572
- // reading the resolved result sees the same clean text a streaming caller
1573
- // already saw via `onStream`.
1574
- let cleanText = '';
1575
- const stripEnvelope = makeDeepSeekEnvelopeStripper();
1576
-
1577
- // Idle watchdog: if the server holds the connection open without ever
1578
- // sending another byte (a stuck upstream call, a proxy that swallows the
1579
- // close), reader.read() below waits forever and the whole desktop host
1580
- // hangs with no way out but force-quit. Cap the gap between chunks —
1581
- // not the whole response — so a slow-but-alive generation is untouched.
1582
- //
1583
- // The budget is per *response*, not per call site: a pooled brain call
1584
- // announces its worker fan-out in the X-AEGIS-Brain response header, and a
1585
- // fan-out is legitimately silent until its first worker returns. Keying the
1586
- // longer budget on a request the caller remembered to flag left the
1587
- // default Nexus turn (brain model id, checkbox off) dying at 60s — with
1588
- // the server already past its own fan-out deadline and every worker
1589
- // billed. See idleBudgetFor().
1590
- // The budget is measured from the last real `data:` frame, not from the
1591
- // last read. SSE keep-alive comments (": keep-alive") are transport
1592
- // framing, and a stalled upstream can emit them forever: a watchdog armed
1593
- // per read() is reset by every one of them and so never fires, which is
1594
- // exactly the hang this guard exists to prevent. Only a parsed payload
1595
- // moves `lastPayloadAt` below.
1596
- const idleMs = idleBudgetFor(res, idleTimeoutMs);
1597
- let lastPayloadAt = Date.now();
1598
- // When this response began, for the one place that needs to tell the two
1599
- // deadlines apart: a provider timeout frame carries no duration, and the
1600
- // elapsed time is what separates "the upstream gave up" (seconds, well
1601
- // inside our budget) from "our own watchdog fired" (the full budget).
1602
- const streamStartedAt = lastPayloadAt;
1603
- let keepAlives = 0;
1604
- async function readWithIdleTimeout() {
1605
- let timer;
1606
- let onAbort = null;
1607
- const remaining = Math.max(0, idleMs - (Date.now() - lastPayloadAt));
1608
- const timeout = new Promise((_, reject) => {
1609
- timer = setTimeout(() => {
1610
- reject(new Error(
1611
- keepAlives > 0
1612
- ? `stream stalled - only keep-alives for ${idleMs / 1000}s`
1613
- : `stream stalled - no data for ${idleMs / 1000}s`
1614
- ));
1615
- }, remaining);
1616
- });
1617
- // The caller's abort, raced against the read directly rather than trusted
1618
- // to propagate through the body stream.
1619
- //
1620
- // Whether an abort of the caller's signal reaches a response body that is
1621
- // already being read is a property of `boundedFetch`, not of this loop —
1622
- // and it is not a property this loop can observe. Racing here makes "the
1623
- // caller stopped" a fact the read loop establishes for itself, so Stop
1624
- // and Escape end the turn at the next chunk boundary regardless of how
1625
- // the request's signal was assembled. Without it an aborted turn kept
1626
- // consuming a stream nobody wanted and `chat()` never settled at all.
1627
- const aborted = signal && typeof signal.addEventListener === 'function'
1628
- ? new Promise((_, reject) => {
1629
- onAbort = () => {
1630
- const e = new Error('The turn was stopped.');
1631
- e.name = 'AbortError';
1632
- e.code = 'ABORT_ERR';
1633
- reject(e);
1634
- };
1635
- if (signal.aborted) onAbort();
1636
- else signal.addEventListener('abort', onAbort, { once: true });
1637
- })
1638
- : null;
1639
- try {
1640
- return await (aborted
1641
- ? Promise.race([reader.read(), timeout, aborted])
1642
- : Promise.race([reader.read(), timeout]));
1643
- } finally {
1644
- clearTimeout(timer);
1645
- if (signal && onAbort && typeof signal.removeEventListener === 'function') {
1646
- signal.removeEventListener('abort', onAbort);
1647
- }
1648
- }
1649
- }
1650
-
1651
- for (;;) {
1652
- let done, value;
1653
- try {
1654
- ({ done, value } = await readWithIdleTimeout());
1655
- } catch (err) {
1656
- reader.cancel().catch(() => {});
1657
- throw err;
1658
- }
1659
- if (done) break;
1660
- buffer += decoder.decode(value, { stream: true });
1661
-
1662
- const lines = buffer.split('\n');
1663
- buffer = lines.pop(); // keep the last partial line for the next read
1664
-
1665
- for (const rawLine of lines) {
1666
- const line = rawLine.trim();
1667
- if (!line.startsWith('data:')) {
1668
- if (line.startsWith(':')) keepAlives++;
1669
- continue;
1670
- }
1671
- lastPayloadAt = Date.now(); // a real frame: the stream is still speaking
1672
- const payload = line.slice(5).trim();
1673
- if (!payload || payload === '[DONE]') continue;
1674
- let json;
1675
- try {
1676
- json = JSON.parse(payload);
1677
- } catch {
1678
- continue; // partial/keepalive line — ignore
1679
- }
1680
- if (json.error) {
1681
- if (!sseError) {
1682
- const e = json.error;
1683
- sseError =
1684
- typeof e === 'string'
1685
- ? e
1686
- : errorMessageOf({ error: e }) || 'stream error';
1687
- sseError = redact(sseError);
1688
- }
1689
- continue;
1690
- }
1691
- if (json.model) resultModel = json.model;
1692
- if (json.usage) usage = json.usage;
1693
- const choice = json.choices && json.choices[0];
1694
- if (choice && choice.finish_reason) finishReason = choice.finish_reason;
1695
- // Extended-reasoning trace: the pool's worker findings (and any
1696
- // provider CoT) arrive as `delta.reasoning_content` *before* the
1697
- // synthesis pass writes the visible answer. Deliberately kept out of
1698
- // `fullText` — deliberation is not an answer, and counting it would
1699
- // make a no-answer turn look answered to every caller's empty-check.
1700
- // `delta.*` is an INCREMENT; `message.*` is a SNAPSHOT of the whole
1701
- // message so far. Collapsing them with `||` made a stream that ends
1702
- // with a message snapshot append the entire answer a second time —
1703
- // the duplicated text in the CLI. They are merged here through one
1704
- // helper that emits only what the caller has not already seen.
1705
- const advance = (increment, snapshot, seen, emit) => {
1706
- if (typeof increment === 'string' && increment) {
1707
- emit(increment);
1708
- return seen + increment;
1709
- }
1710
- if (typeof snapshot === 'string' && snapshot) {
1711
- if (!seen) { emit(snapshot); return snapshot; }
1712
- // The usual shape: the snapshot restates everything streamed so
1713
- // far, so only the tail is new.
1714
- if (snapshot.startsWith(seen)) {
1715
- const tail = snapshot.slice(seen.length);
1716
- if (tail) emit(tail);
1717
- return snapshot;
1718
- }
1719
- // Disjoint from what was already shown — cannot be reconciled, and
1720
- // appending it would duplicate. Keep what the caller has seen.
1721
- return seen;
1722
- }
1723
- return seen;
1724
- };
1725
-
1726
- reasoningText = advance(
1727
- choice && choice.delta && choice.delta.reasoning_content,
1728
- choice && choice.message && choice.message.reasoning_content,
1729
- reasoningText,
1730
- (chunk) => {
1731
- if (typeof onReasoning === 'function') onReasoning(chunk);
1732
- else onStream({ reasoning: chunk });
1733
- }
1734
- );
1735
-
1736
- fullText = advance(
1737
- choice && choice.delta && choice.delta.content,
1738
- choice && choice.message && choice.message.content,
1739
- fullText,
1740
- (chunk) => {
1741
- const clean = stripEnvelope(chunk);
1742
- if (clean) {
1743
- cleanText += clean;
1744
- onStream({ delta: clean });
1745
- }
1746
- }
1747
- );
1748
- const fragments =
1749
- (choice && choice.delta && choice.delta.tool_calls) ||
1750
- (choice && choice.message && choice.message.tool_calls);
1751
- if (Array.isArray(fragments)) {
1752
- for (const tc of fragments) {
1753
- const idx = tc.index == null ? 0 : tc.index;
1754
- const cur = toolCallsByIndex.get(idx) || {
1755
- id: '',
1756
- type: 'function',
1757
- function: { name: '', arguments: '' },
1758
- };
1759
- if (tc.id) cur.id = tc.id;
1760
- if (tc.type) cur.type = tc.type;
1761
- const fn = tc.function || {};
1762
- if (fn.name) cur.function.name = fn.name;
1763
- if (typeof fn.arguments === 'string') cur.function.arguments += fn.arguments;
1764
- toolCallsByIndex.set(idx, cur);
1765
- }
1766
- }
1767
- }
1768
- }
1769
-
1770
- if (!fullText && sseError) {
1771
- if (
1772
- transientStreamAttempt < TRANSIENT_STREAM_RETRIES
1773
- && TRANSIENT_STREAM_ERROR_PATTERN.test(sseError)
1774
- ) {
1775
- await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, transientStreamAttempt), signal);
1776
- return postStream(path, body, headers, onStream, signal, {
1777
- ...streamOpts,
1778
- _transientStreamAttempt: transientStreamAttempt + 1,
1779
- });
1780
- }
1781
- // Deliberately NOT retried: this sentence is aegis1 relaying an upstream
1782
- // abort ("Provider request timed out") as a mid-stream error frame with
1783
- // the headers already 200 OK — the same frame shape as the reset above,
1784
- // but the stall has already cost the caller a full provider deadline, and
1785
- // re-issuing would make a stuck upstream cost three of them before the
1786
- // host could say anything. One attempt, classified, and out.
1787
- //
1788
- // What must NOT happen is the shape this used to be thrown in: `res.status`
1789
- // here is the SSE response's own 200 (the headers landed long before the
1790
- // error frame did), so the rejection carried "success" as its status and
1791
- // nothing downstream could classify it — the desktop host printed the raw
1792
- // stack with `{ status: 200 }` for a turn that never produced a byte. A
1793
- // timeout is stated in the shape every other "waited too long" on this
1794
- // lane uses (status 0 + a code), which is what engine.js's `status === 402`
1795
- // / `status === 400` branches already key off and what local.js translates
1796
- // its own two clocks into — so "waited too long" stays one branch for
1797
- // every class.
1798
- //
1799
- // Message: the budget is NOT named as the cause any more, because this
1800
- // branch cannot be our own watchdog. `sseError` comes only from a
1801
- // `json.error` frame the server sent; our watchdog raises `stream
1802
- // stalled - …` out of readWithIdleTimeout and never reaches this code.
1803
- // So every error here is the provider's deadline, already expired, and
1804
- // the elapsed time says so as a fact rather than as prose — see
1805
- // upstreamTimeoutMessage().
1806
- const timedOut = SSE_UPSTREAM_TIMEOUT_PATTERN.test(sseError);
1807
- const err = new Error(
1808
- timedOut
1809
- ? upstreamTimeoutMessage(sseError, Date.now() - streamStartedAt)
1810
- : sseError
1811
- );
1812
- err.status = timedOut ? 0 : res.status;
1813
- if (timedOut) err.code = 'timeout';
1814
- throw err;
1815
- }
1816
-
1817
- // A trailing '|…' that never closed (stream ended right after it, or it
1818
- // was real prose all along) is real content, not an unfinished envelope
1819
- // token — release it rather than dropping it silently.
1820
- const strayTail = stripEnvelope.flush();
1821
- if (strayTail) {
1822
- cleanText += strayTail;
1823
- onStream({ delta: strayTail });
1824
- }
1825
-
1826
- // An id-less fragment stream still yields usable calls, but the caller
1827
- // needs *an* id to pair results back, so synthesize one.
1828
- const toolCalls = [...toolCallsByIndex.entries()]
1829
- .sort((a, b) => a[0] - b[0])
1830
- .map(([idx, c]) => ({ ...c, id: c.id || `call_${idx}` }));
1831
-
1832
- // The hidden chain-of-thought belongs on the RESULT, not only on the live
1833
- // stream. `reasoningText` above is accumulated and forwarded to the caller's
1834
- // `onReasoning`/`onStream` so the thinking can be shown while it happens —
1835
- // but the resolved result carried only `content`, so every down-stream
1836
- // diagnosis of "the model spent the whole budget thinking and never wrote a
1837
- // word" read an empty reasoning channel on THIS lane and concluded there had
1838
- // been no thinking at all.
1839
- //
1840
- // That is not a cosmetic loss. desktop/lib/local/engine.js decides its
1841
- // reasoning-only recovery from exactly this field (`reasonedButSilent` →
1842
- // `reasoningTextOf(res)`), so on byok the gate was dead code: DeepSeek
1843
- // returns `finish_reason: 'stop'` with empty content and a full
1844
- // `reasoning_content`, which matched neither `isTruncated` (the reason says
1845
- // 'stop', not 'length') nor the reasoning retry (nothing to detect), and the
1846
- // turn fell straight through to emptyTurnError — the "backend error: the
1847
- // model returned no answer … max_tokens 16384" the user sees. Measured live
1848
- // on byok/deepseek-v4-flash 2026-10-11.
1849
- //
1850
- // Kept out of `content` on purpose: deliberation is not an answer, and
1851
- // folding it in would make a no-answer turn look answered to every caller's
1852
- // empty-check (see the note at the `reasoningText` accumulation above).
1853
- const message = { content: cleanText };
1854
- if (reasoningText) message.reasoning_content = reasoningText;
1855
- if (toolCalls.length) message.tool_calls = toolCalls;
1856
- const result = {
1857
- model: resultModel,
1858
- choices: [
1859
- { message, ...(finishReason ? { finish_reason: finishReason } : {}) },
1860
- ],
1861
- };
1862
- if (usage) result.usage = usage;
1863
- // DSML calls arrive as plain text, decoded by stripEnvelope rather than
1864
- // accumulated by index like structured delta.tool_calls — merged into one
1865
- // normalised `{ id, name, args }` list so a tool call that arrived as DSML
1866
- // (no provider-native delta.tool_calls at all) is executed like any other.
1867
- // engine.js's extractToolCalls() reads this field first, ahead of
1868
- // message.tool_calls.
1869
- const dsmlCalls = stripEnvelope.calls();
1870
- if (toolCalls.length || dsmlCalls.length) {
1871
- result.toolCalls = [
1872
- ...toolCalls.map((c) => ({ id: c.id, name: c.function.name, args: c.function.arguments })),
1873
- ...dsmlCalls.map((c) => ({ id: '', name: c.name, args: c.args || {} })),
1874
- ];
1875
- }
1876
- return result;
1877
- }
1878
-
1879
- /**
1880
- * The read-only GETs take an optional `opts` so a host can cancel them.
1881
- * Without it no non-streaming call in this module could be aborted at all:
1882
- * the signal had nowhere to travel, so `boundedFetch` always fell back to its
1883
- * own ceiling and a caller's cancel was silently ignored.
1884
- */
1885
- async function listModels(opts) {
1886
- return apiGet('/api/v1/models', null, opts);
1887
- }
1888
-
1889
- async function tokenBankBalance(opts) {
1890
- return apiGet('/api/token-bank/balance', null, opts);
1891
- }
1892
-
1893
- /** Start a token-bank top-up; resolves to { url } for the payment page.
1894
- * aegis1 requires a signed-in account (403/401 without a key) and rejects
1895
- * an amount outside 2..1000 EUR with 400. */
1896
- async function tokenBankTopup(amountEur) {
1897
- return apiPost('/api/token-bank/topup', { amount_eur: amountEur });
1898
- }
1899
-
1900
- /** Start a plan checkout; resolves to { url } for Stripe's hosted page.
1901
- * aegis1 `/api/billing/checkout` is deliberately public (the Stripe page
1902
- * collects the email), so this works with no key configured — but answers
1903
- * 503 `setup_required` while the price id is unset on the server. */
1904
- async function billingCheckout() {
1905
- return apiPost('/api/billing/checkout', {});
1906
- }
1907
-
1908
- async function byokStatus(opts) {
1909
- return apiGet('/api/user/api-keys', null, opts);
1910
- }
1911
-
1912
- /** The server's BYOK provider catalog: which providers accept a key, which
1913
- * models each unlocks, where to get the key, and the prefix a valid key
1914
- * starts with. Deliberately NOT key-gated — "which key do I go get, and
1915
- * what will it unlock?" is the question asked *before* an AEGIS key exists.
1916
- * An AEGIS key, if present, only adds the `configured` column. */
1917
- async function byokProviders(opts) {
1918
- return apiGet('/api/v1/byok/providers', null, opts);
1919
- }
1920
-
1921
- async function byokSet(provider, providerApiKey) {
1922
- return apiPost('/api/user/api-keys', {
1923
- provider,
1924
- api_key: providerApiKey || '',
1925
- });
1926
- }
1927
-
1928
- async function memorySearch(query, limit) {
1929
- const token = await getMemoryToken();
1930
- return apiPost(
1931
- '/api/memory/search',
1932
- { query: query || '', limit: limit || 5 },
1933
- memoryHeaders(token)
1934
- );
1935
- }
1936
-
1937
- async function memorySave(entry) {
1938
- const token = await getMemoryToken();
1939
- return apiPost('/api/memory/save', { entry }, memoryHeaders(token));
1940
- }
1941
-
1942
- async function memoryList(limit) {
1943
- const token = await getMemoryToken();
1944
- // /api/memory/list is session-cookie (dashboard) auth, unusable here.
1945
- // The bearer-authenticated way to get recent entries is search with an
1946
- // empty query, which the backend returns most-recent-first.
1947
- return apiPost(
1948
- '/api/memory/search',
1949
- { query: '', limit: limit || 10 },
1950
- memoryHeaders(token)
1951
- );
1952
- }
1953
-
1954
- /** Verify a bearer token (memory or API) against the backend. */
1955
- async function verifyToken(token) {
1956
- return apiPost(
1957
- '/api/verify-token',
1958
- { token: token || '' },
1959
- {
1960
- 'Content-Type': 'application/json',
1961
- 'X-AEGIS-Version': clientVersion,
1962
- Authorization: `Bearer ${token}`,
1963
- }
1964
- );
1965
- }
1966
-
1967
- /** Activate cloud memory for the authenticated account. */
1968
- async function memoryActivate(token) {
1969
- const t = token || (await getMemoryToken());
1970
- return apiPost('/api/memory/activate', {}, memoryHeaders(t));
1971
- }
1972
-
1973
- /** Pull memory entries updated since a timestamp (epoch ms). */
1974
- async function memoryPull(since) {
1975
- const token = await getMemoryToken();
1976
- return apiPost(
1977
- '/api/memory/pull',
1978
- { since: since || 0 },
1979
- memoryHeaders(token)
1980
- );
1981
- }
1982
-
1983
- /** Save a batch of memory entries in one request. */
1984
- async function memorySaveBatch(entries) {
1985
- const token = await getMemoryToken();
1986
- return apiPost(
1987
- '/api/memory/save',
1988
- { entries: entries || [] },
1989
- memoryHeaders(token)
1990
- );
1991
- }
1992
-
1993
- /**
1994
- * Push one local conversation transcript to aegis1's conversation-sync
1995
- * surface (P4.5), authenticated the same way as the memory endpoints
1996
- * (memory_token, not the API key — see getMemoryToken()). The response is
1997
- * returned verbatim; callers read `session_id`/`sessions` off it.
1998
- */
1999
- async function conversationSyncPush(transcript) {
2000
- const token = await getMemoryToken();
2001
- return apiPost(
2002
- '/api/conversations/sync',
2003
- {
2004
- session_id: transcript && transcript.session_id,
2005
- title: (transcript && transcript.title) || '',
2006
- messages: (transcript && transcript.messages) || [],
2007
- source: (transcript && transcript.source) || 'aegis-desktop',
2008
- },
2009
- memoryHeaders(token)
2010
- );
2011
- }
2012
-
2013
- /** Pull the account's remote conversation sessions (no transcript to push —
2014
- * same endpoint, list-only request). */
2015
- async function conversationSyncPull() {
2016
- const token = await getMemoryToken();
2017
- return apiPost('/api/conversations/sync', {}, memoryHeaders(token));
2018
- }
2019
-
2020
- /** Import a conversation transcript for later memory/training use. */
2021
- async function importConversation({ messages, url, title, source } = {}) {
2022
- return apiPost('/api/import', {
2023
- messages: messages || [],
2024
- url: url || '',
2025
- title: title || '',
2026
- source: source || 'aegiscode-plugin',
2027
- });
2028
- }
2029
-
2030
- /**
2031
- * aegis1's stored Google Drive connection for this account (`GET
2032
- * /api/drive/token` — app.py's `get_drive_token`), authenticated with the
2033
- * ordinary API key (the same header `authHeaders()` already sends, which
2034
- * that route accepts alongside its session-cookie path). Resolves
2035
- * `{connected, access_token, email}` — `connected: false` with no error
2036
- * when this account has never run the browser's `/connect/drive` consent
2037
- * screen (the route's 404: a real account, just nothing saved yet), since
2038
- * "not yet connected" is the expected answer on every account until it
2039
- * does. A 401 is a DIFFERENT fact — this key is not valid at all — so it is
2040
- * left to throw rather than folded into the same "not connected" reading,
2041
- * which would hide a real credential problem behind the normal first-run
2042
- * state. The access token is refreshed server-side from the stored refresh
2043
- * token on every call, so a caller never has to reason about expiry.
2044
- */
2045
- async function driveToken() {
2046
- try {
2047
- return await apiGet('/api/drive/token');
2048
- } catch (e) {
2049
- if (e && e.status === 404) {
2050
- return { connected: false, access_token: null, email: null };
2051
- }
2052
- throw e;
2053
- }
2054
- }
2055
-
2056
- return {
2057
- apiBase,
2058
- get apiKey() {
2059
- return apiKey;
2060
- },
2061
- setApiKey,
2062
- get clientVersion() {
2063
- return clientVersion;
2064
- },
2065
- get channel() {
2066
- return channel;
2067
- },
2068
- promptUrl,
2069
- verifyApiKey,
2070
- registerDevice,
2071
- chatCompletion,
2072
- byokChatCompletion,
2073
- listModels,
2074
- tokenBankBalance,
2075
- tokenBankTopup,
2076
- billingCheckout,
2077
- byokStatus,
2078
- byokProviders,
2079
- byokSet,
2080
- getMemoryToken,
2081
- memorySearch,
2082
- memorySave,
2083
- memoryList,
2084
- verifyToken,
2085
- memoryActivate,
2086
- memoryPull,
2087
- memorySaveBatch,
2088
- conversationSyncPush,
2089
- conversationSyncPull,
2090
- importConversation,
2091
- driveToken,
2092
- randomUUID,
2093
- };
2094
- }
2095
-
2096
- /** Gap between SSE chunks that counts as "the stream is dead", in ms. */
2097
- const SSE_IDLE_TIMEOUT_MS = 60_000;
2098
-
2099
- /**
2100
- * Gap allowed while a pooled brain call runs its worker fan-out, in ms.
2101
- *
2102
- * The fan-out yields a header chunk and then says nothing until its FIRST
2103
- * worker pass returns — and each worker is a full reasoning-model call at
2104
- * roughly 1/(workers+1) of the effort budget, so the silent window is minutes,
2105
- * not seconds. The server bounds that window itself
2106
- * (``services/pool_brain.py`` ``NEXUS_BRAIN_WORKER_TIMEOUT``, default 600s) and
2107
- * announces it per-response with the ``X-AEGIS-Brain`` header, so this budget
2108
- * has to outlast the *server's* deadline: aborting first kills a healthy turn
2109
- * the server is still running and billing.
2110
- *
2111
- * Raising the server's env var above ~14 minutes requires raising this too.
2112
- * desktop/lib/local/engine.js mirrors the same value for the explicit
2113
- * "work autonomously" path (AUTONOMOUS_IDLE_TIMEOUT_MS); the desktop test
2114
- * test/autonomous-mode.test.mjs fails if either drops below the server default.
2115
- */
2116
- const BRAIN_IDLE_TIMEOUT_MS = 15 * 60_000;
2117
-
2118
- /**
2119
- * Idle budget for one SSE response: the caller's override when it asked for
2120
- * one, widened to the fan-out budget when the server says this response *is* a
2121
- * fan-out. The header is the authoritative signal — it is set by the same code
2122
- * that runs the fan-out, so a renamed brain id or a caller that forgot its
2123
- * flag cannot desynchronise the two. A response with no header (an older
2124
- * server, or a single-pass call) keeps the caller's budget or the 60s default.
2125
- *
2126
- * ── the two env knobs ───────────────────────────────────────────────────────
2127
- *
2128
- * `AEGIS_SSE_IDLE_TIMEOUT_MS` and `AEGIS_BRAIN_IDLE_TIMEOUT_MS` move those two
2129
- * *defaults* without a code edit: the CLI is a host, not a fork, so before this
2130
- * the only way to give a slow link more room — or to reproduce a stall against
2131
- * a fixed wedged server — was to patch the transport. Same escape hatch the
2132
- * engine gives its host cooldown (`AEGIS_HOST_COOLDOWN_MS`).
2133
- *
2134
- * Both are read at CALL time, not at module load, so a host that sets one after
2135
- * `require()` still gets it, and one that unsets it is back on the shipped
2136
- * default. A per-call `idleTimeoutMs` still outranks both: an explicit number
2137
- * from the caller is a decision about *this* request, while the env var is only
2138
- * a house default. See envIdleMs() for why a bad value is ignored rather than
2139
- * obeyed.
2140
- */
2141
- function idleBudgetFor(res, requestedMs) {
2142
- // Caller override -> env knob -> shipped default.
2143
- const stated = Number(requestedMs);
2144
- const envDefault = envIdleMs('AEGIS_SSE_IDLE_TIMEOUT_MS');
2145
- const base = stated > 0 ? stated : envDefault > 0 ? envDefault : SSE_IDLE_TIMEOUT_MS;
2146
- let header = '';
2147
- try {
2148
- const get = res && res.headers && typeof res.headers.get === 'function' ? res.headers.get.bind(res.headers) : null;
2149
- header = (get && get('X-AEGIS-Brain')) || '';
2150
- } catch {
2151
- header = ''; // an exotic fetch shim without headers: keep the caller's budget
2152
- }
2153
- // The fan-out floor is tunable for the same reason the base is — and it has
2154
- // to stay a FLOOR: a server that announced workers=3 is still working, so a
2155
- // smaller base must not cut it off. Raise both if the server's own
2156
- // NEXUS_BRAIN_WORKER_TIMEOUT moves (test/autonomous-mode.test.mjs pins the
2157
- // 600s relationship between them).
2158
- const brainFloor = envIdleMs('AEGIS_BRAIN_IDLE_TIMEOUT_MS') || BRAIN_IDLE_TIMEOUT_MS;
2159
- return header && String(header).trim() ? Math.max(base, brainFloor) : base;
2160
- }
2161
-
2162
- /**
2163
- * Host-facing predicate: does a thrown error mean "upgrade this client"?
2164
- *
2165
- * Hosts catch from a shared client, and a bare `err.status === 426` check
2166
- * misses the gate bodies that arrive inside an otherwise-200 stream. Matched
2167
- * on the typed `code` the client sets, so a host never has to parse prose.
2168
- */
2169
- function isVersionGateError(err) {
2170
- return !!(err && err.code === 'version_mismatch');
2171
- }
2172
-
2173
- const api = { createClient, envVar, randomUUID, DEFAULT_API_BASE, CLIENT_VERSION, isVersionGateError, idleBudgetFor, SSE_IDLE_TIMEOUT_MS, BRAIN_IDLE_TIMEOUT_MS };
2174
-
2175
- // Node / Electron (CommonJS): the MCP plugin and desktop shell require() this.
2176
- if (typeof module !== 'undefined' && module.exports) {
2177
- module.exports = api;
2178
- }
2179
- // Browser <script>: expose a single namespaced global for the aegis-online SPA.
2180
- if (typeof window !== 'undefined') {
2181
- window.AegisClient = api;
2182
- }
4
+ "use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),y),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${y/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<h;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>T?t.slice(0,T):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>T){const n=new Error(`Response from ${t} exceeded the ${T/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let S=null;const y=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,T=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,h=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function k(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function v(){if(r)return r;if(S)return S;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return S=e.memory_token,S}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&""!==n){const e=o[o.length-1];e&&"user"===e.role&&e.content===n||o.push({role:"user",content:n})}return o}function C(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function $(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const e={...n};delete e.stream_options,n=e;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=P(await w(e,{...t,stream:!1},r,{signal:s})),i=C(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=P(await O(f)),t=C(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(k(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const S=f.body.getReader(),y=new TextDecoder;let T="",h="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const v=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const B=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([S.read(),r,o]):Promise.race([S.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){S.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return $(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;T+=y.decode(l,{stream:!0});const u=T.split("\n");T=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:k({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),h=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,h,(e=>{const t=v(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!h&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),$(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-B):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=v.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=v.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",S=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:U(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),$("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):P(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const S=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const y={provider:t,messages:U(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(y.model=r);const T={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":S};return n&&(T["X-AEGIS-Key"]=n),_&&"function"==typeof f?$("/api/v1/byok/chat/completions",y,T,f,E):P(await w("/api/v1/byok/chat/completions",{...y,stream:!1},T))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:v,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await v()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await v()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await v()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await v()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await v()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await v()))},conversationSyncPush:async function(e){const t=await v();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await v()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);