aegiscode 7.0.26 → 7.0.27
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.
- package/SOURCE-OFFER.txt +9 -0
- package/package.json +4 -7
- package/scripts/check.mjs +1 -52
- package/scripts/demo.mjs +1 -94
- package/scripts/predist.mjs +1 -75
- package/scripts/runtests.mjs +1 -56
- package/scripts/seal-gate.mjs +1 -74
- package/src/agents.js +1 -139
- package/src/app.js +1 -2957
- package/src/art.js +1 -289
- package/src/chatflow.js +1 -3023
- package/src/checkpoint.js +1 -90
- package/src/clipboard.js +1 -424
- package/src/cloudsync.js +1 -528
- package/src/commands.js +1 -4089
- package/src/config.js +1 -581
- package/src/connect.js +1 -349
- package/src/credentials.js +1 -33
- package/src/deps.js +1 -232
- package/src/devrun.js +1 -187
- package/src/diff.js +1 -333
- package/src/diffview.js +1 -296
- package/src/engine.js +1 -297
- package/src/entitlement.js +1 -355
- package/src/events.js +1 -707
- package/src/export.js +1 -67
- package/src/filepreview.js +1 -153
- package/src/fingerprint.js +1 -592
- package/src/format.js +1 -259
- package/src/fuzzy.js +1 -119
- package/src/history.js +1 -423
- package/src/init.js +1 -175
- package/src/input.js +1 -139
- package/src/keys.js +1 -183
- package/src/markdown.js +1 -306
- package/src/models.js +1 -507
- package/src/naming.js +1 -57
- package/src/overlays.js +1 -462
- package/src/panels.js +1 -1418
- package/src/ping.js +1 -226
- package/src/presence.js +1 -238
- package/src/render.js +1 -516
- package/src/screen.js +1 -518
- package/src/screens.js +1 -896
- package/src/secret.js +1 -59
- package/src/securefs.js +1 -359
- package/src/settings.js +1 -155
- package/src/shared.js +1 -52
- package/src/sharedpaths.js +1 -53
- package/src/signup.js +1 -156
- package/src/summarize.js +1 -95
- package/src/sysdiag.js +1 -585
- package/src/system.js +1 -40
- package/src/theme.js +1 -570
- package/src/title.js +1 -220
- package/src/todos.js +1 -115
- package/src/tokens.js +1 -263
- package/src/topup.js +1 -210
- package/src/update.js +1 -191
- package/vendor/client/aegis.js +1 -2441
- package/vendor/client/attest.js +1 -518
- package/vendor/client/authorship-key.js +1 -410
- package/vendor/client/auto-provision.js +1 -134
- package/vendor/client/brain-catalog.js +1 -268
- package/vendor/client/byok-catalog.js +1 -199
- package/vendor/client/catalog-client.js +1 -487
- package/vendor/client/conversation-export.js +1 -177
- package/vendor/client/credentials.js +1 -494
- package/vendor/client/device-fingerprint.js +1 -141
- package/vendor/client/drive-connect.js +1 -110
- package/vendor/client/drive-upload.js +1 -234
- package/vendor/client/env-file.js +1 -1273
- package/vendor/client/fingerprint.js +1 -1064
- package/vendor/client/foreign-memory.js +1 -669
- package/vendor/client/google-signin.js +1 -133
- package/vendor/client/hooks.js +1 -430
- package/vendor/client/model-discovery.js +1 -373
- package/vendor/client/naming.js +1 -283
- package/vendor/client/platform.js +1 -937
- package/vendor/client/prefs.js +1 -351
- package/vendor/client/presence-constants.js +1 -107
- package/vendor/client/presence.js +1 -438
- package/vendor/client/record-vault.js +3 -1055
- package/vendor/client/session-store.js +1 -575
- package/vendor/client/topup.js +1 -297
- package/vendor/client/touch.js +1 -458
- package/vendor/client/update.js +1 -763
- package/vendor/client/user-models.js +1 -381
- package/vendor/desktop/lib/local/agents.js +1 -105
- package/vendor/desktop/lib/local/attachments.js +1 -276
- package/vendor/desktop/lib/local/autonomous.js +1 -1045
- package/vendor/desktop/lib/local/claude-pro.js +1 -1028
- package/vendor/desktop/lib/local/context.js +1 -125
- package/vendor/desktop/lib/local/engine.js +1 -3666
- package/vendor/desktop/lib/local/entitlement.js +1 -660
- package/vendor/desktop/lib/local/exec-plan.js +1 -269
- package/vendor/desktop/lib/local/git-scope.js +1 -228
- package/vendor/desktop/lib/local/integrity.js +1 -163
- package/vendor/desktop/lib/local/local.js +1 -2145
- package/vendor/desktop/lib/local/prompt.js +1 -280
- package/vendor/desktop/lib/local/queue.js +1 -560
- package/vendor/desktop/lib/local/session-rounds.js +1 -238
- package/vendor/desktop/lib/local/shell.js +1 -712
- package/vendor/desktop/lib/local/spill.js +1 -75
- package/vendor/desktop/lib/local/tools.js +1 -1328
- package/vendor/desktop/lib/local/turn-guard.js +1 -300
- package/vendor/desktop/lib/local/worktree-lock.js +1 -235
- package/vendor/desktop/lib/settings.js +1 -890
- package/vendor/desktop/main.js +3 -4890
- package/vendor/desktop/renderer/usage.js +1 -1239
- package/vendor/hosts/install.js +1 -638
- package/vendor/hosts/openai-shim.js +1 -515
- package/vendor/hosts/spec.js +1 -164
- package/vendor/hosts/targets.js +1 -346
- package/vendor/mcp/server.js +1 -221
- package/vendor/mcp/tools.js +1 -408
- package/vendor/one/src/child.js +1 -285
- package/vendor/one/src/permissions.js +1 -383
package/vendor/client/aegis.js
CHANGED
|
@@ -1,2444 +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
|
-
* A socket that dies *before* any response header exists, retried.
|
|
494
|
-
*
|
|
495
|
-
* This is the third face of "Could not reach https://aegiscloud.org (connection
|
|
496
|
-
* reset by the backend)", and the only one that was never covered: the two
|
|
497
|
-
* server-side fixes (drain on deploy, `--keep-alive 75`) removed the ways the
|
|
498
|
-
* backend could drop a live connection, but a client that still loses the race
|
|
499
|
-
* has no recovery at all. `boundedFetch` rethrew the reset into
|
|
500
|
-
* `networkFailureError`, which the host renders as a failed TURN — no request
|
|
501
|
-
* ever got an answer, nothing streamed, and the same message the two server
|
|
502
|
-
* fixes were fighting reappears on the user's screen.
|
|
503
|
-
*
|
|
504
|
-
* Everything the reset could have damaged is recoverable here, and only here:
|
|
505
|
-
* `fetch` has not resolved, so no status line exists, no body has been read, no
|
|
506
|
-
* token has been painted, and there is nothing to duplicate. Re-issuing the
|
|
507
|
-
* same request on a fresh socket is exactly what undici would have done had the
|
|
508
|
-
* pool known the socket was dead, so this is not a second attempt at the work,
|
|
509
|
-
* it is the first attempt finally reaching the server.
|
|
510
|
-
*
|
|
511
|
-
* Bounded (2 retries, 500ms/1s backoff) and only for the codes that mean "the
|
|
512
|
-
* socket was already gone", never for a timeout (that is a slow answer, and a
|
|
513
|
-
* retry would spend the deadline twice) and never for the caller's own abort.
|
|
514
|
-
*/
|
|
515
|
-
const TRANSIENT_SOCKET_CODE_PATTERN =
|
|
516
|
-
/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/;
|
|
517
|
-
const TRANSIENT_SOCKET_RETRIES = 2;
|
|
518
|
-
|
|
519
|
-
/**
|
|
520
|
-
* The sentence aegis1 puts in a mid-stream error frame when the UPSTREAM
|
|
521
|
-
* provider call it was relaying hit its own deadline. Deliberately kept out of
|
|
522
|
-
* TRANSIENT_STREAM_ERROR_PATTERN: a socket reset is worth re-issuing at once,
|
|
523
|
-
* but a provider timeout has already spent a full deadline, so the same retry
|
|
524
|
-
* would make a stuck upstream cost three of them before anything was said.
|
|
525
|
-
*
|
|
526
|
-
* It still has to be CLASSIFIED, not passed through raw. The frame arrives
|
|
527
|
-
* after the stream's own 200 OK, so `res.status` is 200 — the throw used to be
|
|
528
|
-
* stamped with that and reached the desktop host as `{ status: 200 }`, which
|
|
529
|
-
* reads as a success to every downstream branch (engine.js keys its recovery
|
|
530
|
-
* on `status === 402`/`400`; the renderer keys "waited too long" on status 0).
|
|
531
|
-
*/
|
|
532
|
-
const SSE_UPSTREAM_TIMEOUT_PATTERN = /request timed out|timed out waiting|upstream timeout/i;
|
|
533
|
-
|
|
534
|
-
/**
|
|
535
|
-
* The message for a provider timeout, stating whose deadline expired.
|
|
536
|
-
*
|
|
537
|
-
* This used to read "the provider returned no answer within the 60s stream
|
|
538
|
-
* budget (raise AEGIS_SSE_IDLE_TIMEOUT_MS for a slower provider)". Measured
|
|
539
|
-
* live, that sentence was false in the one case it fired: the provider gave up
|
|
540
|
-
* in ~11-13s and aegis1 relayed it, so the client's own watchdog never fired at
|
|
541
|
-
* all — `sseError` is only ever set from a `json.error` frame, and our stall
|
|
542
|
-
* raises its own `stream stalled - …` error from `readWithIdleTimeout` instead.
|
|
543
|
-
* The advice pointed at an env var that provably cannot help, which is worse
|
|
544
|
-
* than saying nothing: a user follows it, restarts, and the turn still fails.
|
|
545
|
-
*
|
|
546
|
-
* So the message separates the two deadlines and names elapsed time, which is
|
|
547
|
-
* the fact that tells a reader which one it was without trusting the prose.
|
|
548
|
-
* `elapsedMs` is omitted when the caller has no measured start (the
|
|
549
|
-
* non-streaming path), rather than inventing one.
|
|
550
|
-
*/
|
|
551
|
-
function upstreamTimeoutMessage(base, elapsedMs) {
|
|
552
|
-
// Two different things used to collapse into one branch here.
|
|
553
|
-
//
|
|
554
|
-
// "No measured start" (the buffered caller passes nothing) must stay silent,
|
|
555
|
-
// but "measured, and the answer came back in under a millisecond" is NOT the
|
|
556
|
-
// same fact and must not be dropped: `Number(undefined) > 0` is false and
|
|
557
|
-
// `Number(0) > 0` is false, so a stream that reported its timeout in the same
|
|
558
|
-
// millisecond it began stated no time at all — which made the sentence
|
|
559
|
-
// nondeterministic under load (measured: identical fixture, identical server,
|
|
560
|
-
// the elapsed clause present in 16 of 25 runs). Separating `null`/`undefined`
|
|
561
|
-
// from a real `0` and rendering sub-second values in ms keeps the claim true
|
|
562
|
-
// whichever way the clock lands, instead of rounding 45ms to a useless
|
|
563
|
-
// "0.0s".
|
|
564
|
-
const ms = Number(elapsedMs);
|
|
565
|
-
const measured = elapsedMs != null && Number.isFinite(ms);
|
|
566
|
-
const took = !measured
|
|
567
|
-
? ''
|
|
568
|
-
: ms >= 1000
|
|
569
|
-
? ` after ${(ms / 1000).toFixed(1)}s`
|
|
570
|
-
: ` after ${Math.max(0, Math.round(ms))}ms`;
|
|
571
|
-
return (
|
|
572
|
-
`${base} — the upstream provider gave up before answering${took}. ` +
|
|
573
|
-
"That is the provider's own deadline, not this client's stream budget, so " +
|
|
574
|
-
'raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help'
|
|
575
|
-
);
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
/**
|
|
579
|
-
* .mcp.json / Electron pass config as "${VAR}" template refs. When the var is
|
|
580
|
-
* unset, hosts have been observed to leave the template literally unexpanded
|
|
581
|
-
* (e.g. "${AEGIS_API_BASE}") instead of omitting it — which defeats a plain
|
|
582
|
-
* `|| default` fallback since the literal string is truthy. Treat anything
|
|
583
|
-
* shaped like an unexpanded template as absent.
|
|
584
|
-
*/
|
|
585
|
-
function createClient(opts = {}) {
|
|
586
|
-
const apiBase = (
|
|
587
|
-
opts.apiBase ||
|
|
588
|
-
envVar('AEGIS_API_BASE') ||
|
|
589
|
-
DEFAULT_API_BASE
|
|
590
|
-
).replace(/\/+$/, '');
|
|
591
|
-
let apiKey = opts.apiKey !== undefined ? opts.apiKey : envVar('AEGIS_API_KEY');
|
|
592
|
-
// Optional: a memory token supplied directly, bypassing the api_key exchange.
|
|
593
|
-
const memoryToken =
|
|
594
|
-
opts.memoryToken !== undefined ? opts.memoryToken : envVar('AEGIS_MEMORY_TOKEN');
|
|
595
|
-
const clientVersion = opts.clientVersion || CLIENT_VERSION;
|
|
596
|
-
// Which host is asking, purely so an upgrade prompt raised from inside this
|
|
597
|
-
// shared client is filed against the right product. aegis1 stores an
|
|
598
|
-
// unrecognised source as NULL and reports it as `direct`, so an unknown
|
|
599
|
-
// value here is a silently destroyed datapoint rather than a visible error —
|
|
600
|
-
// hence the allowlist rather than trusting the caller.
|
|
601
|
-
const channel = opts.channel === 'cli' ? 'cli' : 'desktop';
|
|
602
|
-
|
|
603
|
-
/**
|
|
604
|
-
* Strip the live API key out of anything on its way to a message, a log or a
|
|
605
|
-
* renderer. Server error bodies echo the offending request often enough that
|
|
606
|
-
* this is not theoretical: a 400 that repeats the request payload puts the
|
|
607
|
-
* key into `err.message`, which hosts print to a terminal, a log file, and
|
|
608
|
-
* (desktop) across an IPC boundary. The key is the one value in this module
|
|
609
|
-
* whose leak is unrecoverable, so it is scrubbed at the boundary rather than
|
|
610
|
-
* trusted not to appear.
|
|
611
|
-
*/
|
|
612
|
-
function redact(value) {
|
|
613
|
-
if (!apiKey || typeof value !== 'string') return value;
|
|
614
|
-
return value.split(apiKey).join('[redacted]');
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
/**
|
|
618
|
-
* Transport failure codes → what actually happened, in words that point at
|
|
619
|
-
* the culprit. Names, not errno numbers, because "ECONNRESET" tells a user
|
|
620
|
-
* nothing while "the connection was reset mid-request" tells them to retry.
|
|
621
|
-
*/
|
|
622
|
-
const AEGIS_NETWORK_ERROR_HINTS = {
|
|
623
|
-
ECONNRESET: 'connection reset by the backend',
|
|
624
|
-
ECONNREFUSED: 'connection refused — is the backend running?',
|
|
625
|
-
EPIPE: 'connection closed while sending the request',
|
|
626
|
-
ETIMEDOUT: 'connection timed out',
|
|
627
|
-
ENOTFOUND: 'host not found — check the endpoint URL',
|
|
628
|
-
EAI_AGAIN: 'DNS lookup failed temporarily',
|
|
629
|
-
EHOSTUNREACH: 'host unreachable',
|
|
630
|
-
ENETUNREACH: 'network unreachable',
|
|
631
|
-
CERT_HAS_EXPIRED: 'TLS certificate has expired',
|
|
632
|
-
DEPTH_ZERO_SELF_SIGNED_CERT: 'TLS certificate is self-signed',
|
|
633
|
-
UND_ERR_SOCKET: 'the socket closed before the response finished',
|
|
634
|
-
UND_ERR_CLOSED: 'the connection was closed',
|
|
635
|
-
UND_ERR_CONNECT_TIMEOUT: 'timed out connecting to the backend',
|
|
636
|
-
UND_ERR_HEADERS_TIMEOUT: 'the backend accepted the connection but never sent a response',
|
|
637
|
-
UND_ERR_BODY_TIMEOUT: 'the backend stalled mid-response',
|
|
638
|
-
UND_ERR_ABORTED: 'the request was aborted',
|
|
639
|
-
};
|
|
640
|
-
|
|
641
|
-
/**
|
|
642
|
-
* Turn a raw transport failure into something a person can act on.
|
|
643
|
-
*
|
|
644
|
-
* Node's undici raises `TypeError: fetch failed` for every socket-level
|
|
645
|
-
* fault and puts the real reason on `err.cause` (`ECONNRESET`,
|
|
646
|
-
* `UND_ERR_SOCKET`, `HeadersTimeoutError`, `ENOTFOUND`, …). Rethrown
|
|
647
|
-
* untouched, the user sees the literal string `fetch failed`, which names
|
|
648
|
-
* no component, no cause and no next step — and, worse, hides the fact that
|
|
649
|
-
* the backend is the thing that dropped us rather than a bad request.
|
|
650
|
-
*
|
|
651
|
-
* The cause code, when there is one, is the single most useful fact here,
|
|
652
|
-
* so it is promoted into `message` and kept on `cause`/`networkCode` for
|
|
653
|
-
* callers that want to branch on it. Everything else about the error is
|
|
654
|
-
* left alone.
|
|
655
|
-
*/
|
|
656
|
-
function networkFailureError(err, base) {
|
|
657
|
-
const reraised = err instanceof Error ? err : new Error(String(err));
|
|
658
|
-
// The caller's own cancellation is not a failure and must stay untouched.
|
|
659
|
-
const name = reraised && reraised.name;
|
|
660
|
-
if (name === 'AbortError' || name === 'TimeoutError') return err;
|
|
661
|
-
const detail = describeNetworkCause(reraised);
|
|
662
|
-
const target = base || 'the backend';
|
|
663
|
-
const e = new Error(
|
|
664
|
-
detail
|
|
665
|
-
? `Could not reach ${target} (${detail}).`
|
|
666
|
-
: `Could not reach ${target}: ${reraised.message || 'network failure'}.`
|
|
667
|
-
);
|
|
668
|
-
e.status = 0;
|
|
669
|
-
e.code = 'network';
|
|
670
|
-
e.networkCode = detail || null;
|
|
671
|
-
e.data = null;
|
|
672
|
-
e.cause = reraised;
|
|
673
|
-
return e;
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
/** The innermost human-meaningful reason from an undici error chain. */
|
|
677
|
-
function describeNetworkCause(err, depth = 0) {
|
|
678
|
-
if (!err || depth > 4) return null;
|
|
679
|
-
const code = err.code || (err.cause && err.cause.code);
|
|
680
|
-
const inner = err.cause;
|
|
681
|
-
const innerDetail = inner ? describeNetworkCause(inner, depth + 1) : null;
|
|
682
|
-
if (AEGIS_NETWORK_ERROR_HINTS[code]) return AEGIS_NETWORK_ERROR_HINTS[code];
|
|
683
|
-
if (innerDetail) return innerDetail;
|
|
684
|
-
// An undici cause often carries only a message ("other side closed").
|
|
685
|
-
if (inner && inner.message && inner.message !== err.message) return inner.message;
|
|
686
|
-
return code || null;
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
/**
|
|
690
|
-
* A bounded `fetch`: caller signal where there is one, an aborting timeout
|
|
691
|
-
* where there is not. Returns the caller's abort untouched (so a host that
|
|
692
|
-
* cancelled a turn still sees its own cancellation, not a timeout), and
|
|
693
|
-
* raises a typed `timeout` error for the ceiling it added itself.
|
|
694
|
-
*/
|
|
695
|
-
async function boundedFetch(url, init) {
|
|
696
|
-
const callerSignal = init && init.signal;
|
|
697
|
-
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
698
|
-
let timer = null;
|
|
699
|
-
const onAbort = () => {
|
|
700
|
-
if (controller) controller.abort();
|
|
701
|
-
};
|
|
702
|
-
if (controller) {
|
|
703
|
-
// `unref` where available: a pending timeout must never be the reason a
|
|
704
|
-
// short-lived CLI process (`aegiscode -p "..."`) refuses to exit.
|
|
705
|
-
timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
706
|
-
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
707
|
-
if (callerSignal) {
|
|
708
|
-
if (callerSignal.aborted) controller.abort();
|
|
709
|
-
else if (typeof callerSignal.addEventListener === 'function') {
|
|
710
|
-
callerSignal.addEventListener('abort', onAbort, { once: true });
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
try {
|
|
715
|
-
return await fetch(url, {
|
|
716
|
-
...(init || {}),
|
|
717
|
-
signal: controller ? controller.signal : callerSignal,
|
|
718
|
-
});
|
|
719
|
-
} catch (err) {
|
|
720
|
-
// Only claim a timeout when *we* aborted. A caller-originated abort is
|
|
721
|
-
// the caller's business and is rethrown as-is.
|
|
722
|
-
const ours =
|
|
723
|
-
controller && controller.signal.aborted && !(callerSignal && callerSignal.aborted);
|
|
724
|
-
if (ours) {
|
|
725
|
-
const e = new Error(
|
|
726
|
-
`Timed out after ${timeoutMs / 1000}s waiting for ${apiBase}.`
|
|
727
|
-
);
|
|
728
|
-
e.status = 0;
|
|
729
|
-
e.code = 'timeout';
|
|
730
|
-
e.data = null;
|
|
731
|
-
throw e;
|
|
732
|
-
}
|
|
733
|
-
throw networkFailureError(err, apiBase);
|
|
734
|
-
} finally {
|
|
735
|
-
// The timeout is time-to-*headers* only, so it is cleared the moment the
|
|
736
|
-
// response resolves: a long generation must never be cut off by it.
|
|
737
|
-
if (timer) clearTimeout(timer);
|
|
738
|
-
// …but the caller's abort bridge is deliberately NOT removed here.
|
|
739
|
-
//
|
|
740
|
-
// `fetch` resolves at the status line, while the RESPONSE BODY is still
|
|
741
|
-
// bound to `controller.signal` and keeps being read long after this
|
|
742
|
-
// function has returned. Unhooking the caller's signal at that point
|
|
743
|
-
// detached Stop/Escape from the stream it was supposed to stop: the
|
|
744
|
-
// engine's own controller really did abort — `engine.cancel()` answered
|
|
745
|
-
// `{ ok: true }`, so the right controller was found and `abort()` was
|
|
746
|
-
// really called — and nothing happened, because the only thing wired to
|
|
747
|
-
// the live body had already been told to stop listening. The turn then
|
|
748
|
-
// streamed to completion while the UI sat on "stopping…", never settled,
|
|
749
|
-
// and never produced the salvaged bubble, because no error ever reached
|
|
750
|
-
// the caller's catch.
|
|
751
|
-
//
|
|
752
|
-
// `once: true` plus one signal per turn bounds the cost of leaving it
|
|
753
|
-
// attached to a single listener per turn — a far smaller price than a
|
|
754
|
-
// cancel button that does nothing.
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
/**
|
|
759
|
-
* How long to hold off after a 429. The server's `Retry-After` wins when it
|
|
760
|
-
* sends one, since only the server knows when the window actually opens; both
|
|
761
|
-
* the delta-seconds and the HTTP-date form are accepted because either is
|
|
762
|
-
* legal. Without the header — which is the case for aegis1's BYOK relay today,
|
|
763
|
-
* it answers the bare 429 body — we back off exponentially from
|
|
764
|
-
* RATE_LIMIT_BASE_WAIT_MS. Either way the wait is capped: an unclamped
|
|
765
|
-
* `Retry-After` (or a hostile one) would otherwise be a turn that hangs.
|
|
766
|
-
*/
|
|
767
|
-
function rateLimitDelayMs(res, attempt) {
|
|
768
|
-
const header =
|
|
769
|
-
res && res.headers && typeof res.headers.get === 'function'
|
|
770
|
-
? res.headers.get('retry-after')
|
|
771
|
-
: null;
|
|
772
|
-
let delay = 0;
|
|
773
|
-
if (header) {
|
|
774
|
-
const secs = Number(header);
|
|
775
|
-
if (Number.isFinite(secs) && secs >= 0) {
|
|
776
|
-
delay = secs * 1000;
|
|
777
|
-
} else {
|
|
778
|
-
const when = Date.parse(header);
|
|
779
|
-
if (Number.isFinite(when)) delay = when - Date.now();
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
if (!delay) delay = rateLimitBaseWaitMs * Math.pow(2, attempt);
|
|
783
|
-
return Math.min(delay, rateLimitMaxWaitMs);
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
/**
|
|
787
|
-
* Wait out a back-off. A mid-wait abort resolves rather than rejecting: the
|
|
788
|
-
* retry that follows is issued on the caller's now-aborted signal, so `fetch`
|
|
789
|
-
* rejects the way it would have anyway. Synthesising a second abort error here
|
|
790
|
-
* would race the real one to the caller's catch and decide which of the two
|
|
791
|
-
* they see — not this helper's call to make.
|
|
792
|
-
*/
|
|
793
|
-
function sleep(ms, signal) {
|
|
794
|
-
return new Promise((resolve) => {
|
|
795
|
-
const timer = setTimeout(resolve, ms);
|
|
796
|
-
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
797
|
-
if (!signal || typeof signal.addEventListener !== 'function') return;
|
|
798
|
-
if (signal.aborted) {
|
|
799
|
-
clearTimeout(timer);
|
|
800
|
-
resolve();
|
|
801
|
-
return;
|
|
802
|
-
}
|
|
803
|
-
signal.addEventListener(
|
|
804
|
-
'abort',
|
|
805
|
-
() => {
|
|
806
|
-
clearTimeout(timer);
|
|
807
|
-
resolve();
|
|
808
|
-
},
|
|
809
|
-
{ once: true }
|
|
810
|
-
);
|
|
811
|
-
});
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
/**
|
|
815
|
-
* `boundedFetch` with a 429 back-off. Retries are bounded (RATE_LIMIT_RETRIES)
|
|
816
|
-
* so a window that never opens still fails — and fails with the server's own
|
|
817
|
-
* 429 body, since the last response is returned unread to `parseResponse`
|
|
818
|
-
* rather than being replaced by a home-made "gave up" error. The caller keeps
|
|
819
|
-
* the message the user was already seeing; it just arrives after the transport
|
|
820
|
-
* did what it could.
|
|
821
|
-
*/
|
|
822
|
-
/**
|
|
823
|
-
* `boundedFetch` with a retry on a socket that was already dead.
|
|
824
|
-
*
|
|
825
|
-
* Only a failure that never became a response is retried: `networkFailureError`
|
|
826
|
-
* carries `code: 'network'` and the underlying `networkCode`, and a caller's
|
|
827
|
-
* own abort or our own header timeout have their own codes and are rethrown
|
|
828
|
-
* untouched. Each retry is a fresh `boundedFetch`, so it gets a fresh timer and
|
|
829
|
-
* a fresh socket — the point is to stop writing onto a connection the server
|
|
830
|
-
* has already given up on (see TRANSIENT_SOCKET_CODE_PATTERN for why every
|
|
831
|
-
* such request is safe to repeat).
|
|
832
|
-
*/
|
|
833
|
-
/**
|
|
834
|
-
* The raw transport code from a wrapped network failure.
|
|
835
|
-
*
|
|
836
|
-
* `err.networkCode` is deliberately PROSE (the hint table's sentence), which
|
|
837
|
-
* is right for a user and useless for a branch — so this walks the original
|
|
838
|
-
* undici error chain (`err.cause`) for the actual `code`. Depth-capped like
|
|
839
|
-
* `describeNetworkCause`, for the same reason: a self-referential cause chain
|
|
840
|
-
* must not spin. The walk starts at `cause`, because the wrapper's own code is
|
|
841
|
-
* the literal string `network` and would otherwise match itself.
|
|
842
|
-
*/
|
|
843
|
-
function rawSocketCode(err, depth = 0) {
|
|
844
|
-
if (!err || depth > 4) return null;
|
|
845
|
-
const code = err.code;
|
|
846
|
-
if (typeof code === 'string' && code !== 'network') return code;
|
|
847
|
-
return rawSocketCode(err.cause, depth + 1);
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
async function boundedFetchRetryingDeadSocket(url, init) {
|
|
851
|
-
let attempt = 0;
|
|
852
|
-
for (;;) {
|
|
853
|
-
try {
|
|
854
|
-
return await boundedFetch(url, init);
|
|
855
|
-
} catch (err) {
|
|
856
|
-
const code = err && err.code === 'network' ? String(rawSocketCode(err) || '') : '';
|
|
857
|
-
if (attempt >= TRANSIENT_SOCKET_RETRIES || !TRANSIENT_SOCKET_CODE_PATTERN.test(code)) {
|
|
858
|
-
throw err;
|
|
859
|
-
}
|
|
860
|
-
// A caller who aborted during the wait must not have the request
|
|
861
|
-
// re-issued underneath them: `sleep` resolves on abort, so this is the
|
|
862
|
-
// check that turns that into the caller's own cancellation instead of
|
|
863
|
-
// one more doomed round-trip.
|
|
864
|
-
if (init && init.signal && init.signal.aborted) throw err;
|
|
865
|
-
await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, attempt), init && init.signal);
|
|
866
|
-
if (init && init.signal && init.signal.aborted) throw err;
|
|
867
|
-
attempt++;
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
async function fetchWithRateLimitRetry(url, init) {
|
|
873
|
-
let res = await boundedFetchRetryingDeadSocket(url, init);
|
|
874
|
-
for (let attempt = 0; res && res.status === 429 && attempt < rateLimitRetries; attempt++) {
|
|
875
|
-
const wait = rateLimitDelayMs(res, attempt);
|
|
876
|
-
try {
|
|
877
|
-
// The 429 body is discarded unread either way — releasing it is what
|
|
878
|
-
// keeps a long back-off from pinning the socket.
|
|
879
|
-
if (res.body) await res.body.cancel();
|
|
880
|
-
} catch {
|
|
881
|
-
/* discarded anyway */
|
|
882
|
-
}
|
|
883
|
-
await sleep(wait, init && init.signal);
|
|
884
|
-
res = await boundedFetchRetryingDeadSocket(url, init);
|
|
885
|
-
}
|
|
886
|
-
// The NON-streaming twin of postStream's mid-stream transient retry below:
|
|
887
|
-
// aegis1's chat-completions route drains the same generate() generator
|
|
888
|
-
// itself when the caller sent `stream: false`, and on the SAME exception
|
|
889
|
-
// (a reset socket to the provider) returns it as a plain 503 —
|
|
890
|
-
// `{"error":{"message":"[Errno 104] Connection reset by peer","type":
|
|
891
|
-
// "server_error"}}` — not a 200 SSE frame, because no response has been
|
|
892
|
-
// sent yet on this branch. Peeked via a clone so a non-matching body (a
|
|
893
|
-
// real 503 — insufficient balance, "not configured" — is untouched for
|
|
894
|
-
// `parseResponse` to read and surface normally, unretried.
|
|
895
|
-
for (
|
|
896
|
-
let attempt = 0;
|
|
897
|
-
res && res.status >= 500 && res.status < 600 && attempt < TRANSIENT_STREAM_RETRIES;
|
|
898
|
-
attempt++
|
|
899
|
-
) {
|
|
900
|
-
let text = '';
|
|
901
|
-
try {
|
|
902
|
-
text = await readCappedText(res.clone());
|
|
903
|
-
} catch {
|
|
904
|
-
break; // body already disturbed or unclonable — surface res as-is
|
|
905
|
-
}
|
|
906
|
-
if (!TRANSIENT_STREAM_ERROR_PATTERN.test(text)) break;
|
|
907
|
-
await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, attempt), init && init.signal);
|
|
908
|
-
res = await boundedFetchRetryingDeadSocket(url, init);
|
|
909
|
-
}
|
|
910
|
-
return res;
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
/**
|
|
914
|
-
* A transport fault that arrives AFTER the status line, classified.
|
|
915
|
-
*
|
|
916
|
-
* The pre-header case is handled by `boundedFetchRetryingDeadSocket`, but a
|
|
917
|
-
* socket can also die once `fetch` has already resolved: undici is reading
|
|
918
|
-
* the body and the peer RSTs. That throw is a bare `TypeError: fetch failed`
|
|
919
|
-
* with `ECONNRESET` on its cause, and nothing on either body path used to
|
|
920
|
-
* classify it — so the SAME user-visible symptom ("fetch failed" / an
|
|
921
|
-
* unclassified turn failure) reappeared from the one direction the request
|
|
922
|
-
* retry cannot see. It is classified here so the message names the transport
|
|
923
|
-
* and the caller can decide whether the work is safe to repeat.
|
|
924
|
-
*
|
|
925
|
-
* Not a transport fault, and deliberately left alone: the caller's own abort,
|
|
926
|
-
* our header timeout, and the SSE idle watchdog's `stream stalled - …` (our
|
|
927
|
-
* clock, not the network's, and it owns its own sentence).
|
|
928
|
-
*/
|
|
929
|
-
function classifyBodyTransportFailure(err) {
|
|
930
|
-
if (!err) return err;
|
|
931
|
-
if (err.name === 'AbortError' || err.name === 'TimeoutError') return err;
|
|
932
|
-
if (err.code === 'network' || err.code === 'timeout' || err.code === 'ABORT_ERR') return err;
|
|
933
|
-
if (/^stream stalled - /.test(String(err.message || ''))) return err;
|
|
934
|
-
if (!rawSocketCode(err)) return err;
|
|
935
|
-
const wrapped = networkFailureError(err, apiBase);
|
|
936
|
-
wrapped.bodyPhase = true;
|
|
937
|
-
return wrapped;
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
/** Read a response body, refusing to buffer more than MAX_BODY_BYTES. */
|
|
941
|
-
async function readCappedText(res) {
|
|
942
|
-
if (!res || !res.body || typeof res.body.getReader !== 'function') {
|
|
943
|
-
let text;
|
|
944
|
-
try {
|
|
945
|
-
text = await res.text();
|
|
946
|
-
} catch (err) {
|
|
947
|
-
const wrapped = classifyBodyTransportFailure(err);
|
|
948
|
-
if (wrapped && wrapped.code === 'network') wrapped.bytesRead = 0;
|
|
949
|
-
throw wrapped || err;
|
|
950
|
-
}
|
|
951
|
-
return text.length > maxBodyBytes ? text.slice(0, maxBodyBytes) : text;
|
|
952
|
-
}
|
|
953
|
-
const reader = res.body.getReader();
|
|
954
|
-
const decoder = new TextDecoder();
|
|
955
|
-
let out = '';
|
|
956
|
-
let total = 0;
|
|
957
|
-
try {
|
|
958
|
-
for (;;) {
|
|
959
|
-
let chunk;
|
|
960
|
-
try {
|
|
961
|
-
chunk = await reader.read();
|
|
962
|
-
} catch (err) {
|
|
963
|
-
const wrapped = classifyBodyTransportFailure(err);
|
|
964
|
-
// How much of the body the caller already has. Zero means nothing
|
|
965
|
-
// was parsed, painted or billed downstream, which is what makes
|
|
966
|
-
// re-issuing the request safe rather than a duplicate.
|
|
967
|
-
if (wrapped && wrapped.code === 'network') wrapped.bytesRead = total;
|
|
968
|
-
throw wrapped || err;
|
|
969
|
-
}
|
|
970
|
-
const { done, value } = chunk;
|
|
971
|
-
if (done) break;
|
|
972
|
-
total += value ? value.byteLength : 0;
|
|
973
|
-
if (total > maxBodyBytes) {
|
|
974
|
-
const e = new Error(
|
|
975
|
-
`Response from ${apiBase} exceeded the ${maxBodyBytes / (1024 * 1024)}MB cap.`
|
|
976
|
-
);
|
|
977
|
-
e.status = res.status;
|
|
978
|
-
e.code = 'body_too_large';
|
|
979
|
-
e.data = null;
|
|
980
|
-
throw e;
|
|
981
|
-
}
|
|
982
|
-
out += decoder.decode(value, { stream: true });
|
|
983
|
-
}
|
|
984
|
-
out += decoder.decode();
|
|
985
|
-
return out;
|
|
986
|
-
} finally {
|
|
987
|
-
// Release the socket on every path, including the cap trip and any
|
|
988
|
-
// decoder throw — otherwise a rejected body keeps the connection alive.
|
|
989
|
-
try {
|
|
990
|
-
await reader.cancel();
|
|
991
|
-
} catch {
|
|
992
|
-
/* already released */
|
|
993
|
-
}
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
let memoryTokenCache = null;
|
|
998
|
-
|
|
999
|
-
// Injectable ceilings. A guard that can only be exercised by sleeping for a
|
|
1000
|
-
// minute, or by allocating 9MB, is a guard that quietly rots — so the
|
|
1001
|
-
// transport takes both limits as options (and an env override, so a host can
|
|
1002
|
-
// tighten them without a code change). The defaults are the production ones.
|
|
1003
|
-
const timeoutMs =
|
|
1004
|
-
Number(opts.timeoutMs) > 0
|
|
1005
|
-
? Number(opts.timeoutMs)
|
|
1006
|
-
: Number(envVar('AEGIS_HTTP_TIMEOUT_MS')) > 0
|
|
1007
|
-
? Number(envVar('AEGIS_HTTP_TIMEOUT_MS'))
|
|
1008
|
-
: DEFAULT_TIMEOUT_MS;
|
|
1009
|
-
const maxBodyBytes =
|
|
1010
|
-
Number(opts.maxBodyBytes) > 0 ? Number(opts.maxBodyBytes) : MAX_BODY_BYTES;
|
|
1011
|
-
// The 429 back-off is injectable for the same reason as the two ceilings
|
|
1012
|
-
// above: a guard that can only be exercised by sleeping out a real
|
|
1013
|
-
// 15-second window is a guard that quietly rots. Defaults are the production
|
|
1014
|
-
// values (the RATE_LIMIT_* constants at the top of this module).
|
|
1015
|
-
const rateLimitRetries =
|
|
1016
|
-
Number(opts.rateLimitRetries) >= 0 ? Number(opts.rateLimitRetries) : RATE_LIMIT_RETRIES;
|
|
1017
|
-
const rateLimitBaseWaitMs =
|
|
1018
|
-
Number(opts.rateLimitBaseWaitMs) >= 0
|
|
1019
|
-
? Number(opts.rateLimitBaseWaitMs)
|
|
1020
|
-
: RATE_LIMIT_BASE_WAIT_MS;
|
|
1021
|
-
const rateLimitMaxWaitMs =
|
|
1022
|
-
Number(opts.rateLimitMaxWaitMs) > 0
|
|
1023
|
-
? Number(opts.rateLimitMaxWaitMs)
|
|
1024
|
-
: RATE_LIMIT_MAX_WAIT_MS;
|
|
1025
|
-
|
|
1026
|
-
/**
|
|
1027
|
-
* A campaign-tagged upgrade link. Never hand-build a `/subscribe` URL in a
|
|
1028
|
-
* prompt: the bare form carries no attribution, so the click arrives as
|
|
1029
|
-
* `direct` and the surface that produced it can never be credited.
|
|
1030
|
-
* The campaign must be one of the ids fixed in `docs/upgrade-conversion-plan.md`
|
|
1031
|
-
* §1 (`welcome_cloud`, `queue_cap`, `memory_quota`, `status_card`,
|
|
1032
|
-
* `topup_bank`) — a sixth id invented here is a row no report or allowlist
|
|
1033
|
-
* knows about, which is the same destroyed datapoint as an untagged link.
|
|
1034
|
-
* The slug is checked against aegis1's `_sanitize_signup_slug` shape rather
|
|
1035
|
-
* than an allowlist, because this module is shared by every host and cannot
|
|
1036
|
-
* know the server's current list.
|
|
1037
|
-
* Returns '' if the base is not a parseable absolute URL, so a caller can
|
|
1038
|
-
* fall back to plain text instead of rendering "undefined" at a user.
|
|
1039
|
-
*/
|
|
1040
|
-
function promptUrl(page, campaign) {
|
|
1041
|
-
try {
|
|
1042
|
-
const url = new URL(`/go/${String(page || 'upgrade').replace(/^\/+|\/+$/g, '')}`, apiBase);
|
|
1043
|
-
url.searchParams.set('s', channel);
|
|
1044
|
-
const c = String(campaign || '').trim().toLowerCase();
|
|
1045
|
-
if (/^[a-z0-9][a-z0-9_-]{0,63}$/.test(c)) url.searchParams.set('c', c);
|
|
1046
|
-
return url.toString();
|
|
1047
|
-
} catch (e) {
|
|
1048
|
-
return '';
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
|
|
1052
|
-
// -------------------------------------------------------------------------
|
|
1053
|
-
// HTTP helpers
|
|
1054
|
-
// -------------------------------------------------------------------------
|
|
1055
|
-
|
|
1056
|
-
/** Base headers every request carries (version gate + key when present). */
|
|
1057
|
-
function authHeaders(extra) {
|
|
1058
|
-
const headers = {
|
|
1059
|
-
'Content-Type': 'application/json',
|
|
1060
|
-
'X-AEGIS-Version': clientVersion,
|
|
1061
|
-
...extra,
|
|
1062
|
-
};
|
|
1063
|
-
// Keys are optional per-client (a BYOK-only browser page has none); when
|
|
1064
|
-
// absent, omit the auth headers entirely so no empty values are sent.
|
|
1065
|
-
if (apiKey) {
|
|
1066
|
-
headers['X-API-Key'] = apiKey;
|
|
1067
|
-
headers.Authorization = `Bearer ${apiKey}`;
|
|
1068
|
-
}
|
|
1069
|
-
return headers;
|
|
1070
|
-
}
|
|
1071
|
-
|
|
1072
|
-
/**
|
|
1073
|
-
* `fetchWithRateLimitRetry` + `parseResponse`, with one more retry for a
|
|
1074
|
-
* socket that died *while its body was being read* and had delivered nothing.
|
|
1075
|
-
*
|
|
1076
|
-
* `boundedFetchRetryingDeadSocket` covers the reset that lands before the
|
|
1077
|
-
* status line; this covers the other end of the same race, where the headers
|
|
1078
|
-
* arrived and the peer vanished mid-body. The condition is deliberately
|
|
1079
|
-
* narrow — `bytesRead === 0` — because that is the only case in which the
|
|
1080
|
-
* work is provably unstarted downstream: no JSON was parsed, no token was
|
|
1081
|
-
* painted, no quota was spent by anything the caller can see. A body that dies
|
|
1082
|
-
* partway through is NOT retried here; it is surfaced classified, because
|
|
1083
|
-
* re-issuing it would silently duplicate whatever the server already charged
|
|
1084
|
-
* for and whatever the caller already displayed.
|
|
1085
|
-
*/
|
|
1086
|
-
async function requestParsedOnce(path, init) {
|
|
1087
|
-
const res = await fetchWithRateLimitRetry(`${apiBase}${path}`, init);
|
|
1088
|
-
return parseResponse(res);
|
|
1089
|
-
}
|
|
1090
|
-
|
|
1091
|
-
async function apiRequest(path, init) {
|
|
1092
|
-
let attempt = 0;
|
|
1093
|
-
for (;;) {
|
|
1094
|
-
try {
|
|
1095
|
-
return await requestParsedOnce(path, init);
|
|
1096
|
-
} catch (err) {
|
|
1097
|
-
const repeatable =
|
|
1098
|
-
err && err.code === 'network' && err.bodyPhase === true && err.bytesRead === 0;
|
|
1099
|
-
if (!repeatable || attempt >= TRANSIENT_SOCKET_RETRIES) throw err;
|
|
1100
|
-
if (init && init.signal && init.signal.aborted) throw err;
|
|
1101
|
-
await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, attempt), init && init.signal);
|
|
1102
|
-
if (init && init.signal && init.signal.aborted) throw err;
|
|
1103
|
-
attempt++;
|
|
1104
|
-
}
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
async function apiPost(path, body, headers, opts) {
|
|
1109
|
-
return apiRequest(path, {
|
|
1110
|
-
method: 'POST',
|
|
1111
|
-
headers: headers || authHeaders(),
|
|
1112
|
-
body: JSON.stringify(body || {}),
|
|
1113
|
-
signal: opts && opts.signal,
|
|
1114
|
-
});
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
async function apiGet(path, headers, opts) {
|
|
1118
|
-
return apiRequest(path, {
|
|
1119
|
-
method: 'GET',
|
|
1120
|
-
headers: headers || authHeaders(),
|
|
1121
|
-
signal: opts && opts.signal,
|
|
1122
|
-
});
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
/**
|
|
1126
|
-
* A 426 `version_mismatch` from either server gate: this client is too old
|
|
1127
|
-
* to be served. The body carries the minimum it failed (`required`), the
|
|
1128
|
-
* npm dist-tags to move to (`latest_cli`/`latest_desktop`) and where to get
|
|
1129
|
-
* them, so a host can show an upgrade prompt naming a target instead of a
|
|
1130
|
-
* bare "connection refused".
|
|
1131
|
-
*
|
|
1132
|
-
* Surfaced as a typed error (`code` + `upgrade`) rather than only a message
|
|
1133
|
-
* so hosts can branch on it without parsing prose, and so the desktop/MCP
|
|
1134
|
-
* shells can open the upgrade panel with a version already filled in.
|
|
1135
|
-
*
|
|
1136
|
-
* The upgrade link is rebuilt through promptUrl() rather than trusting
|
|
1137
|
-
* `update_url` verbatim: a server-supplied bare URL carries no `?s=`/`?c=`,
|
|
1138
|
-
* so the click is filed as `direct` and the surface that hit the gate can
|
|
1139
|
-
* never be credited for the conversion it caused. The server value is kept
|
|
1140
|
-
* as a fallback for hosts reaching a base we cannot parse.
|
|
1141
|
-
*/
|
|
1142
|
-
function versionGateError(data, status) {
|
|
1143
|
-
const body = data || {};
|
|
1144
|
-
const latestCli = body.latest_cli || '';
|
|
1145
|
-
const latestDesktop = body.latest_desktop || '';
|
|
1146
|
-
// Prefer a real published version; fall back to the minimum so the
|
|
1147
|
-
// message always names something the user can act on.
|
|
1148
|
-
const target = latestCli || latestDesktop || body.required || '';
|
|
1149
|
-
const err = new Error(
|
|
1150
|
-
target
|
|
1151
|
-
? `This client (v${clientVersion}) is out of date — upgrade to v${target}.`
|
|
1152
|
-
: `This client (v${clientVersion}) is out of date.`
|
|
1153
|
-
);
|
|
1154
|
-
err.status = status;
|
|
1155
|
-
err.code = 'version_mismatch';
|
|
1156
|
-
err.data = body;
|
|
1157
|
-
err.upgrade = {
|
|
1158
|
-
required: body.required || '',
|
|
1159
|
-
latestCli,
|
|
1160
|
-
latestDesktop,
|
|
1161
|
-
// Campaign is `version_gate`: a refusal to serve is its own reason to
|
|
1162
|
-
// pay, distinct from a quota wall, and summing them hides which lever
|
|
1163
|
-
// the upgrade prompt is actually pulling.
|
|
1164
|
-
//
|
|
1165
|
-
// Guarded on typeof, not called directly: the attribution helper is a
|
|
1166
|
-
// separate concern from the gate, and a gate that throws because the
|
|
1167
|
-
// campaign tagger is absent would turn "your client is old" into
|
|
1168
|
-
// "undefined is not a function" on the one path whose whole job is to
|
|
1169
|
-
// tell the user what to do. Falls back to the server's own update_url.
|
|
1170
|
-
url: (typeof promptUrl === 'function' ? promptUrl('upgrade', 'version_gate') : '')
|
|
1171
|
-
|| body.update_url
|
|
1172
|
-
|| '',
|
|
1173
|
-
};
|
|
1174
|
-
return err;
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
/** Is this error body the version gate rather than a normal failure? */
|
|
1178
|
-
function isVersionGate(status, data) {
|
|
1179
|
-
return status === 426 || (data && data.code === 'version_mismatch');
|
|
1180
|
-
}
|
|
1181
|
-
|
|
1182
|
-
async function parseResponse(res) {
|
|
1183
|
-
const text = await readCappedText(res);
|
|
1184
|
-
let data;
|
|
1185
|
-
try {
|
|
1186
|
-
data = text ? JSON.parse(text) : {};
|
|
1187
|
-
} catch {
|
|
1188
|
-
// An unparseable body is often a proxy/error page that quotes the
|
|
1189
|
-
// request, so it goes through redaction too.
|
|
1190
|
-
data = { raw: redact(text) };
|
|
1191
|
-
}
|
|
1192
|
-
if (!res.ok) {
|
|
1193
|
-
if (isVersionGate(res.status, data)) {
|
|
1194
|
-
throw versionGateError(data, res.status);
|
|
1195
|
-
}
|
|
1196
|
-
const msg =
|
|
1197
|
-
(data && (data.error?.message || data.error || data.message)) ||
|
|
1198
|
-
`HTTP ${res.status}`;
|
|
1199
|
-
const err = new Error(redact(typeof msg === 'string' ? msg : JSON.stringify(msg)));
|
|
1200
|
-
// The buffered twin of postStream's upstream-timeout classification.
|
|
1201
|
-
//
|
|
1202
|
-
// Aegis1 answers a NON-streaming request by draining the same generator
|
|
1203
|
-
// itself, so the provider's deadline arrives here as a plain 503 carrying
|
|
1204
|
-
// the same sentence a streaming caller gets as an error frame. Without
|
|
1205
|
-
// this the one failure had two shapes depending on wire form: the stream
|
|
1206
|
-
// path said `status 0 / code timeout` with an explanation, while the
|
|
1207
|
-
// buffered path said `status 503 / code undefined` and nothing else —
|
|
1208
|
-
// measured live, same provider, same 10s wall, ~10.8s either way. A host
|
|
1209
|
-
// gating on `code === 'timeout'` therefore saw it on one path only.
|
|
1210
|
-
//
|
|
1211
|
-
// Status becomes 0 for the same reason as the stream path: this is
|
|
1212
|
-
// "waited too long", which every downstream branch already reads as
|
|
1213
|
-
// status 0 + code, and a 5xx would instead be taken as a server fault.
|
|
1214
|
-
// The server's own number is preserved on `serverStatus`, because 5xx is
|
|
1215
|
-
// worth knowing even when it means the same thing to the caller.
|
|
1216
|
-
const upstreamTimeout =
|
|
1217
|
-
res.status >= 500 && res.status < 600 && SSE_UPSTREAM_TIMEOUT_PATTERN.test(err.message);
|
|
1218
|
-
if (upstreamTimeout) {
|
|
1219
|
-
err.serverStatus = res.status;
|
|
1220
|
-
err.status = 0;
|
|
1221
|
-
err.code = 'timeout';
|
|
1222
|
-
err.message = upstreamTimeoutMessage(err.message);
|
|
1223
|
-
} else {
|
|
1224
|
-
err.status = res.status;
|
|
1225
|
-
}
|
|
1226
|
-
err.data = data;
|
|
1227
|
-
throw err;
|
|
1228
|
-
}
|
|
1229
|
-
// A 2xx carrying a version gate body: some streaming endpoints answer
|
|
1230
|
-
// JSON with a real status mid-stream. Without this the gate would be
|
|
1231
|
-
// invisible on exactly those paths.
|
|
1232
|
-
if (data && data.code === 'version_mismatch') {
|
|
1233
|
-
throw versionGateError(data, res.status);
|
|
1234
|
-
}
|
|
1235
|
-
return data;
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
/** Extract a human message from a structured backend error body. */
|
|
1239
|
-
function errorMessageOf(data) {
|
|
1240
|
-
if (!data) return '';
|
|
1241
|
-
const e = data.error;
|
|
1242
|
-
if (typeof e === 'string') return e;
|
|
1243
|
-
if (e && typeof e.message === 'string') return e.message;
|
|
1244
|
-
if (e && typeof e.error === 'string') return e.error;
|
|
1245
|
-
if (typeof data.message === 'string') return data.message;
|
|
1246
|
-
if (typeof data.error_message === 'string') return data.error_message;
|
|
1247
|
-
return '';
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
/** Throw an Error carrying status/data from a 2xx body that still has an
|
|
1251
|
-
* error field (seen on streaming endpoints that answer JSON mid-stream). */
|
|
1252
|
-
function throwErrorFrom(data, status) {
|
|
1253
|
-
// Keep the gate typed on this path too: it is the one that carries JSON
|
|
1254
|
-
// errors inside an otherwise-successful stream, which is where a gate
|
|
1255
|
-
// response would otherwise be flattened into a generic message.
|
|
1256
|
-
if (data && data.code === 'version_mismatch') {
|
|
1257
|
-
throw versionGateError(data, status || 426);
|
|
1258
|
-
}
|
|
1259
|
-
const msg = redact(errorMessageOf(data));
|
|
1260
|
-
if (!msg) return;
|
|
1261
|
-
const err = new Error(msg);
|
|
1262
|
-
err.status = status || 500;
|
|
1263
|
-
err.data = data;
|
|
1264
|
-
throw err;
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
// Memory endpoints authenticate with a memory_token, not the API key.
|
|
1268
|
-
async function getMemoryToken() {
|
|
1269
|
-
if (memoryToken) return memoryToken;
|
|
1270
|
-
if (memoryTokenCache) return memoryTokenCache;
|
|
1271
|
-
const info = await apiPost('/api/verify-api-key', { api_key: apiKey });
|
|
1272
|
-
if (!info || !info.memory_token) {
|
|
1273
|
-
// The campaign is Phase 1's `memory_quota`, not a new `memory_token`: the
|
|
1274
|
-
// prompt family (memory cap notice, memory list, memory view) files under
|
|
1275
|
-
// one id so the funnel keeps one row per prompt intent, and the plan's
|
|
1276
|
-
// five ids are what the telemetry allowlist and the baseline table carry.
|
|
1277
|
-
const link = promptUrl('upgrade', 'memory_quota');
|
|
1278
|
-
throw new Error(
|
|
1279
|
-
'This AEGIS account has no memory token. '
|
|
1280
|
-
+ (link
|
|
1281
|
-
? `Enable cloud memory at ${link}`
|
|
1282
|
-
: 'Enable cloud memory in your AEGIS account settings.')
|
|
1283
|
-
);
|
|
1284
|
-
}
|
|
1285
|
-
memoryTokenCache = info.memory_token;
|
|
1286
|
-
return memoryTokenCache;
|
|
1287
|
-
}
|
|
1288
|
-
|
|
1289
|
-
function memoryHeaders(token) {
|
|
1290
|
-
return {
|
|
1291
|
-
'Content-Type': 'application/json',
|
|
1292
|
-
'X-AEGIS-Version': clientVersion,
|
|
1293
|
-
Authorization: `Bearer ${token}`,
|
|
1294
|
-
};
|
|
1295
|
-
}
|
|
1296
|
-
|
|
1297
|
-
/**
|
|
1298
|
-
* Replace the API key at runtime (desktop in-app key entry). Clears the
|
|
1299
|
-
* cached memory token so the next memory/account call re-exchanges with the
|
|
1300
|
-
* new key. Returns the trimmed raw key — main-process only; hosts must mask
|
|
1301
|
-
* it before returning anything to a renderer.
|
|
1302
|
-
*/
|
|
1303
|
-
function setApiKey(key) {
|
|
1304
|
-
apiKey = typeof key === 'string' ? key.trim() : '';
|
|
1305
|
-
memoryTokenCache = null;
|
|
1306
|
-
return apiKey;
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
|
-
// -------------------------------------------------------------------------
|
|
1310
|
-
// High-level API (returns raw backend data; hosts decide how to format it)
|
|
1311
|
-
// -------------------------------------------------------------------------
|
|
1312
|
-
|
|
1313
|
-
async function verifyApiKey() {
|
|
1314
|
-
return apiPost('/api/verify-api-key', { api_key: apiKey });
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
|
-
/**
|
|
1318
|
-
* Ask aegis1 for a free device key when the caller has none configured yet
|
|
1319
|
-
* (`POST /api/v1/auth/register-device`). Idempotent server-side on
|
|
1320
|
-
* `fingerprint` — the same fingerprint always returns the same account's
|
|
1321
|
-
* key rather than minting a new one. A BRAND-NEW fingerprint (first call
|
|
1322
|
-
* ever for this machine) is additionally granted aegis1's 30-day
|
|
1323
|
-
* welcome-trial `unlimited` entitlement in the SAME request that mints the
|
|
1324
|
-
* key — a token-bank credit of UNLIMITED_CLOUD_ALLOWANCE_MICROS plus a
|
|
1325
|
-
* time-boxed `subscriptions` row (aegis1 commit 4372830), so a fresh
|
|
1326
|
-
* install can use pooled cloud models immediately instead of starting at a
|
|
1327
|
-
* zero balance. Re-registering an already-known fingerprint does NOT
|
|
1328
|
-
* re-grant it; the pool balance gate still applies once the allowance is
|
|
1329
|
-
* spent or the 30 days lapse. Sends no API key of its own — there isn't
|
|
1330
|
-
* one yet. `opts.app` names the host ('cli' | 'desktop' | 'mcp') so the
|
|
1331
|
-
* server files this machine under its real name, not 'other'.
|
|
1332
|
-
*/
|
|
1333
|
-
async function registerDevice(fingerprint, opts) {
|
|
1334
|
-
return apiPost('/api/v1/auth/register-device', { fingerprint, app: opts && opts.app }, undefined, opts);
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
/** Build the OpenAI-style messages array from either a full history or the
|
|
1338
|
-
* single-shot { system, prompt } shorthand.
|
|
1339
|
-
*
|
|
1340
|
-
* The history is no longer returned verbatim when present: doing so dropped
|
|
1341
|
-
* `system` entirely, so the agent loop's ported persona disappeared on this
|
|
1342
|
-
* transport alone. The system turn is prepended unless the caller already
|
|
1343
|
-
* supplied one, and a non-empty `prompt` is appended as a final user turn
|
|
1344
|
-
* (skipped when the history already ends with that same turn). */
|
|
1345
|
-
/** Flatten a message `content` to text. Kept local (this file is the
|
|
1346
|
-
* dependency-free transport and must not require lib/local/*): an array
|
|
1347
|
-
* is the OpenAI content-part form a dropped picture produces, and its text
|
|
1348
|
-
* parts are what a duplicate check can meaningfully compare. */
|
|
1349
|
-
function flattenContent(content) {
|
|
1350
|
-
if (content == null) return '';
|
|
1351
|
-
if (typeof content === 'string') return content;
|
|
1352
|
-
if (!Array.isArray(content)) return String(content);
|
|
1353
|
-
let out = '';
|
|
1354
|
-
for (let i = 0; i < content.length; i += 1) {
|
|
1355
|
-
const part = content[i];
|
|
1356
|
-
if (!part || typeof part !== 'object') continue;
|
|
1357
|
-
if (typeof part.text === 'string') out += (out ? '\n' : '') + part.text;
|
|
1358
|
-
else if (part.type === 'image_url') out += (out ? '\n' : '') + '[image]';
|
|
1359
|
-
}
|
|
1360
|
-
return out;
|
|
1361
|
-
}
|
|
1362
|
-
|
|
1363
|
-
function buildMessages(messages, system, prompt) {
|
|
1364
|
-
const history = Array.isArray(messages) ? messages.filter(Boolean) : [];
|
|
1365
|
-
const out = [];
|
|
1366
|
-
if (system && !history.some((m) => m && m.role === 'system')) {
|
|
1367
|
-
out.push({ role: 'system', content: system });
|
|
1368
|
-
}
|
|
1369
|
-
out.push(...history);
|
|
1370
|
-
// `prompt` may be a content-part ARRAY when the turn carries dropped
|
|
1371
|
-
// attachments (lib/local/attachments.js buildContent). The old
|
|
1372
|
-
// `!== ''` test plus a strict `===` duplicate check silently DROPPED an
|
|
1373
|
-
// array prompt — the pooled transport would have sent the history with no
|
|
1374
|
-
// question and no picture attached to it.
|
|
1375
|
-
const hasPrompt =
|
|
1376
|
-
prompt != null && (typeof prompt === 'string' ? prompt !== '' : Array.isArray(prompt) && prompt.length > 0);
|
|
1377
|
-
if (hasPrompt) {
|
|
1378
|
-
const last = out[out.length - 1];
|
|
1379
|
-
const sameText =
|
|
1380
|
-
Array.isArray(prompt) && last && last.role === 'user'
|
|
1381
|
-
? flattenContent(last.content) === flattenContent(prompt)
|
|
1382
|
-
: last && last.role === 'user' && last.content === prompt;
|
|
1383
|
-
if (!sameText) {
|
|
1384
|
-
out.push({ role: 'user', content: prompt });
|
|
1385
|
-
}
|
|
1386
|
-
}
|
|
1387
|
-
return out;
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
/**
|
|
1391
|
-
* Chat completion against the AEGIS pool (API key auth). Non-streaming by
|
|
1392
|
-
* default (structured JSON error bodies — this is what the MCP host relies
|
|
1393
|
-
* on). When `stream: true` AND `onStream` is a function, the request is sent
|
|
1394
|
-
* with `stream: true` and each SSE delta is delivered as `onStream({ delta })`.
|
|
1395
|
-
* The resolved value is normalised to the same shape as the non-streaming
|
|
1396
|
-
* response either way, so hosts can reconcile final text after the last chunk.
|
|
1397
|
-
*
|
|
1398
|
-
* Additive options shared with byokChatCompletion():
|
|
1399
|
-
* - `messages` full OpenAI-format history (supersedes prompt/system)
|
|
1400
|
-
* - `extra` extra body fields merged verbatim (e.g. { aegis_memory,
|
|
1401
|
-
* session } for the online host's synced-memory writeback)
|
|
1402
|
-
* - `onReasoning` receives `delta.reasoning_content` text as it streams
|
|
1403
|
-
* (pool-brain worker findings). Kept off the answer channel
|
|
1404
|
-
* so a reasoning-only stream still counts as unanswered.
|
|
1405
|
-
* - `idleTimeoutMs` override the stalled-stream watchdog for this call
|
|
1406
|
-
* (a worker fan-out is legitimately silent between passes)
|
|
1407
|
-
* - `maxTokens` output ceiling. Omitted from the body when absent so the
|
|
1408
|
-
* server's own budget applies — on a pooled request that is
|
|
1409
|
-
* the `effort` ladder, and a number sent from here caps it.
|
|
1410
|
-
* - `effort` / `workers` pooled-brain budget rung and fan-out size.
|
|
1411
|
-
* Forwarded only inside `extra`, as the server reads them off
|
|
1412
|
-
* the body (aegis1 services/pool_brain.py parse_brain_request)
|
|
1413
|
-
* and sizes the budget from them.
|
|
1414
|
-
*/
|
|
1415
|
-
async function chatCompletion({
|
|
1416
|
-
prompt,
|
|
1417
|
-
system,
|
|
1418
|
-
messages,
|
|
1419
|
-
model,
|
|
1420
|
-
mode,
|
|
1421
|
-
maxTokens,
|
|
1422
|
-
stream = false,
|
|
1423
|
-
onStream,
|
|
1424
|
-
onReasoning,
|
|
1425
|
-
idleTimeoutMs,
|
|
1426
|
-
includeUsage,
|
|
1427
|
-
signal,
|
|
1428
|
-
extra,
|
|
1429
|
-
// Opt-in only: the caller (the agent loop, which already knows whether
|
|
1430
|
-
// the tools it just attached to `extra` are code-capable) decides
|
|
1431
|
-
// whether this turn needs one — this file has no policy of its own for
|
|
1432
|
-
// when to attach it, only how. See aegis1 services/agent_gate.py
|
|
1433
|
-
// CODE_TOOLS for the server-side verb list a caller should mirror.
|
|
1434
|
-
agentKey,
|
|
1435
|
-
} = {}) {
|
|
1436
|
-
// Model-first: an explicit `model` pins that provider id verbatim; with no
|
|
1437
|
-
// model the server picks its default (no client-invented tier id). `mode`
|
|
1438
|
-
// is a legacy server-side shorthand — forwarded verbatim only when the
|
|
1439
|
-
// caller supplies it, never defaulted, never built into a model id.
|
|
1440
|
-
//
|
|
1441
|
-
// `max_tokens` is omitted entirely when the caller states none, rather than
|
|
1442
|
-
// defaulted here. The server has its own budget ladder (`mode`/`effort` on
|
|
1443
|
-
// the pooled path) and treats a body max_tokens as a *ceiling* over it, so
|
|
1444
|
-
// an invented 4096 was not a harmless default: it capped every pass of a
|
|
1445
|
-
// pooled-brain fan-out at 4096 and overrode the ladder the caller's effort
|
|
1446
|
-
// selected. Omitting it is the documented way to say "server default" (see
|
|
1447
|
-
// mcp/tools.js's max_tokens description).
|
|
1448
|
-
const body = {
|
|
1449
|
-
messages: buildMessages(messages, system, prompt),
|
|
1450
|
-
...(maxTokens ? { max_tokens: maxTokens } : {}),
|
|
1451
|
-
...(extra || {}),
|
|
1452
|
-
};
|
|
1453
|
-
if (model) body.model = model;
|
|
1454
|
-
else if (mode) body.mode = mode;
|
|
1455
|
-
const headers = authHeaders(agentKey ? { 'X-AEGIS-Agent-Key': agentKey } : undefined);
|
|
1456
|
-
if (!stream || typeof onStream !== 'function') {
|
|
1457
|
-
// `signal` must be forwarded here. It was not, and the consequence was
|
|
1458
|
-
// silent: a caller that aborted a non-streaming turn saw the abort
|
|
1459
|
-
// ignored, the request ran on to its timeout, and the eventual error was
|
|
1460
|
-
// a timeout the user never asked for. postStream's own fallback at the
|
|
1461
|
-
// bottom of this function always forwarded it — only this branch did not.
|
|
1462
|
-
return decodeDsmlInResult(
|
|
1463
|
-
await apiPost('/api/v1/chat/completions', { ...body, stream: false }, headers, { signal })
|
|
1464
|
-
);
|
|
1465
|
-
}
|
|
1466
|
-
// An OpenAI-compatible SSE response carries no `usage` unless the caller
|
|
1467
|
-
// asks for it (`stream_options.include_usage`). Without this the streamed
|
|
1468
|
-
// AEGIS pool call — the only path the desktop uses for the Nexus brain —
|
|
1469
|
-
// resolved with no usage at all, so a pooled turn could report its text but
|
|
1470
|
-
// never what it spent, while the same model through the non-streaming MCP
|
|
1471
|
-
// path reported both. Only the streaming request sets it: `stream_options`
|
|
1472
|
-
// is invalid alongside `stream:false`, so the non-stream branch above and
|
|
1473
|
-
// every non-stream fallback must stay clean.
|
|
1474
|
-
if (includeUsage) body.stream_options = { include_usage: true };
|
|
1475
|
-
return postStream('/api/v1/chat/completions', body, headers, onStream, signal, {
|
|
1476
|
-
onReasoning,
|
|
1477
|
-
idleTimeoutMs,
|
|
1478
|
-
// A server that predates `stream_options` 400s the whole request; the
|
|
1479
|
-
// stream is worth more than the token count, so retry on the wire without
|
|
1480
|
-
// the hint before sacrificing streaming for the non-stream fallback.
|
|
1481
|
-
retryWithoutStreamOptions: Boolean(includeUsage),
|
|
1482
|
-
});
|
|
1483
|
-
}
|
|
1484
|
-
|
|
1485
|
-
/**
|
|
1486
|
-
* BYOK chat completion: relay a provider request through
|
|
1487
|
-
* /api/v1/byok/chat/completions using a per-request X-Provider-Key. The
|
|
1488
|
-
* provider key never touches AEGIS storage — it is forwarded straight to the
|
|
1489
|
-
* provider for this request only. Mirrors chatCompletion()'s streaming /
|
|
1490
|
-
* fallback semantics exactly.
|
|
1491
|
-
*
|
|
1492
|
-
* The caller's *AEGIS* key is sent alongside the provider key as X-AEGIS-Key.
|
|
1493
|
-
* Two credentials, two headers, on purpose: the provider key authenticates the
|
|
1494
|
-
* upstream call, the AEGIS key says whose bank pays the handling fee —
|
|
1495
|
-
* `_byok_identify_user` on the server resolves the payer from it, and nothing
|
|
1496
|
-
* else. With no AEGIS key the header is omitted and the call is anonymous;
|
|
1497
|
-
* THIS function still sends it, because it is a transport and the route is
|
|
1498
|
-
* unauthenticated by design (aegis1 tests/test_byok_fee.py pins the anonymous
|
|
1499
|
-
* path as allowed) — refusing here would break every other caller of a
|
|
1500
|
-
* published endpoint.
|
|
1501
|
-
*
|
|
1502
|
-
* Attribution is the whole game, because an unattributed turn is the one way
|
|
1503
|
-
* a BYOK call escapes the fee: the relay serves it, `charge_byok` never runs
|
|
1504
|
-
* (`app.py` charges only `if _byok_user_id:`), and the call is logged against
|
|
1505
|
-
* user 0 as uncollected — a free ride. So the shipped HOSTS refuse a keyless
|
|
1506
|
-
* BYOK send before the relay is reached: desktop/lib/local/engine.js raises
|
|
1507
|
-
* 401, and the desktop app and the CLI share that engine (the CLI stages it
|
|
1508
|
-
* as cli/vendor/desktop/lib/local/engine.js), so one gate covers both. Every
|
|
1509
|
-
* turn is then attributable, and therefore billable: a funded balance is
|
|
1510
|
-
* debited, an unfunded one is recorded as owed — `charge_byok` clamps the
|
|
1511
|
-
* debit at zero and never refuses the call, so "cannot pay" and "must not be
|
|
1512
|
-
* billed" stop being the same thing. `AEGIS_BYOK_REQUIRE_BALANCE` (off by
|
|
1513
|
-
* default) remains the server's own, separate 402 gate and is not what makes
|
|
1514
|
-
* the fee land.
|
|
1515
|
-
*/
|
|
1516
|
-
async function byokChatCompletion({
|
|
1517
|
-
provider = 'openai',
|
|
1518
|
-
model,
|
|
1519
|
-
messages,
|
|
1520
|
-
prompt,
|
|
1521
|
-
system,
|
|
1522
|
-
maxTokens,
|
|
1523
|
-
effort,
|
|
1524
|
-
reasoningEffort,
|
|
1525
|
-
tools,
|
|
1526
|
-
toolChoice,
|
|
1527
|
-
stream = false,
|
|
1528
|
-
onStream,
|
|
1529
|
-
signal,
|
|
1530
|
-
providerKey,
|
|
1531
|
-
baseURL,
|
|
1532
|
-
} = {}) {
|
|
1533
|
-
const key = providerKey !== undefined ? providerKey : opts.providerKey;
|
|
1534
|
-
// `custom` is the one catalog provider whose address the server does NOT
|
|
1535
|
-
// know: every other id maps to a host aegis1 has baked in, and `custom`
|
|
1536
|
-
// travels as `base_url` on each request instead. So a custom call that
|
|
1537
|
-
// names no endpoint is not "a provider we can guess a default for" — there
|
|
1538
|
-
// is no default to guess, and aegis1 answers 400 (`_byok_custom_base_url`
|
|
1539
|
-
// refuses it). Refusing HERE turns that server-side 400 into a client-side
|
|
1540
|
-
// sentence naming the missing half, which is the difference between "custom
|
|
1541
|
-
// is broken" and "you saved a key but never saved the endpoint".
|
|
1542
|
-
//
|
|
1543
|
-
// Reachable without the card: `/byok-key custom <key>` saves a key alone,
|
|
1544
|
-
// and a hand-edited row can hold a key with no address. Guarded on the
|
|
1545
|
-
// value actually being absent (`!baseURL`), never on the provider alone, so
|
|
1546
|
-
// a correctly-saved custom row is untouched.
|
|
1547
|
-
if (provider === 'custom' && !baseURL) {
|
|
1548
|
-
const err = new Error(
|
|
1549
|
-
'the "custom" provider dials the endpoint you name, and this call names none — ' +
|
|
1550
|
-
'save the address first: /model-add custom <https-base-url> <api-key> <model-id>, ' +
|
|
1551
|
-
'or the endpoint field in Settings › Provider (custom).'
|
|
1552
|
-
);
|
|
1553
|
-
err.status = 400;
|
|
1554
|
-
err.code = 'custom_endpoint_missing';
|
|
1555
|
-
throw err;
|
|
1556
|
-
}
|
|
1557
|
-
// Same rule as the pooled path above: omit `max_tokens` entirely when the
|
|
1558
|
-
// caller states none, rather than inventing a default. The server treats a
|
|
1559
|
-
// body max_tokens as a ceiling *over* its own ladder, so a defaulted 4096
|
|
1560
|
-
// was not a harmless floor — it capped the call at 4k and overrode the
|
|
1561
|
-
// budget the caller's effort selected, exactly as on the pooled path.
|
|
1562
|
-
//
|
|
1563
|
-
// This survived the earlier fix (which only touched chatCompletion) and the
|
|
1564
|
-
// guard meant to catch it, because test/budget.test.mjs searched for a
|
|
1565
|
-
// direct assignment of 4096 to maxTokens while the defect here is a
|
|
1566
|
-
// fallback expression inside the body literal — the verifier could not see
|
|
1567
|
-
// the shape it was written to forbid. (The guard now reads this file as
|
|
1568
|
-
// text, comments included, so this note names no forbidden literal.)
|
|
1569
|
-
const body = {
|
|
1570
|
-
provider,
|
|
1571
|
-
messages: buildMessages(messages, system, prompt),
|
|
1572
|
-
...(maxTokens ? { max_tokens: maxTokens } : {}),
|
|
1573
|
-
// Native effort knobs, forwarded verbatim and ONLY when a caller states
|
|
1574
|
-
// one — never invented here, because a made-up level overrides the
|
|
1575
|
-
// vendor's own default. The field name is not portable: DeepSeek's
|
|
1576
|
-
// Anthropic-compatible surface takes `effort` (low|high|max), while the
|
|
1577
|
-
// OpenAI-shaped vendors take `reasoning_effort` (low|medium|high). The
|
|
1578
|
-
// caller translates the rung per dialect and names the field, so neither
|
|
1579
|
-
// field is ever sent blind to a strict validator — Groq answers 400 for
|
|
1580
|
-
// any level outside a model's supported set, so a misfiled knob is a
|
|
1581
|
-
// failed turn, not a harmless extra key.
|
|
1582
|
-
...(effort ? { effort } : {}),
|
|
1583
|
-
...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),
|
|
1584
|
-
// Forwarded only when the caller actually supplied a schema — aegis1's
|
|
1585
|
-
// byok_chat_completions (app.py) reads `tools`/`tool_choice` off the body
|
|
1586
|
-
// and passes each to the provider only `if tools:`, so an empty array
|
|
1587
|
-
// here would still be a behavioural change for a provider that treats
|
|
1588
|
-
// `tools: []` differently from the field's plain absence.
|
|
1589
|
-
...(Array.isArray(tools) && tools.length ? { tools } : {}),
|
|
1590
|
-
...(toolChoice ? { tool_choice: toolChoice } : {}),
|
|
1591
|
-
// Read server-side ONLY for provider "custom" (aegis1 app.py
|
|
1592
|
-
// byok_chat_completions) — every other provider's upstream host is a
|
|
1593
|
-
// constant the server already knows, so sending this for them is a
|
|
1594
|
-
// no-op rather than a behaviour change.
|
|
1595
|
-
...(baseURL ? { base_url: baseURL } : {}),
|
|
1596
|
-
};
|
|
1597
|
-
if (model) body.model = model;
|
|
1598
|
-
const headers = {
|
|
1599
|
-
'Content-Type': 'application/json',
|
|
1600
|
-
'X-AEGIS-Version': clientVersion,
|
|
1601
|
-
'X-Provider-Key': key,
|
|
1602
|
-
};
|
|
1603
|
-
// Identify the payer. Absent key => anonymous call, which the server
|
|
1604
|
-
// accepts but cannot bill; sending it is what turns a BYOK turn into
|
|
1605
|
-
// billable traffic instead of a free ride.
|
|
1606
|
-
if (apiKey) headers['X-AEGIS-Key'] = apiKey;
|
|
1607
|
-
if (!stream || typeof onStream !== 'function') {
|
|
1608
|
-
return decodeDsmlInResult(await apiPost('/api/v1/byok/chat/completions', { ...body, stream: false }, headers));
|
|
1609
|
-
}
|
|
1610
|
-
return postStream('/api/v1/byok/chat/completions', body, headers, onStream, signal);
|
|
1611
|
-
}
|
|
1612
|
-
|
|
1613
|
-
/** Extract the assistant text from a full (non-streamed) completion JSON. */
|
|
1614
|
-
function textOf(data) {
|
|
1615
|
-
const choice = data && data.choices && data.choices[0];
|
|
1616
|
-
const content = choice && (choice.message && choice.message.content);
|
|
1617
|
-
return typeof content === 'string' ? content : '';
|
|
1618
|
-
}
|
|
1619
|
-
|
|
1620
|
-
/**
|
|
1621
|
-
* One-shot DSML decode for a non-streamed completion: the whole answer
|
|
1622
|
-
* already arrived in one JSON payload, so there is no partial-token hold-
|
|
1623
|
-
* back to do — just decode, drift-decode what the well-formed pass missed,
|
|
1624
|
-
* and strip whatever residue would otherwise render as garble. Mutates and
|
|
1625
|
-
* returns `data` so every non-stream return site in this module can wrap
|
|
1626
|
-
* its result the same way the streaming path's `message.content` is clean.
|
|
1627
|
-
*/
|
|
1628
|
-
function decodeDsmlInResult(data) {
|
|
1629
|
-
const choice = data && data.choices && data.choices[0];
|
|
1630
|
-
const content = choice && choice.message && choice.message.content;
|
|
1631
|
-
if (typeof content !== 'string' || content.indexOf('|') === -1) return data;
|
|
1632
|
-
const once = decodeDeepSeekDSML(content);
|
|
1633
|
-
const drift = decodeDeepSeekDSMLDrift(once.text);
|
|
1634
|
-
choice.message.content = dsmlResidue(drift.text);
|
|
1635
|
-
const calls = [...once.calls, ...drift.calls];
|
|
1636
|
-
if (calls.length) {
|
|
1637
|
-
data.toolCalls = [
|
|
1638
|
-
...(Array.isArray(data.toolCalls) ? data.toolCalls : []),
|
|
1639
|
-
...calls.map((c) => ({ id: '', name: c.name, args: c.args || {} })),
|
|
1640
|
-
];
|
|
1641
|
-
}
|
|
1642
|
-
return data;
|
|
1643
|
-
}
|
|
1644
|
-
|
|
1645
|
-
/**
|
|
1646
|
-
* POST body with `stream: true` and forward SSE deltas to onStream.
|
|
1647
|
-
* Shared by the AEGIS pool and the BYOK relay so every host parses exactly
|
|
1648
|
-
* one wire format.
|
|
1649
|
-
*
|
|
1650
|
-
* Handles two servers gracefully:
|
|
1651
|
-
* - a real SSE endpoint -> incremental deltas, normalised final result
|
|
1652
|
-
* - an endpoint that ignores `stream` and replies with plain JSON (or
|
|
1653
|
-
* rejects `stream: true` outright) -> one-shot fallback: deliver the full
|
|
1654
|
-
* text as a single delta and resolve the parsed JSON, unchanged.
|
|
1655
|
-
* This keeps streaming purely additive for hosts that opt in.
|
|
1656
|
-
*/
|
|
1657
|
-
async function postStream(path, body, headers, onStream, signal, streamOpts) {
|
|
1658
|
-
const {
|
|
1659
|
-
onReasoning, idleTimeoutMs, retryWithoutStreamOptions,
|
|
1660
|
-
_transientStreamAttempt: transientStreamAttempt = 0,
|
|
1661
|
-
} = streamOpts || {};
|
|
1662
|
-
const request = (payload) =>
|
|
1663
|
-
// `boundedFetch` here bounds time-to-*headers* only: fetch resolves when
|
|
1664
|
-
// the status line lands, and the timer is cleared in its `finally`, so a
|
|
1665
|
-
// legitimately long generation is never cut off by it. What it does fix is
|
|
1666
|
-
// the gap the idle watchdog cannot reach — a server that accepts the
|
|
1667
|
-
// socket and never sends response headers, where `reader.read()` has not
|
|
1668
|
-
// been reached yet and so nothing is watching at all.
|
|
1669
|
-
fetchWithRateLimitRetry(`${apiBase}${path}`, {
|
|
1670
|
-
method: 'POST',
|
|
1671
|
-
headers,
|
|
1672
|
-
body: JSON.stringify({ ...payload, stream: true }),
|
|
1673
|
-
signal,
|
|
1674
|
-
});
|
|
1675
|
-
let res;
|
|
1676
|
-
try {
|
|
1677
|
-
res = await request(body);
|
|
1678
|
-
} catch (err) {
|
|
1679
|
-
// The headers never arrived, so `boundedFetchRetryingDeadSocket` inside
|
|
1680
|
-
// `request` has already spent its retries and this is a real refusal.
|
|
1681
|
-
throw err;
|
|
1682
|
-
}
|
|
1683
|
-
|
|
1684
|
-
// A version gate is a pre-flight refusal, not a schema complaint: the
|
|
1685
|
-
// server rejects *every* shape of this request with 426, so the
|
|
1686
|
-
// `stream_options` retry below and the `stream: false` fallback after it
|
|
1687
|
-
// each buy a wasted round-trip and then report an opaque status. Fail on
|
|
1688
|
-
// the first one. Checked by status alone (no body read) so the happy path
|
|
1689
|
-
// pays nothing for this.
|
|
1690
|
-
if (!res.ok && res.status === 426) {
|
|
1691
|
-
let gateData = {};
|
|
1692
|
-
try {
|
|
1693
|
-
// Capped like every other body read: a gate response is still a
|
|
1694
|
-
// response from a host we do not control the size of.
|
|
1695
|
-
const t = await readCappedText(res);
|
|
1696
|
-
gateData = t ? JSON.parse(t) : {};
|
|
1697
|
-
} catch {
|
|
1698
|
-
gateData = {}; // a gate with an unreadable body is still a gate
|
|
1699
|
-
}
|
|
1700
|
-
throw versionGateError(gateData, res.status);
|
|
1701
|
-
}
|
|
1702
|
-
|
|
1703
|
-
// Ask for the token count, but never at the cost of the stream: a server
|
|
1704
|
-
// that predates `stream_options` rejects the request outright, so drop that
|
|
1705
|
-
// one hint and put it back on the wire before falling back to a non-stream
|
|
1706
|
-
// response (which would answer in one lump and end the live paint).
|
|
1707
|
-
if (!res.ok && retryWithoutStreamOptions && body.stream_options) {
|
|
1708
|
-
try {
|
|
1709
|
-
if (res.body) await res.body.cancel();
|
|
1710
|
-
} catch {
|
|
1711
|
-
/* the failed response is being discarded anyway */
|
|
1712
|
-
}
|
|
1713
|
-
const cleanBody = { ...body };
|
|
1714
|
-
delete cleanBody.stream_options;
|
|
1715
|
-
body = cleanBody;
|
|
1716
|
-
try {
|
|
1717
|
-
res = await request(body);
|
|
1718
|
-
} catch (err) {
|
|
1719
|
-
throw err;
|
|
1720
|
-
}
|
|
1721
|
-
}
|
|
1722
|
-
|
|
1723
|
-
if (!res.ok) {
|
|
1724
|
-
// The endpoint may not accept `stream: true`. Retry once without it so
|
|
1725
|
-
// the caller gets the normal structured JSON (result or error). Strip
|
|
1726
|
-
// `stream_options` too — it is only legal with `stream: true`, so leaving
|
|
1727
|
-
// it on would turn this graceful fallback into a second rejection.
|
|
1728
|
-
const cleanBody = { ...body };
|
|
1729
|
-
delete cleanBody.stream_options;
|
|
1730
|
-
// `signal` is forwarded here too: this is the *non-stream fallback* of a
|
|
1731
|
-
// stream call, i.e. the path taken when the server answered a streaming
|
|
1732
|
-
// request with plain JSON. Dropping the signal here meant an aborted turn
|
|
1733
|
-
// kept waiting on a request nobody was listening for any more — the
|
|
1734
|
-
// caller had already moved on, and the host held the socket.
|
|
1735
|
-
const data = decodeDsmlInResult(await apiPost(path, { ...cleanBody, stream: false }, headers, { signal }));
|
|
1736
|
-
const fullText = textOf(data);
|
|
1737
|
-
if (fullText) onStream({ delta: fullText });
|
|
1738
|
-
return data;
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
|
-
const contentType = res.headers.get('content-type') || '';
|
|
1742
|
-
if (!contentType.includes('text/event-stream')) {
|
|
1743
|
-
// Server ignored the stream flag and answered with plain JSON.
|
|
1744
|
-
const data = decodeDsmlInResult(await parseResponse(res));
|
|
1745
|
-
const fullText = textOf(data);
|
|
1746
|
-
if (fullText) {
|
|
1747
|
-
onStream({ delta: fullText });
|
|
1748
|
-
} else {
|
|
1749
|
-
throwErrorFrom(data, res.status);
|
|
1750
|
-
}
|
|
1751
|
-
return data;
|
|
1752
|
-
}
|
|
1753
|
-
|
|
1754
|
-
// Real SSE: parse `data:` lines incrementally, OpenAI-chunk shape.
|
|
1755
|
-
const reader = res.body.getReader();
|
|
1756
|
-
const decoder = new TextDecoder();
|
|
1757
|
-
let buffer = '';
|
|
1758
|
-
let fullText = '';
|
|
1759
|
-
// Mirrors fullText for the reasoning channel so a reasoning SNAPSHOT is
|
|
1760
|
-
// deduplicated the same way a content snapshot is.
|
|
1761
|
-
let reasoningText = '';
|
|
1762
|
-
let resultModel = body.model;
|
|
1763
|
-
let usage = null;
|
|
1764
|
-
let sseError = '';
|
|
1765
|
-
// Tool-call fragments, keyed by the provider's index. The pool forwards
|
|
1766
|
-
// the provider's own `delta.tool_calls` chunks verbatim when the caller
|
|
1767
|
-
// sent `tools`, so the shared client has to reassemble them the same way
|
|
1768
|
-
// the non-streaming branch does — otherwise a tool-calling turn would
|
|
1769
|
-
// resolve with text only and the caller could never see the calls.
|
|
1770
|
-
const toolCallsByIndex = new Map();
|
|
1771
|
-
let finishReason = null;
|
|
1772
|
-
// `fullText` above stays RAW (it is also the `seen` cursor the snapshot
|
|
1773
|
-
// reconciliation below compares against the provider's own un-stripped
|
|
1774
|
-
// snapshots); `cleanText` is what the caller actually receives — the same
|
|
1775
|
-
// stream, with DeepSeek's chat-template envelope removed — and is what the
|
|
1776
|
-
// final `message.content` below is built from, so a non-streaming caller
|
|
1777
|
-
// reading the resolved result sees the same clean text a streaming caller
|
|
1778
|
-
// already saw via `onStream`.
|
|
1779
|
-
let cleanText = '';
|
|
1780
|
-
const stripEnvelope = makeDeepSeekEnvelopeStripper();
|
|
1781
|
-
|
|
1782
|
-
// Idle watchdog: if the server holds the connection open without ever
|
|
1783
|
-
// sending another byte (a stuck upstream call, a proxy that swallows the
|
|
1784
|
-
// close), reader.read() below waits forever and the whole desktop host
|
|
1785
|
-
// hangs with no way out but force-quit. Cap the gap between chunks —
|
|
1786
|
-
// not the whole response — so a slow-but-alive generation is untouched.
|
|
1787
|
-
//
|
|
1788
|
-
// The budget is per *response*, not per call site: a pooled brain call
|
|
1789
|
-
// announces its worker fan-out in the X-AEGIS-Brain response header, and a
|
|
1790
|
-
// fan-out is legitimately silent until its first worker returns. Keying the
|
|
1791
|
-
// longer budget on a request the caller remembered to flag left the
|
|
1792
|
-
// default Nexus turn (brain model id, checkbox off) dying at 60s — with
|
|
1793
|
-
// the server already past its own fan-out deadline and every worker
|
|
1794
|
-
// billed. See idleBudgetFor().
|
|
1795
|
-
// The budget is measured from the last real `data:` frame, not from the
|
|
1796
|
-
// last read. SSE keep-alive comments (": keep-alive") are transport
|
|
1797
|
-
// framing, and a stalled upstream can emit them forever: a watchdog armed
|
|
1798
|
-
// per read() is reset by every one of them and so never fires, which is
|
|
1799
|
-
// exactly the hang this guard exists to prevent. Only a parsed payload
|
|
1800
|
-
// moves `lastPayloadAt` below.
|
|
1801
|
-
const idleMs = idleBudgetFor(res, idleTimeoutMs);
|
|
1802
|
-
let lastPayloadAt = Date.now();
|
|
1803
|
-
// When this response began, for the one place that needs to tell the two
|
|
1804
|
-
// deadlines apart: a provider timeout frame carries no duration, and the
|
|
1805
|
-
// elapsed time is what separates "the upstream gave up" (seconds, well
|
|
1806
|
-
// inside our budget) from "our own watchdog fired" (the full budget).
|
|
1807
|
-
const streamStartedAt = lastPayloadAt;
|
|
1808
|
-
let keepAlives = 0;
|
|
1809
|
-
async function readWithIdleTimeout() {
|
|
1810
|
-
let timer;
|
|
1811
|
-
let onAbort = null;
|
|
1812
|
-
const remaining = Math.max(0, idleMs - (Date.now() - lastPayloadAt));
|
|
1813
|
-
const timeout = new Promise((_, reject) => {
|
|
1814
|
-
timer = setTimeout(() => {
|
|
1815
|
-
reject(new Error(
|
|
1816
|
-
keepAlives > 0
|
|
1817
|
-
? `stream stalled - only keep-alives for ${idleMs / 1000}s`
|
|
1818
|
-
: `stream stalled - no data for ${idleMs / 1000}s`
|
|
1819
|
-
));
|
|
1820
|
-
}, remaining);
|
|
1821
|
-
});
|
|
1822
|
-
// The caller's abort, raced against the read directly rather than trusted
|
|
1823
|
-
// to propagate through the body stream.
|
|
1824
|
-
//
|
|
1825
|
-
// Whether an abort of the caller's signal reaches a response body that is
|
|
1826
|
-
// already being read is a property of `boundedFetch`, not of this loop —
|
|
1827
|
-
// and it is not a property this loop can observe. Racing here makes "the
|
|
1828
|
-
// caller stopped" a fact the read loop establishes for itself, so Stop
|
|
1829
|
-
// and Escape end the turn at the next chunk boundary regardless of how
|
|
1830
|
-
// the request's signal was assembled. Without it an aborted turn kept
|
|
1831
|
-
// consuming a stream nobody wanted and `chat()` never settled at all.
|
|
1832
|
-
const aborted = signal && typeof signal.addEventListener === 'function'
|
|
1833
|
-
? new Promise((_, reject) => {
|
|
1834
|
-
onAbort = () => {
|
|
1835
|
-
const e = new Error('The turn was stopped.');
|
|
1836
|
-
e.name = 'AbortError';
|
|
1837
|
-
e.code = 'ABORT_ERR';
|
|
1838
|
-
reject(e);
|
|
1839
|
-
};
|
|
1840
|
-
if (signal.aborted) onAbort();
|
|
1841
|
-
else signal.addEventListener('abort', onAbort, { once: true });
|
|
1842
|
-
})
|
|
1843
|
-
: null;
|
|
1844
|
-
try {
|
|
1845
|
-
return await (aborted
|
|
1846
|
-
? Promise.race([reader.read(), timeout, aborted])
|
|
1847
|
-
: Promise.race([reader.read(), timeout]));
|
|
1848
|
-
} finally {
|
|
1849
|
-
clearTimeout(timer);
|
|
1850
|
-
if (signal && onAbort && typeof signal.removeEventListener === 'function') {
|
|
1851
|
-
signal.removeEventListener('abort', onAbort);
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
}
|
|
1855
|
-
|
|
1856
|
-
for (;;) {
|
|
1857
|
-
let done, value;
|
|
1858
|
-
try {
|
|
1859
|
-
({ done, value } = await readWithIdleTimeout());
|
|
1860
|
-
} catch (err) {
|
|
1861
|
-
reader.cancel().catch(() => {});
|
|
1862
|
-
// A reset on the SSE body is the streaming face of the body-phase
|
|
1863
|
-
// fault: `readWithIdleTimeout` races the read but does not classify
|
|
1864
|
-
// what it rejects with, so this used to reach the host as an
|
|
1865
|
-
// unclassified `fetch failed`. Classify it, and attach how much of the
|
|
1866
|
-
// answer was already parsed — `cleanText` is what the caller has
|
|
1867
|
-
// actually SEEN, so an empty one is the only case where re-issuing the
|
|
1868
|
-
// whole request cannot duplicate visible output.
|
|
1869
|
-
const wrapped = classifyBodyTransportFailure(err);
|
|
1870
|
-
if (wrapped && wrapped.code === 'network') {
|
|
1871
|
-
wrapped.bytesRead = cleanText ? 1 : 0;
|
|
1872
|
-
// Nothing was painted, so this is still the first attempt's work
|
|
1873
|
-
// finally reaching the server: repeat the whole request through the
|
|
1874
|
-
// same bounded budget the empty-turn retry uses. Re-entering
|
|
1875
|
-
// `postStream` (rather than re-reading `res` here) keeps the
|
|
1876
|
-
// non-SSE fallback ladder intact — a retry that comes back as plain
|
|
1877
|
-
// JSON is handled by the code above instead of being fed to an SSE
|
|
1878
|
-
// parser that has no frames.
|
|
1879
|
-
if (
|
|
1880
|
-
wrapped.bytesRead === 0
|
|
1881
|
-
&& transientStreamAttempt < TRANSIENT_STREAM_RETRIES
|
|
1882
|
-
&& !(signal && signal.aborted)
|
|
1883
|
-
) {
|
|
1884
|
-
await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, transientStreamAttempt), signal);
|
|
1885
|
-
if (signal && signal.aborted) throw wrapped;
|
|
1886
|
-
return postStream(path, body, headers, onStream, signal, {
|
|
1887
|
-
...streamOpts,
|
|
1888
|
-
_transientStreamAttempt: transientStreamAttempt + 1,
|
|
1889
|
-
});
|
|
1890
|
-
}
|
|
1891
|
-
}
|
|
1892
|
-
throw wrapped || err;
|
|
1893
|
-
}
|
|
1894
|
-
if (done) break;
|
|
1895
|
-
buffer += decoder.decode(value, { stream: true });
|
|
1896
|
-
|
|
1897
|
-
const lines = buffer.split('\n');
|
|
1898
|
-
buffer = lines.pop(); // keep the last partial line for the next read
|
|
1899
|
-
|
|
1900
|
-
for (const rawLine of lines) {
|
|
1901
|
-
const line = rawLine.trim();
|
|
1902
|
-
if (!line.startsWith('data:')) {
|
|
1903
|
-
if (line.startsWith(':')) keepAlives++;
|
|
1904
|
-
continue;
|
|
1905
|
-
}
|
|
1906
|
-
lastPayloadAt = Date.now(); // a real frame: the stream is still speaking
|
|
1907
|
-
const payload = line.slice(5).trim();
|
|
1908
|
-
if (!payload || payload === '[DONE]') continue;
|
|
1909
|
-
let json;
|
|
1910
|
-
try {
|
|
1911
|
-
json = JSON.parse(payload);
|
|
1912
|
-
} catch {
|
|
1913
|
-
continue; // partial/keepalive line — ignore
|
|
1914
|
-
}
|
|
1915
|
-
if (json.error) {
|
|
1916
|
-
if (!sseError) {
|
|
1917
|
-
const e = json.error;
|
|
1918
|
-
sseError =
|
|
1919
|
-
typeof e === 'string'
|
|
1920
|
-
? e
|
|
1921
|
-
: errorMessageOf({ error: e }) || 'stream error';
|
|
1922
|
-
sseError = redact(sseError);
|
|
1923
|
-
}
|
|
1924
|
-
continue;
|
|
1925
|
-
}
|
|
1926
|
-
if (json.model) resultModel = json.model;
|
|
1927
|
-
if (json.usage) usage = json.usage;
|
|
1928
|
-
const choice = json.choices && json.choices[0];
|
|
1929
|
-
if (choice && choice.finish_reason) finishReason = choice.finish_reason;
|
|
1930
|
-
// Extended-reasoning trace: the pool's worker findings (and any
|
|
1931
|
-
// provider CoT) arrive as `delta.reasoning_content` *before* the
|
|
1932
|
-
// synthesis pass writes the visible answer. Deliberately kept out of
|
|
1933
|
-
// `fullText` — deliberation is not an answer, and counting it would
|
|
1934
|
-
// make a no-answer turn look answered to every caller's empty-check.
|
|
1935
|
-
// `delta.*` is an INCREMENT; `message.*` is a SNAPSHOT of the whole
|
|
1936
|
-
// message so far. Collapsing them with `||` made a stream that ends
|
|
1937
|
-
// with a message snapshot append the entire answer a second time —
|
|
1938
|
-
// the duplicated text in the CLI. They are merged here through one
|
|
1939
|
-
// helper that emits only what the caller has not already seen.
|
|
1940
|
-
const advance = (increment, snapshot, seen, emit) => {
|
|
1941
|
-
if (typeof increment === 'string' && increment) {
|
|
1942
|
-
emit(increment);
|
|
1943
|
-
return seen + increment;
|
|
1944
|
-
}
|
|
1945
|
-
if (typeof snapshot === 'string' && snapshot) {
|
|
1946
|
-
if (!seen) { emit(snapshot); return snapshot; }
|
|
1947
|
-
// The usual shape: the snapshot restates everything streamed so
|
|
1948
|
-
// far, so only the tail is new.
|
|
1949
|
-
if (snapshot.startsWith(seen)) {
|
|
1950
|
-
const tail = snapshot.slice(seen.length);
|
|
1951
|
-
if (tail) emit(tail);
|
|
1952
|
-
return snapshot;
|
|
1953
|
-
}
|
|
1954
|
-
// Disjoint from what was already shown — cannot be reconciled, and
|
|
1955
|
-
// appending it would duplicate. Keep what the caller has seen.
|
|
1956
|
-
return seen;
|
|
1957
|
-
}
|
|
1958
|
-
return seen;
|
|
1959
|
-
};
|
|
1960
|
-
|
|
1961
|
-
reasoningText = advance(
|
|
1962
|
-
choice && choice.delta && choice.delta.reasoning_content,
|
|
1963
|
-
choice && choice.message && choice.message.reasoning_content,
|
|
1964
|
-
reasoningText,
|
|
1965
|
-
(chunk) => {
|
|
1966
|
-
if (typeof onReasoning === 'function') onReasoning(chunk);
|
|
1967
|
-
else onStream({ reasoning: chunk });
|
|
1968
|
-
}
|
|
1969
|
-
);
|
|
1970
|
-
|
|
1971
|
-
fullText = advance(
|
|
1972
|
-
choice && choice.delta && choice.delta.content,
|
|
1973
|
-
choice && choice.message && choice.message.content,
|
|
1974
|
-
fullText,
|
|
1975
|
-
(chunk) => {
|
|
1976
|
-
const clean = stripEnvelope(chunk);
|
|
1977
|
-
if (clean) {
|
|
1978
|
-
cleanText += clean;
|
|
1979
|
-
onStream({ delta: clean });
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
);
|
|
1983
|
-
const fragments =
|
|
1984
|
-
(choice && choice.delta && choice.delta.tool_calls) ||
|
|
1985
|
-
(choice && choice.message && choice.message.tool_calls);
|
|
1986
|
-
if (Array.isArray(fragments)) {
|
|
1987
|
-
for (const tc of fragments) {
|
|
1988
|
-
const idx = tc.index == null ? 0 : tc.index;
|
|
1989
|
-
const cur = toolCallsByIndex.get(idx) || {
|
|
1990
|
-
id: '',
|
|
1991
|
-
type: 'function',
|
|
1992
|
-
function: { name: '', arguments: '' },
|
|
1993
|
-
};
|
|
1994
|
-
if (tc.id) cur.id = tc.id;
|
|
1995
|
-
if (tc.type) cur.type = tc.type;
|
|
1996
|
-
const fn = tc.function || {};
|
|
1997
|
-
if (fn.name) cur.function.name = fn.name;
|
|
1998
|
-
if (typeof fn.arguments === 'string') cur.function.arguments += fn.arguments;
|
|
1999
|
-
toolCallsByIndex.set(idx, cur);
|
|
2000
|
-
}
|
|
2001
|
-
}
|
|
2002
|
-
}
|
|
2003
|
-
}
|
|
2004
|
-
|
|
2005
|
-
if (!fullText && sseError) {
|
|
2006
|
-
if (
|
|
2007
|
-
transientStreamAttempt < TRANSIENT_STREAM_RETRIES
|
|
2008
|
-
&& TRANSIENT_STREAM_ERROR_PATTERN.test(sseError)
|
|
2009
|
-
) {
|
|
2010
|
-
await sleep(TRANSIENT_STREAM_BASE_WAIT_MS * Math.pow(2, transientStreamAttempt), signal);
|
|
2011
|
-
return postStream(path, body, headers, onStream, signal, {
|
|
2012
|
-
...streamOpts,
|
|
2013
|
-
_transientStreamAttempt: transientStreamAttempt + 1,
|
|
2014
|
-
});
|
|
2015
|
-
}
|
|
2016
|
-
// Deliberately NOT retried: this sentence is aegis1 relaying an upstream
|
|
2017
|
-
// abort ("Provider request timed out") as a mid-stream error frame with
|
|
2018
|
-
// the headers already 200 OK — the same frame shape as the reset above,
|
|
2019
|
-
// but the stall has already cost the caller a full provider deadline, and
|
|
2020
|
-
// re-issuing would make a stuck upstream cost three of them before the
|
|
2021
|
-
// host could say anything. One attempt, classified, and out.
|
|
2022
|
-
//
|
|
2023
|
-
// What must NOT happen is the shape this used to be thrown in: `res.status`
|
|
2024
|
-
// here is the SSE response's own 200 (the headers landed long before the
|
|
2025
|
-
// error frame did), so the rejection carried "success" as its status and
|
|
2026
|
-
// nothing downstream could classify it — the desktop host printed the raw
|
|
2027
|
-
// stack with `{ status: 200 }` for a turn that never produced a byte. A
|
|
2028
|
-
// timeout is stated in the shape every other "waited too long" on this
|
|
2029
|
-
// lane uses (status 0 + a code), which is what engine.js's `status === 402`
|
|
2030
|
-
// / `status === 400` branches already key off and what local.js translates
|
|
2031
|
-
// its own two clocks into — so "waited too long" stays one branch for
|
|
2032
|
-
// every class.
|
|
2033
|
-
//
|
|
2034
|
-
// Message: the budget is NOT named as the cause any more, because this
|
|
2035
|
-
// branch cannot be our own watchdog. `sseError` comes only from a
|
|
2036
|
-
// `json.error` frame the server sent; our watchdog raises `stream
|
|
2037
|
-
// stalled - …` out of readWithIdleTimeout and never reaches this code.
|
|
2038
|
-
// So every error here is the provider's deadline, already expired, and
|
|
2039
|
-
// the elapsed time says so as a fact rather than as prose — see
|
|
2040
|
-
// upstreamTimeoutMessage().
|
|
2041
|
-
const timedOut = SSE_UPSTREAM_TIMEOUT_PATTERN.test(sseError);
|
|
2042
|
-
const err = new Error(
|
|
2043
|
-
timedOut
|
|
2044
|
-
? upstreamTimeoutMessage(sseError, Date.now() - streamStartedAt)
|
|
2045
|
-
: sseError
|
|
2046
|
-
);
|
|
2047
|
-
err.status = timedOut ? 0 : res.status;
|
|
2048
|
-
if (timedOut) err.code = 'timeout';
|
|
2049
|
-
throw err;
|
|
2050
|
-
}
|
|
2051
|
-
|
|
2052
|
-
// A trailing '|…' that never closed (stream ended right after it, or it
|
|
2053
|
-
// was real prose all along) is real content, not an unfinished envelope
|
|
2054
|
-
// token — release it rather than dropping it silently.
|
|
2055
|
-
const strayTail = stripEnvelope.flush();
|
|
2056
|
-
if (strayTail) {
|
|
2057
|
-
cleanText += strayTail;
|
|
2058
|
-
onStream({ delta: strayTail });
|
|
2059
|
-
}
|
|
2060
|
-
|
|
2061
|
-
// An id-less fragment stream still yields usable calls, but the caller
|
|
2062
|
-
// needs *an* id to pair results back, so synthesize one.
|
|
2063
|
-
const toolCalls = [...toolCallsByIndex.entries()]
|
|
2064
|
-
.sort((a, b) => a[0] - b[0])
|
|
2065
|
-
.map(([idx, c]) => ({ ...c, id: c.id || `call_${idx}` }));
|
|
2066
|
-
|
|
2067
|
-
// The hidden chain-of-thought belongs on the RESULT, not only on the live
|
|
2068
|
-
// stream. `reasoningText` above is accumulated and forwarded to the caller's
|
|
2069
|
-
// `onReasoning`/`onStream` so the thinking can be shown while it happens —
|
|
2070
|
-
// but the resolved result carried only `content`, so every down-stream
|
|
2071
|
-
// diagnosis of "the model spent the whole budget thinking and never wrote a
|
|
2072
|
-
// word" read an empty reasoning channel on THIS lane and concluded there had
|
|
2073
|
-
// been no thinking at all.
|
|
2074
|
-
//
|
|
2075
|
-
// That is not a cosmetic loss. desktop/lib/local/engine.js decides its
|
|
2076
|
-
// reasoning-only recovery from exactly this field (`reasonedButSilent` →
|
|
2077
|
-
// `reasoningTextOf(res)`), so on byok the gate was dead code: DeepSeek
|
|
2078
|
-
// returns `finish_reason: 'stop'` with empty content and a full
|
|
2079
|
-
// `reasoning_content`, which matched neither `isTruncated` (the reason says
|
|
2080
|
-
// 'stop', not 'length') nor the reasoning retry (nothing to detect), and the
|
|
2081
|
-
// turn fell straight through to emptyTurnError — the "backend error: the
|
|
2082
|
-
// model returned no answer … max_tokens 16384" the user sees. Measured live
|
|
2083
|
-
// on byok/deepseek-v4-flash 2026-10-11.
|
|
2084
|
-
//
|
|
2085
|
-
// Kept out of `content` on purpose: deliberation is not an answer, and
|
|
2086
|
-
// folding it in would make a no-answer turn look answered to every caller's
|
|
2087
|
-
// empty-check (see the note at the `reasoningText` accumulation above).
|
|
2088
|
-
const message = { content: cleanText };
|
|
2089
|
-
if (reasoningText) message.reasoning_content = reasoningText;
|
|
2090
|
-
if (toolCalls.length) message.tool_calls = toolCalls;
|
|
2091
|
-
const result = {
|
|
2092
|
-
model: resultModel,
|
|
2093
|
-
choices: [
|
|
2094
|
-
{ message, ...(finishReason ? { finish_reason: finishReason } : {}) },
|
|
2095
|
-
],
|
|
2096
|
-
};
|
|
2097
|
-
if (usage) result.usage = usage;
|
|
2098
|
-
// DSML calls arrive as plain text, decoded by stripEnvelope rather than
|
|
2099
|
-
// accumulated by index like structured delta.tool_calls — merged into one
|
|
2100
|
-
// normalised `{ id, name, args }` list so a tool call that arrived as DSML
|
|
2101
|
-
// (no provider-native delta.tool_calls at all) is executed like any other.
|
|
2102
|
-
// engine.js's extractToolCalls() reads this field first, ahead of
|
|
2103
|
-
// message.tool_calls.
|
|
2104
|
-
const dsmlCalls = stripEnvelope.calls();
|
|
2105
|
-
if (toolCalls.length || dsmlCalls.length) {
|
|
2106
|
-
result.toolCalls = [
|
|
2107
|
-
...toolCalls.map((c) => ({ id: c.id, name: c.function.name, args: c.function.arguments })),
|
|
2108
|
-
...dsmlCalls.map((c) => ({ id: '', name: c.name, args: c.args || {} })),
|
|
2109
|
-
];
|
|
2110
|
-
}
|
|
2111
|
-
return result;
|
|
2112
|
-
}
|
|
2113
|
-
|
|
2114
|
-
/**
|
|
2115
|
-
* The read-only GETs take an optional `opts` so a host can cancel them.
|
|
2116
|
-
* Without it no non-streaming call in this module could be aborted at all:
|
|
2117
|
-
* the signal had nowhere to travel, so `boundedFetch` always fell back to its
|
|
2118
|
-
* own ceiling and a caller's cancel was silently ignored.
|
|
2119
|
-
*/
|
|
2120
|
-
async function listModels(opts) {
|
|
2121
|
-
return apiGet('/api/v1/models', null, opts);
|
|
2122
|
-
}
|
|
2123
|
-
|
|
2124
|
-
async function tokenBankBalance(opts) {
|
|
2125
|
-
return apiGet('/api/token-bank/balance', null, opts);
|
|
2126
|
-
}
|
|
2127
|
-
|
|
2128
|
-
/** Start a token-bank top-up; resolves to { url } for the payment page.
|
|
2129
|
-
* aegis1 requires a signed-in account (403/401 without a key) and rejects
|
|
2130
|
-
* an amount outside 2..1000 EUR with 400. */
|
|
2131
|
-
async function tokenBankTopup(amountEur) {
|
|
2132
|
-
return apiPost('/api/token-bank/topup', { amount_eur: amountEur });
|
|
2133
|
-
}
|
|
2134
|
-
|
|
2135
|
-
/** Start a plan checkout; resolves to { url } for Stripe's hosted page.
|
|
2136
|
-
* aegis1 `/api/billing/checkout` is deliberately public (the Stripe page
|
|
2137
|
-
* collects the email), so this works with no key configured — but answers
|
|
2138
|
-
* 503 `setup_required` while the price id is unset on the server. */
|
|
2139
|
-
async function billingCheckout() {
|
|
2140
|
-
return apiPost('/api/billing/checkout', {});
|
|
2141
|
-
}
|
|
2142
|
-
|
|
2143
|
-
async function byokStatus(opts) {
|
|
2144
|
-
return apiGet('/api/user/api-keys', null, opts);
|
|
2145
|
-
}
|
|
2146
|
-
|
|
2147
|
-
/** The server's BYOK provider catalog: which providers accept a key, which
|
|
2148
|
-
* models each unlocks, where to get the key, and the prefix a valid key
|
|
2149
|
-
* starts with. Deliberately NOT key-gated — "which key do I go get, and
|
|
2150
|
-
* what will it unlock?" is the question asked *before* an AEGIS key exists.
|
|
2151
|
-
* An AEGIS key, if present, only adds the `configured` column. */
|
|
2152
|
-
async function byokProviders(opts) {
|
|
2153
|
-
return apiGet('/api/v1/byok/providers', null, opts);
|
|
2154
|
-
}
|
|
2155
|
-
|
|
2156
|
-
/** The paged, full provider/model catalog (`/api/v1/catalog`, ETag-cached).
|
|
2157
|
-
*
|
|
2158
|
-
* Distinct from `byokProviders()`: that one answers "what will THIS account
|
|
2159
|
-
* relay accept" and is filtered to what the caller can actually reach. This
|
|
2160
|
-
* one is the whole ingested universe — every provider the server's ingest
|
|
2161
|
-
* has seen — and is what `catalog-client.js` caches as the offline fallback.
|
|
2162
|
-
*
|
|
2163
|
-
* `kind` is `models` (default) or `providers`; `params` may carry
|
|
2164
|
-
* `{limit, cursor, provider, capability, q}`. `etag` sends `If-None-Match`,
|
|
2165
|
-
* and the server answers 304 — which `apiRequest` surfaces as a rejection
|
|
2166
|
-
* like any other non-2xx, so callers revalidating should pass `allow304`.
|
|
2167
|
-
*/
|
|
2168
|
-
async function catalog(kind, params, opts) {
|
|
2169
|
-
const seg = (kind || 'models').replace(/^\/+/, '');
|
|
2170
|
-
const qs = new URLSearchParams();
|
|
2171
|
-
for (const [k, v] of Object.entries(params || {})) {
|
|
2172
|
-
if (v === undefined || v === null || v === '') continue;
|
|
2173
|
-
qs.set(k, String(v));
|
|
2174
|
-
}
|
|
2175
|
-
const query = qs.toString();
|
|
2176
|
-
const headers = opts && opts.etag
|
|
2177
|
-
? { ...authHeaders(), 'If-None-Match': opts.etag }
|
|
2178
|
-
: authHeaders();
|
|
2179
|
-
return apiGet(`/api/v1/catalog/${seg}${query ? `?${query}` : ''}`, headers, opts);
|
|
2180
|
-
}
|
|
2181
|
-
|
|
2182
|
-
async function byokSet(provider, providerApiKey) {
|
|
2183
|
-
return apiPost('/api/user/api-keys', {
|
|
2184
|
-
provider,
|
|
2185
|
-
api_key: providerApiKey || '',
|
|
2186
|
-
});
|
|
2187
|
-
}
|
|
2188
|
-
|
|
2189
|
-
async function memorySearch(query, limit) {
|
|
2190
|
-
const token = await getMemoryToken();
|
|
2191
|
-
return apiPost(
|
|
2192
|
-
'/api/memory/search',
|
|
2193
|
-
{ query: query || '', limit: limit || 5 },
|
|
2194
|
-
memoryHeaders(token)
|
|
2195
|
-
);
|
|
2196
|
-
}
|
|
2197
|
-
|
|
2198
|
-
async function memorySave(entry) {
|
|
2199
|
-
const token = await getMemoryToken();
|
|
2200
|
-
return apiPost('/api/memory/save', { entry }, memoryHeaders(token));
|
|
2201
|
-
}
|
|
2202
|
-
|
|
2203
|
-
async function memoryList(limit) {
|
|
2204
|
-
const token = await getMemoryToken();
|
|
2205
|
-
// /api/memory/list is session-cookie (dashboard) auth, unusable here.
|
|
2206
|
-
// The bearer-authenticated way to get recent entries is search with an
|
|
2207
|
-
// empty query, which the backend returns most-recent-first.
|
|
2208
|
-
return apiPost(
|
|
2209
|
-
'/api/memory/search',
|
|
2210
|
-
{ query: '', limit: limit || 10 },
|
|
2211
|
-
memoryHeaders(token)
|
|
2212
|
-
);
|
|
2213
|
-
}
|
|
2214
|
-
|
|
2215
|
-
/** Verify a bearer token (memory or API) against the backend. */
|
|
2216
|
-
async function verifyToken(token) {
|
|
2217
|
-
return apiPost(
|
|
2218
|
-
'/api/verify-token',
|
|
2219
|
-
{ token: token || '' },
|
|
2220
|
-
{
|
|
2221
|
-
'Content-Type': 'application/json',
|
|
2222
|
-
'X-AEGIS-Version': clientVersion,
|
|
2223
|
-
Authorization: `Bearer ${token}`,
|
|
2224
|
-
}
|
|
2225
|
-
);
|
|
2226
|
-
}
|
|
2227
|
-
|
|
2228
|
-
/** Activate cloud memory for the authenticated account. */
|
|
2229
|
-
async function memoryActivate(token) {
|
|
2230
|
-
const t = token || (await getMemoryToken());
|
|
2231
|
-
return apiPost('/api/memory/activate', {}, memoryHeaders(t));
|
|
2232
|
-
}
|
|
2233
|
-
|
|
2234
|
-
/** Pull memory entries updated since a timestamp (epoch ms). */
|
|
2235
|
-
async function memoryPull(since) {
|
|
2236
|
-
const token = await getMemoryToken();
|
|
2237
|
-
return apiPost(
|
|
2238
|
-
'/api/memory/pull',
|
|
2239
|
-
{ since: since || 0 },
|
|
2240
|
-
memoryHeaders(token)
|
|
2241
|
-
);
|
|
2242
|
-
}
|
|
2243
|
-
|
|
2244
|
-
/** Save a batch of memory entries in one request. */
|
|
2245
|
-
async function memorySaveBatch(entries) {
|
|
2246
|
-
const token = await getMemoryToken();
|
|
2247
|
-
return apiPost(
|
|
2248
|
-
'/api/memory/save',
|
|
2249
|
-
{ entries: entries || [] },
|
|
2250
|
-
memoryHeaders(token)
|
|
2251
|
-
);
|
|
2252
|
-
}
|
|
2253
|
-
|
|
2254
|
-
/**
|
|
2255
|
-
* Push one local conversation transcript to aegis1's conversation-sync
|
|
2256
|
-
* surface (P4.5), authenticated the same way as the memory endpoints
|
|
2257
|
-
* (memory_token, not the API key — see getMemoryToken()). The response is
|
|
2258
|
-
* returned verbatim; callers read `session_id`/`sessions` off it.
|
|
2259
|
-
*/
|
|
2260
|
-
async function conversationSyncPush(transcript) {
|
|
2261
|
-
const token = await getMemoryToken();
|
|
2262
|
-
return apiPost(
|
|
2263
|
-
'/api/conversations/sync',
|
|
2264
|
-
{
|
|
2265
|
-
session_id: transcript && transcript.session_id,
|
|
2266
|
-
title: (transcript && transcript.title) || '',
|
|
2267
|
-
messages: (transcript && transcript.messages) || [],
|
|
2268
|
-
source: (transcript && transcript.source) || 'aegis-desktop',
|
|
2269
|
-
},
|
|
2270
|
-
memoryHeaders(token)
|
|
2271
|
-
);
|
|
2272
|
-
}
|
|
2273
|
-
|
|
2274
|
-
/** Pull the account's remote conversation sessions (no transcript to push —
|
|
2275
|
-
* same endpoint, list-only request). */
|
|
2276
|
-
async function conversationSyncPull() {
|
|
2277
|
-
const token = await getMemoryToken();
|
|
2278
|
-
return apiPost('/api/conversations/sync', {}, memoryHeaders(token));
|
|
2279
|
-
}
|
|
2280
|
-
|
|
2281
|
-
/** Import a conversation transcript for later memory/training use. */
|
|
2282
|
-
async function importConversation({ messages, url, title, source } = {}) {
|
|
2283
|
-
return apiPost('/api/import', {
|
|
2284
|
-
messages: messages || [],
|
|
2285
|
-
url: url || '',
|
|
2286
|
-
title: title || '',
|
|
2287
|
-
source: source || 'aegiscode-plugin',
|
|
2288
|
-
});
|
|
2289
|
-
}
|
|
2290
|
-
|
|
2291
|
-
/**
|
|
2292
|
-
* aegis1's stored Google Drive connection for this account (`GET
|
|
2293
|
-
* /api/drive/token` — app.py's `get_drive_token`), authenticated with the
|
|
2294
|
-
* ordinary API key (the same header `authHeaders()` already sends, which
|
|
2295
|
-
* that route accepts alongside its session-cookie path). Resolves
|
|
2296
|
-
* `{connected, access_token, email}` — `connected: false` with no error
|
|
2297
|
-
* when this account has never run the browser's `/connect/drive` consent
|
|
2298
|
-
* screen (the route's 404: a real account, just nothing saved yet), since
|
|
2299
|
-
* "not yet connected" is the expected answer on every account until it
|
|
2300
|
-
* does. A 401 is a DIFFERENT fact — this key is not valid at all — so it is
|
|
2301
|
-
* left to throw rather than folded into the same "not connected" reading,
|
|
2302
|
-
* which would hide a real credential problem behind the normal first-run
|
|
2303
|
-
* state. The access token is refreshed server-side from the stored refresh
|
|
2304
|
-
* token on every call, so a caller never has to reason about expiry.
|
|
2305
|
-
*/
|
|
2306
|
-
async function driveToken() {
|
|
2307
|
-
try {
|
|
2308
|
-
return await apiGet('/api/drive/token');
|
|
2309
|
-
} catch (e) {
|
|
2310
|
-
if (e && e.status === 404) {
|
|
2311
|
-
return { connected: false, access_token: null, email: null };
|
|
2312
|
-
}
|
|
2313
|
-
throw e;
|
|
2314
|
-
}
|
|
2315
|
-
}
|
|
2316
|
-
|
|
2317
|
-
return {
|
|
2318
|
-
apiBase,
|
|
2319
|
-
get apiKey() {
|
|
2320
|
-
return apiKey;
|
|
2321
|
-
},
|
|
2322
|
-
setApiKey,
|
|
2323
|
-
get clientVersion() {
|
|
2324
|
-
return clientVersion;
|
|
2325
|
-
},
|
|
2326
|
-
get channel() {
|
|
2327
|
-
return channel;
|
|
2328
|
-
},
|
|
2329
|
-
promptUrl,
|
|
2330
|
-
verifyApiKey,
|
|
2331
|
-
registerDevice,
|
|
2332
|
-
chatCompletion,
|
|
2333
|
-
byokChatCompletion,
|
|
2334
|
-
listModels,
|
|
2335
|
-
tokenBankBalance,
|
|
2336
|
-
tokenBankTopup,
|
|
2337
|
-
billingCheckout,
|
|
2338
|
-
byokStatus,
|
|
2339
|
-
byokProviders,
|
|
2340
|
-
catalog,
|
|
2341
|
-
byokSet,
|
|
2342
|
-
getMemoryToken,
|
|
2343
|
-
memorySearch,
|
|
2344
|
-
memorySave,
|
|
2345
|
-
memoryList,
|
|
2346
|
-
verifyToken,
|
|
2347
|
-
memoryActivate,
|
|
2348
|
-
memoryPull,
|
|
2349
|
-
memorySaveBatch,
|
|
2350
|
-
conversationSyncPush,
|
|
2351
|
-
conversationSyncPull,
|
|
2352
|
-
importConversation,
|
|
2353
|
-
driveToken,
|
|
2354
|
-
randomUUID,
|
|
2355
|
-
};
|
|
2356
|
-
}
|
|
2357
|
-
|
|
2358
|
-
/** Gap between SSE chunks that counts as "the stream is dead", in ms. */
|
|
2359
|
-
const SSE_IDLE_TIMEOUT_MS = 60_000;
|
|
2360
|
-
|
|
2361
|
-
/**
|
|
2362
|
-
* Gap allowed while a pooled brain call runs its worker fan-out, in ms.
|
|
2363
|
-
*
|
|
2364
|
-
* The fan-out yields a header chunk and then says nothing until its FIRST
|
|
2365
|
-
* worker pass returns — and each worker is a full reasoning-model call at
|
|
2366
|
-
* roughly 1/(workers+1) of the effort budget, so the silent window is minutes,
|
|
2367
|
-
* not seconds. The server bounds that window itself
|
|
2368
|
-
* (``services/pool_brain.py`` ``NEXUS_BRAIN_WORKER_TIMEOUT``, default 600s) and
|
|
2369
|
-
* announces it per-response with the ``X-AEGIS-Brain`` header, so this budget
|
|
2370
|
-
* has to outlast the *server's* deadline: aborting first kills a healthy turn
|
|
2371
|
-
* the server is still running and billing.
|
|
2372
|
-
*
|
|
2373
|
-
* Raising the server's env var above ~14 minutes requires raising this too.
|
|
2374
|
-
* desktop/lib/local/engine.js mirrors the same value for the explicit
|
|
2375
|
-
* "work autonomously" path (AUTONOMOUS_IDLE_TIMEOUT_MS); the desktop test
|
|
2376
|
-
* test/autonomous-mode.test.mjs fails if either drops below the server default.
|
|
2377
|
-
*/
|
|
2378
|
-
const BRAIN_IDLE_TIMEOUT_MS = 15 * 60_000;
|
|
2379
|
-
|
|
2380
|
-
/**
|
|
2381
|
-
* Idle budget for one SSE response: the caller's override when it asked for
|
|
2382
|
-
* one, widened to the fan-out budget when the server says this response *is* a
|
|
2383
|
-
* fan-out. The header is the authoritative signal — it is set by the same code
|
|
2384
|
-
* that runs the fan-out, so a renamed brain id or a caller that forgot its
|
|
2385
|
-
* flag cannot desynchronise the two. A response with no header (an older
|
|
2386
|
-
* server, or a single-pass call) keeps the caller's budget or the 60s default.
|
|
2387
|
-
*
|
|
2388
|
-
* ── the two env knobs ───────────────────────────────────────────────────────
|
|
2389
|
-
*
|
|
2390
|
-
* `AEGIS_SSE_IDLE_TIMEOUT_MS` and `AEGIS_BRAIN_IDLE_TIMEOUT_MS` move those two
|
|
2391
|
-
* *defaults* without a code edit: the CLI is a host, not a fork, so before this
|
|
2392
|
-
* the only way to give a slow link more room — or to reproduce a stall against
|
|
2393
|
-
* a fixed wedged server — was to patch the transport. Same escape hatch the
|
|
2394
|
-
* engine gives its host cooldown (`AEGIS_HOST_COOLDOWN_MS`).
|
|
2395
|
-
*
|
|
2396
|
-
* Both are read at CALL time, not at module load, so a host that sets one after
|
|
2397
|
-
* `require()` still gets it, and one that unsets it is back on the shipped
|
|
2398
|
-
* default. A per-call `idleTimeoutMs` still outranks both: an explicit number
|
|
2399
|
-
* from the caller is a decision about *this* request, while the env var is only
|
|
2400
|
-
* a house default. See envIdleMs() for why a bad value is ignored rather than
|
|
2401
|
-
* obeyed.
|
|
2402
|
-
*/
|
|
2403
|
-
function idleBudgetFor(res, requestedMs) {
|
|
2404
|
-
// Caller override -> env knob -> shipped default.
|
|
2405
|
-
const stated = Number(requestedMs);
|
|
2406
|
-
const envDefault = envIdleMs('AEGIS_SSE_IDLE_TIMEOUT_MS');
|
|
2407
|
-
const base = stated > 0 ? stated : envDefault > 0 ? envDefault : SSE_IDLE_TIMEOUT_MS;
|
|
2408
|
-
let header = '';
|
|
2409
|
-
try {
|
|
2410
|
-
const get = res && res.headers && typeof res.headers.get === 'function' ? res.headers.get.bind(res.headers) : null;
|
|
2411
|
-
header = (get && get('X-AEGIS-Brain')) || '';
|
|
2412
|
-
} catch {
|
|
2413
|
-
header = ''; // an exotic fetch shim without headers: keep the caller's budget
|
|
2414
|
-
}
|
|
2415
|
-
// The fan-out floor is tunable for the same reason the base is — and it has
|
|
2416
|
-
// to stay a FLOOR: a server that announced workers=3 is still working, so a
|
|
2417
|
-
// smaller base must not cut it off. Raise both if the server's own
|
|
2418
|
-
// NEXUS_BRAIN_WORKER_TIMEOUT moves (test/autonomous-mode.test.mjs pins the
|
|
2419
|
-
// 600s relationship between them).
|
|
2420
|
-
const brainFloor = envIdleMs('AEGIS_BRAIN_IDLE_TIMEOUT_MS') || BRAIN_IDLE_TIMEOUT_MS;
|
|
2421
|
-
return header && String(header).trim() ? Math.max(base, brainFloor) : base;
|
|
2422
|
-
}
|
|
2423
|
-
|
|
2424
|
-
/**
|
|
2425
|
-
* Host-facing predicate: does a thrown error mean "upgrade this client"?
|
|
2426
|
-
*
|
|
2427
|
-
* Hosts catch from a shared client, and a bare `err.status === 426` check
|
|
2428
|
-
* misses the gate bodies that arrive inside an otherwise-200 stream. Matched
|
|
2429
|
-
* on the typed `code` the client sets, so a host never has to parse prose.
|
|
2430
|
-
*/
|
|
2431
|
-
function isVersionGateError(err) {
|
|
2432
|
-
return !!(err && err.code === 'version_mismatch');
|
|
2433
|
-
}
|
|
2434
|
-
|
|
2435
|
-
const api = { createClient, envVar, randomUUID, DEFAULT_API_BASE, CLIENT_VERSION, isVersionGateError, idleBudgetFor, SSE_IDLE_TIMEOUT_MS, BRAIN_IDLE_TIMEOUT_MS };
|
|
2436
|
-
|
|
2437
|
-
// Node / Electron (CommonJS): the MCP plugin and desktop shell require() this.
|
|
2438
|
-
if (typeof module !== 'undefined' && module.exports) {
|
|
2439
|
-
module.exports = api;
|
|
2440
|
-
}
|
|
2441
|
-
// Browser <script>: expose a single namespaced global for the aegis-online SPA.
|
|
2442
|
-
if (typeof window !== 'undefined') {
|
|
2443
|
-
window.AegisClient = api;
|
|
2444
|
-
}
|
|
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()),S),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 ${S/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<T;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>h?t.slice(0,h):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>h){const n=new Error(`Response from ${t} exceeded the ${h/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 y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=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 v(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 k(){if(r)return r;if(y)return y;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 y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(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&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(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 B(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=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=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([y.read(),r,o]):Promise.race([y.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){y.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 B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=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:v({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})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(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(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(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()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.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=k.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():"",y=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:C(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}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(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 y=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 S={provider:t,messages:C(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&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},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)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},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 k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();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 k()))},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);
|