aegiscode 7.0.26 → 7.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4089
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +1 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
@@ -1,3668 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * engine.js — the desktop LocalEngine registry (plan P1 §5.2). Transport-only:
10
- * it owns the provider settings/credentials and routes a chat payload to the
11
- * cloud client, the local Ollama module, or a custom OpenAI/Anthropic-
12
- * compatible endpoint. No tier/brain/routing decisions are made here — the
13
- * chosen class is the user's explicit selection.
14
- *
15
- * Since the tool-calling port it ALSO owns the agent loop (the client half of
16
- * the upstream engine's src/backend.js runProvider): every turn carries a real
17
- * system prompt (prompt.js) and the builtin tool schemas (tools.js), and when
18
- * a provider answers with tool calls the loop executes them in-process and
19
- * feeds the results back for as many rounds as the model keeps calling tools
20
- * — there is no round cap; a turn ends when the model answers with text, or
21
- * the user cancels it (cancel()/AbortController).
22
- *
23
- * Because a provider can signal "finished" with no answer attached, the two
24
- * exit paths are guarded against the empty turn (see the loop's comment):
25
- * a `finish_reason: 'length'` completion with no text is retried once with a
26
- * doubled budget, and a turn that ends with neither text nor a tool call is
27
- * re-dispatched once with `tools: []` plus a nudge so the model has to write
28
- * up what it already gathered. A turn still empty after both throws instead
29
- * of returning a blank completion for the renderer to paint "(empty
30
- * response)" over. The window stays
31
- * contextIsolated + sandboxed: this module runs in the MAIN process, so the
32
- * executor never has to be exposed to the renderer.
33
- *
34
- * Two turn-scoped resources ride along with the loop, mirroring
35
- * the upstream engine's runProvider exactly:
36
- * - a lazily-started ShellSession (shell.js) that the `exec` tool shares,
37
- * so cd/export state persists across calls within one turn instead of
38
- * each call spawning a fresh process;
39
- * - the `task` tool, executed as a nested `chat()` call on the chosen
40
- * specialist preset (agents.js) rather than a local tool — a subagent
41
- * turn with its own tool rounds, bounded by MAX_SUBAGENT_DEPTH so a
42
- * delegation chain can't recurse forever.
43
- *
44
- * Pure Node + dependency-injected (aegis client, settings store, ollama,
45
- * providers, optionally tools/prompt) so it unit-tests without Electron.
46
- */
47
-
48
- const { randomUUID } = require('node:crypto');
49
- const os = require('node:os');
50
-
51
- const toolsModule = require('./tools.js');
52
- const attachmentsModule = require('./attachments.js');
53
- const { flattenContent } = attachmentsModule;
54
- const promptModule = require('./prompt.js');
55
- const localTransport = require('./local.js');
56
- const { ShellSession } = require('./shell.js');
57
- const { planExec } = require('./exec-plan.js');
58
- // The Claude Code Pro class' transport (the user's own subscription, spent
59
- // through the `claude` CLI). Owned by one module — the way local.js owns the
60
- // loopback transport — so the argv builder, the credential read and the
61
- // stream-json parser have exactly one implementation and one test surface.
62
- const claudePro = require('./claude-pro.js');
63
- const { agentSystemPrompt, agentRoleLabel } = require('./agents.js');
64
- // Cooperative working-tree sharing (see each module's header). The lock
65
- // serialises two hosts that start a turn on one checkout close together; the
66
- // guard is the load-bearing half — it refuses a tree-wide git operation while
67
- // another session's uncommitted work is present, which is the operation that
68
- // destroyed a peer's file for real. Both live beside the engine because the
69
- // CLI vendors this directory wholesale (cli/scripts/predist.mjs), so the GUI
70
- // and the terminal get one implementation rather than two that drift.
71
- const { beginTurnGuard, recordWrite, blocksDestructive } = require('./turn-guard.js');
72
- const { acquireWorktreeLock, releaseWorktreeLock } = require('./worktree-lock.js');
73
- // The ÆGIS covenant (ÆL/1), decoded lazily and bound into the tool chokepoint
74
- // below. Pure Node, no I/O at require time — a missing seal degrades rather
75
- // than breaking the engine at load (see lib/local/covenant.js).
76
- const covenant = require('./covenant.js');
77
-
78
- // `~/.aegiscode/.env` — the shared key file both hosts load at startup, so
79
- // "put your key in the env file" is the whole setup instruction for either app.
80
- // Optional by design, and resolved the same two ways this repo resolves every
81
- // shared module: repo-relative in a checkout AND in the CLI's mirrored vendor
82
- // tree (cli/vendor/client/env-file.js), then the staged app-dir copy a packaged
83
- // desktop build carries. Absent in all three, `envFile` stays null and byok
84
- // reads the encrypted store alone — exactly the behaviour before this file.
85
- let envFile = null;
86
- try {
87
- envFile = require('../../../client/env-file.js');
88
- } catch {
89
- try {
90
- envFile = require('../../vendor/env-file.js');
91
- } catch {
92
- envFile = null;
93
- }
94
- }
95
-
96
- // The ONE platform module (client/platform.js), resolved the same two ways, for
97
- // `desktopDir()` — the environment preamble names the user's REAL Desktop so a
98
- // model asked to put a file there stops guessing `~/Desktop`, which is wrong
99
- // under OneDrive redirection on Windows and on any localised Linux session.
100
- let platformLib = null;
101
- try {
102
- platformLib = require('../../../client/platform.js');
103
- } catch {
104
- try {
105
- platformLib = require('../../vendor/platform.js');
106
- } catch {
107
- platformLib = null;
108
- }
109
- }
110
-
111
- /**
112
- * The module that decides where this install's data directory IS
113
- * (`$AEGISCODE_HOME`, else `~/.aegiscode`) — the same two-layout resolution as
114
- * `platformLib` above, and for the same reason: the environment block must
115
- * state the path this machine actually writes, not a path this file guessed.
116
- *
117
- * Reported live (DeepSeek, Windows, 2026-10-04): asked to check the AEGIS data
118
- * directory, the model produced `C:\Users\Dator.aegiscode` — the home directory
119
- * with the separator EATEN — and then ran
120
- * `Get-ChildItem -Filter aegis -Recurse -Depth 2` over the whole profile when
121
- * that path came back empty. Nothing in the prompt had ever named the real
122
- * directory, so building it from the home directory was the only move it had.
123
- */
124
- let credentialsLib = null;
125
- try {
126
- credentialsLib = require('../../../client/credentials.js');
127
- } catch {
128
- try {
129
- credentialsLib = require('../../vendor/credentials.js');
130
- } catch {
131
- credentialsLib = null;
132
- }
133
- }
134
-
135
- /**
136
- * The environment facts the model needs to stop asking which OS it is on.
137
- *
138
- * Module scope, not a closure inside `createLocalEngine`, because there are now
139
- * TWO hosts that must state these facts the same way: the desktop engine (whose
140
- * `envFor` below is this function with the host's own `env` bag) and the CLI
141
- * (`cli/src/app.js`), which had no environment block at all. A second copy over
142
- * there is precisely how the two hosts would drift — the Windows report that
143
- * started this ("it still writes to /home/you/... on my PC") was the CLI path,
144
- * where a Linux-shaped persona was built from `process.platform` and nothing
145
- * else.
146
- *
147
- * Everything is best-effort: a missing field is simply omitted, never guessed.
148
- *
149
- * base the host's own env bag ({ platform, homedir, cwd, … } or {})
150
- * supplied a per-turn override bag (payload.env; wins key by key)
151
- * payload the turn payload, for `model`
152
- */
153
- /**
154
- * Resolve a tool call's path arguments, tolerating an injected tools module that
155
- * does not implement it.
156
- *
157
- * `createLocalEngine({ tools })` accepts a PARTIAL tool layer — the engine tests
158
- * inject `{ MUTATING_TOOLS, executeTool, toolsFor }` and nothing else — so
159
- * calling `T.normalizeArgs` unconditionally turns every such caller into a
160
- * TypeError. The injected module's own implementation wins when it has one; the
161
- * real tools.js is the fallback, because path resolution is a property of the
162
- * MACHINE (client/platform.js) and not of which executors a caller supplied.
163
- */
164
- function normalizeToolArgs(T, name, args, ctx) {
165
- const fn =
166
- (T && typeof T.normalizeArgs === 'function' && T.normalizeArgs) ||
167
- (typeof toolsModule.normalizeArgs === 'function' && toolsModule.normalizeArgs) ||
168
- null;
169
- if (!fn) return { ok: true, args: args && typeof args === 'object' ? args : {}, error: null };
170
- return fn(name, args, ctx);
171
- }
172
-
173
- /**
174
- * Is `dir` inside a git work tree? Walks up the way git itself does, so a turn
175
- * running in a subdirectory of a repo is still told it is one.
176
- *
177
- * Returns `'git'`, `''` (definitely not a repo), or `null` when the probe could
178
- * not answer — the caller omits the line rather than asserting "not a repo",
179
- * because a wrong negative is exactly the kind of fact a model will act on.
180
- */
181
- function detectVcs(dir) {
182
- if (!dir) return null;
183
- try {
184
- const fs = require('node:fs');
185
- const path = require('node:path');
186
- let probe = path.resolve(String(dir));
187
- for (let i = 0; i < 8; i += 1) {
188
- if (fs.existsSync(path.join(probe, '.git'))) return 'git';
189
- const up = path.dirname(probe);
190
- if (up === probe) break;
191
- probe = up;
192
- }
193
- return '';
194
- } catch {
195
- return null;
196
- }
197
- }
198
-
199
- function hostEnv(base = {}, supplied = {}, payload = null) {
200
- const b = base || {};
201
- const s = supplied || {};
202
- const pick = (key, value) => (s[key] != null ? s[key] : value);
203
- let homedir = b.homedir;
204
- let cwd = b.cwd;
205
- try {
206
- if (!homedir) homedir = os.homedir();
207
- if (!cwd) cwd = process.cwd();
208
- } catch {
209
- /* keep whatever we have */
210
- }
211
- // The shell the `exec` tool really runs in, from the module that decides it
212
- // (shell.js resolveSessionShell) rather than a second guess here: on win32
213
- // that is PowerShell, and a model told nothing reaches for `ls`/`cat`/`grep`
214
- // — commands that do not exist there. Best-effort; a failed probe simply
215
- // omits the line.
216
- let shellName = b.shell;
217
- let shellKind = b.shellKind;
218
- try {
219
- if (!shellName || !shellKind) {
220
- const spec = require('./shell.js').resolveSessionShell();
221
- shellName = shellName || spec.cmd;
222
- shellKind = shellKind || spec.kind;
223
- }
224
- } catch {
225
- /* no shell line */
226
- }
227
- let desktopdir = b.desktopdir;
228
- try {
229
- if (!desktopdir && platformLib) desktopdir = platformLib.desktopDir();
230
- } catch {
231
- /* no desktop line */
232
- }
233
- // The data directory (`$AEGISCODE_HOME`, else `~/.aegiscode`), read from the
234
- // module every host already resolves it through. Stated rather than left to
235
- // be built from `homedir`: a model that concatenates home + ".aegiscode"
236
- // itself is one dropped separator away from `Dator.aegiscode`, a path that
237
- // does not exist, and it has no way to tell the difference from the answer.
238
- let dataDir = b.dataDir;
239
- try {
240
- if (!dataDir && credentialsLib) dataDir = credentialsLib.aegisHome();
241
- } catch {
242
- /* no data-directory line */
243
- }
244
- // The user's own locale, from the module that already resolves home and
245
- // Desktop (client/platform.js appLocale). Stated for the same reason the
246
- // Desktop path is: it is a fact about THIS machine that the model cannot
247
- // derive from `platform: win32`, and until it is stated the model mirrors
248
- // whatever language the message arrived in and defaults to the prompt's
249
- // English otherwise — so a Swedish user had no way to stop being greeted in
250
- // English, and a one-word request ("städa") had no language to be read in.
251
- // Best-effort: a failed probe simply omits the line.
252
- let locale = b.locale;
253
- let localeName = b.localeName;
254
- try {
255
- if (!locale && platformLib && typeof platformLib.appLocale === 'function') {
256
- locale = platformLib.appLocale();
257
- }
258
- if (locale && !localeName && platformLib && typeof platformLib.languageName === 'function') {
259
- localeName = platformLib.languageName(locale);
260
- }
261
- } catch {
262
- /* no locale line */
263
- }
264
- return {
265
- platform: pick('platform', b.platform || process.platform),
266
- arch: pick('arch', b.arch || process.arch),
267
- homedir: pick('homedir', homedir),
268
- desktopdir: pick('desktopdir', desktopdir),
269
- dataDir: pick('dataDir', dataDir),
270
- locale: pick('locale', locale),
271
- localeName: pick('localeName', localeName),
272
- // Durable language EVIDENCE, which is a different thing from `locale` and is
273
- // passed through rather than probed: `locale` is where the machine is set
274
- // up, this is what the holder's own saved writing is in. A host that has
275
- // folded the avatar profile (lib/avatar/profile.js foldLanguage, which
276
- // already emits "writes durably in Swedish (sv), so reply in Swedish unless
277
- // asked otherwise") hands the facets in here; a host with no avatar passes
278
- // nothing and gets the exact pre-locale turn. Shapes: a `{ code, name }`,
279
- // a `{ key, value }` facet, or a bare string.
280
- languages: pick('languages', b.languages),
281
- cwd: pick('cwd', cwd),
282
- // Whether the turn's directory is a git work tree, probed once per turn.
283
- // Measured reason: the work rules order the model to check prior work with
284
- // `git log` before it starts, and a benchmark workspace (a temp dir holding
285
- // three files) is NOT a repo. On every task the model dutifully spent its
286
- // second round on `cd … && git log`, paid a failed exec, and carried the
287
- // error text into every later round's prompt — one wasted round in seven,
288
- // and a bigger prefix for the rest. The host already knew; this states it
289
- // so the rule can say "skip the sources the workspace does not have" and
290
- // mean something the model can act on without guessing.
291
- vcs: pick('vcs', b.vcs != null ? b.vcs : detectVcs(cwd)),
292
- shell: pick('shell', shellName),
293
- shellKind: pick('shellKind', shellKind),
294
- roots: pick('roots', b.roots),
295
- appVersion: pick('appVersion', b.appVersion),
296
- model: pick('model', payload && payload.model),
297
- };
298
- }
299
-
300
- /**
301
- * The shared pooled-brain selection rule (`client/brain-catalog.js`), resolved
302
- * the same two ways as every other shared module: repo-relative from a source
303
- * checkout, and this app's own staged tree (`desktop/vendor/brain-catalog.js`,
304
- * flattened by scripts/predist.mjs because a packaged app cannot reach outside
305
- * its own directory). The CLI resolves the same file its own way, through
306
- * `cli/src/sharedpaths.js`. Both hosts must agree on which entry stands for the
307
- * pool, so there is deliberately no fallback implementation here — a silently
308
- * divergent local copy is the exact bug this module removes. When neither
309
- * layout has it, require() throws at load time naming the file, rather than the
310
- * host quietly offering a different model list than its sibling.
311
- */
312
- function requireSharedBrain() {
313
- const candidates = [
314
- () => require('../../../client/brain-catalog.js'),
315
- () => require('../../vendor/brain-catalog.js'),
316
- ];
317
- let last = null;
318
- for (const load of candidates) {
319
- try {
320
- return load();
321
- } catch (err) {
322
- last = err;
323
- }
324
- }
325
- throw last;
326
- }
327
-
328
- /**
329
- * The shared BYOK model additions (`client/byok-catalog.js`), resolved exactly
330
- * the two ways above and for the same reason: the CLI vendors THIS file
331
- * (cli/scripts/predist.mjs) and requires the same module through
332
- * `cli/src/sharedpaths.js`, so a copy-per-host here is how the terminal and the
333
- * window would come to offer one account two different provider model lists —
334
- * the defect class this repo keeps paying for.
335
- *
336
- * The module is pure and returns a NEW array, so a caller may apply it to a
337
- * payload it did not build. It never invents a provider: a provider absent from
338
- * the server's catalog stays absent, because a row that accepts a vendor key
339
- * must correspond to a slug the relay actually takes.
340
- */
341
- function requireSharedByokCatalog() {
342
- const candidates = [
343
- () => require('../../../client/byok-catalog.js'),
344
- () => require('../../vendor/byok-catalog.js'),
345
- ];
346
- let last = null;
347
- for (const load of candidates) {
348
- try {
349
- return load();
350
- } catch (err) {
351
- last = err;
352
- }
353
- }
354
- throw last;
355
- }
356
-
357
- /**
358
- * The models the USER declares (`client/user-models.js`) — resolved exactly as
359
- * the two modules above, and required here for the same reason: it is the ONE
360
- * store the CLI's `/model-add` and this window's Settings row both write, so a
361
- * model added in the terminal is a row in this picker and vice versa. A second
362
- * implementation would be a second file, and "the two hosts show one account
363
- * two different model lists" is the defect class this resolution rule exists
364
- * to end.
365
- *
366
- * Unlike the two catalog modules this one touches the disk (it reads
367
- * `$AEGISCODE_HOME/models.json`), which is why it is required through the
368
- * staged-tree fallback like any other shared module — the packaged app has no
369
- * `client/` beside it.
370
- */
371
- function requireSharedUserModels() {
372
- const candidates = [
373
- () => require('../../../client/user-models.js'),
374
- () => require('../../vendor/user-models.js'),
375
- ];
376
- let last = null;
377
- for (const load of candidates) {
378
- try {
379
- return load();
380
- } catch (err) {
381
- last = err;
382
- }
383
- }
384
- throw last;
385
- }
386
-
387
- /**
388
- * The server's own catalog, cached on disk (`client/catalog-client.js`) — the
389
- * layer that adds the ids the server publishes but the shipped list does not
390
- * carry. Resolved exactly the two ways above, and for the same reason: the CLI
391
- * requires this one module too (cli/src/commands.js, through sharedpaths.js),
392
- * so the terminal and the window cannot offer one account two different id
393
- * lists. Layered between the shipped additions and the user's own overlay.
394
- *
395
- * `withCatalog(providers, undefined)` reads the cache lazily and never throws:
396
- * a missing cache means "no extra ids", not a failed provider list.
397
- */
398
- function requireSharedCatalogClient() {
399
- const candidates = [
400
- () => require('../../../client/catalog-client.js'),
401
- () => require('../../vendor/catalog-client.js'),
402
- ];
403
- let last = null;
404
- for (const load of candidates) {
405
- try {
406
- return load();
407
- } catch (err) {
408
- last = err;
409
- }
410
- }
411
- throw last;
412
- }
413
-
414
- /**
415
- * The vendor-list helper (`client/model-discovery.js`) — the module that asks a
416
- * provider's OWN API which model ids exist, so a desktop user is not asked to
417
- * recall an id the vendor publishes at a URL. Same resolution rule as the two
418
- * catalog modules above, for the same reason: the CLI's `/model-discover` reads
419
- * this one module too, so the terminal and the window cannot answer "what does
420
- * this key reach" differently.
421
- *
422
- * It does no I/O at load time (no key store, no network), so requiring it here
423
- * costs the window nothing until a user asks for a list.
424
- */
425
- function requireSharedModelDiscovery() {
426
- const candidates = [
427
- () => require('../../../client/model-discovery.js'),
428
- () => require('../../vendor/model-discovery.js'),
429
- ];
430
- let last = null;
431
- for (const load of candidates) {
432
- try {
433
- return load();
434
- } catch (err) {
435
- last = err;
436
- }
437
- }
438
- throw last;
439
- }
440
-
441
- /**
442
- * How long a turn waits for the working-tree lock before running anyway.
443
- *
444
- * Short on purpose. This engine serves interactive hosts — a desktop window
445
- * and a terminal — where stalling for the lock's own 11-minute default would
446
- * be a worse failure than contending: the user is watching a spinner. So the
447
- * lock is best-effort mutual exclusion for turns that start near-simultaneously
448
- * (the common overlap), and the turn guard covers everything after that. A
449
- * non-interactive caller that can afford to queue should pass
450
- * `payload.worktreeWaitMs` with the long DEFAULT_WORKTREE_WAIT_MS instead.
451
- */
452
- const WORKTREE_LOCK_WAIT_MS = 1500;
453
-
454
- /**
455
- * Depth at which the task tool stops being offered. The main chat (depth 0)
456
- * and subagents down to depth MAX_SUBAGENT_DEPTH - 1 can all delegate, so
457
- * legitimate hierarchical work (scan -> review -> patch, etc.) has room to
458
- * nest without hitting a wall. Past that the tool is dropped, hard-cutting a
459
- * runaway chain instead of letting it recurse unbounded.
460
- */
461
- const MAX_SUBAGENT_DEPTH = 4;
462
-
463
- // The four shipping classes — kept in lockstep with the CLI's HOST_CLASSES
464
- // (cli/src/engine.js). 'anthropic'/'openai'/'deepseek' still appear in this
465
- // file as BYOK *provider* ids: upstream names, never model classes.
466
- //
467
- // aegis — pooled relay; the account key pays the pool's margin.
468
- // byok — relayed with the caller's provider key; AEGIS bills a handling fee.
469
- // local — a model on hardware the user owns, reached over loopback. Bills
470
- // nobody because there is no vendor: the compute was already bought.
471
- // Fenced by local.js `remoteRefusal()` — a remote URL here would be
472
- // an unpaid turn, which is why that gate exists and fails closed.
473
- // pro — the user's OWN Claude Code Pro/Max subscription, spent by spawning
474
- // the `claude` CLI. It reaches no AEGIS endpoint and no vendor API:
475
- // no baseURL, no key row, no relay, so there is nothing for AEGIS to
476
- // bill and nothing to meter. See claude-pro.js for why the argv is
477
- // derived from one/src/child.js rather than written there.
478
- const CLASSES = [
479
- { class: 'aegis', label: 'Aegis Cloud', kind: 'cloud' },
480
- { class: 'byok', label: 'Bring your own key', kind: 'cloud' },
481
- { class: 'local', label: 'Local model', kind: 'local' },
482
- { class: 'pro', label: 'Claude Code Pro', kind: 'subscription' },
483
- ];
484
-
485
- /** Local settings namespace for one BYOK provider's key. The `byok:` prefix
486
- * keeps a provider key (e.g. 'anthropic' the *provider*) in its own row out
487
- * of every model class's row in the same store — one flat 'byok' row could
488
- * not hold two providers' keys at once. Named once here because two callers
489
- * now need to take the provider back OUT of a row name. */
490
- const BYOK_NAMESPACE_PREFIX = 'byok:';
491
-
492
- function byokNamespace(providerId) {
493
- return `${BYOK_NAMESPACE_PREFIX}${providerId}`;
494
- }
495
-
496
- /** Split a byok model id ("anthropic:claude-sonnet-5") into its provider and
497
- * bare model parts. `modelId` may itself contain ':' (none of today's
498
- * catalog ids do, but nothing guarantees that), so only the FIRST segment is
499
- * the provider — the rest re-joins as the model. */
500
- function splitByokModel(compound) {
501
- const s = typeof compound === 'string' ? compound : '';
502
- const i = s.indexOf(':');
503
- if (i < 0) return { provider: '', model: s };
504
- return { provider: s.slice(0, i), model: s.slice(i + 1) };
505
- }
506
-
507
- /**
508
- * The BYOK key an environment variable supplies for a provider, if any — from
509
- * `~/.aegiscode/.env` (loaded into the environment at host startup via
510
- * `client/env-file.js`) or an explicit shell export. '' when neither has one,
511
- * which leaves the encrypted store the only source, exactly as before.
512
- *
513
- * Read HERE and not inside lib/settings.js on purpose. The store's contract is
514
- * "what I persisted": its tests assert `configured === false` after a
515
- * remove(), and a store that silently answered from the environment would break
516
- * that — and would make a provider look configured to code that never learns
517
- * where the key came from. The resolution chain (store first, environment
518
- * second) belongs to the class that spends the key, which is this one.
519
- */
520
- /**
521
- * The env-file's own answer for a provider's key, as a RECORD.
522
- *
523
- * `providerKeyFromEnv` below deliberately answers with the key alone, which is
524
- * what every spend site wants. Anything that has to EXPLAIN a keyless row wants
525
- * the record instead, because the two reasons a provider has no env key look
526
- * nothing alike to the user:
527
- *
528
- * absent nothing supplied one — "paste a key".
529
- * refused the value supplied cannot be a credential at all. Measured on
530
- * this machine 2026-10-14: a shell `ANTHROPIC_API_KEY=he` (2
531
- * characters, a paste that lost its payload) made every
532
- * `anthropic:*` row read as configured and every turn fail
533
- * upstream with `{"type":"authentication_error","message":
534
- * "Invalid bearer token"}`.
535
- *
536
- * The second case is the one that sends a user hunting for a new key while the
537
- * broken two characters sit in the file they are editing, so the reason is
538
- * carried rather than dropped. client/env-file.js owns the floor and the wording
539
- * (its `credentialLooksUsable`); this only reads it.
540
- *
541
- * @returns {{key: string, env: string, rejected: string|null}}
542
- */
543
- function providerKeyRecord(provider) {
544
- const empty = { key: '', env: '', rejected: null };
545
- if (!envFile || typeof envFile.providerKeyFromEnv !== 'function') return empty;
546
- try {
547
- const rec = envFile.providerKeyFromEnv(provider) || empty;
548
- return {
549
- key: typeof rec.key === 'string' ? rec.key : '',
550
- env: typeof rec.env === 'string' ? rec.env : '',
551
- rejected: typeof rec.rejected === 'string' && rec.rejected ? rec.rejected : null,
552
- };
553
- } catch {
554
- // A host whose env module predates the record (or whose file is unreadable)
555
- // degrades to "no key", which is exactly what the string accessor does.
556
- return empty;
557
- }
558
- }
559
-
560
- function providerKeyFromEnv(provider) {
561
- if (!envFile || typeof envFile.providerKeyFromEnv !== 'function') return '';
562
- try {
563
- return envFile.providerKeyFromEnv(provider).key || '';
564
- } catch {
565
- return '';
566
- }
567
- }
568
-
569
- /**
570
- * Mirrors the upstream engine's src/backend.js DEEPSEEK_REASONING_MODEL_RE +
571
- * EFFORT_TOKEN_BUDGET verbatim. DeepSeek's reasoning models (deepseek-flash,
572
- * i.e. "Flash 4.1", deepseek-v4-pro, the deprecated deepseek-reasoner, and the
573
- * legacy v4-flash/v4.1-flash aliases some configs still carry) spend part of
574
- * the budget on hidden chain-of-thought before ever emitting visible content —
575
- * DeepSeek counts reasoning tokens against the same budget as content. Under
576
- * the renderer's removed 4k dropdown default, any non-trivial question could
577
- * burn the whole budget reasoning and finish with empty content: no error, no
578
- * tool calls, just a turn that "completes" with nothing to show for it (the
579
- * empty-response bug). A user pointing the Custom OpenAI-compatible class
580
- * straight at DeepSeek's API hits exactly this, so the request is sized by the
581
- * same effort budget the upstream engine uses for its own direct DeepSeek calls.
582
- *
583
- * desktop/renderer/budget.js carries the renderer's copy of these two
584
- * constants plus budgetFor() below; test/budget.test.mjs requires both and
585
- * asserts they agree, so the mirror cannot drift silently.
586
- */
587
- const DEEPSEEK_REASONING_MODEL_RE = /^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/;
588
- /**
589
- * Effort rung -> the output ceiling that rung buys.
590
- *
591
- * `max` is a rung of this ladder now. It was reachable on the wire (see
592
- * DEEPSEEK_EFFORT_EXTRA) but absent here, so a call that asked for `max` was
593
- * sized off `undefined` — the depth was bought and the ceiling was not, which
594
- * is the one combination that spends deliberation against a budget nobody
595
- * chose. It carries `high`'s ceiling rather than a larger one: the extra depth
596
- * is the vendor's own reasoning control, and that deliberation is billed
597
- * against this same number, so raising it here would charge twice for one
598
- * decision.
599
- */
600
- const EFFORT_TOKEN_BUDGET = { low: 8192, medium: 16384, high: 32768, max: 32768 };
601
-
602
- /**
603
- * DeepSeek native reasoning level per config rung.
604
- *
605
- * The field is `effort`, NOT `reasoning_effort`. Verified live 2026-10-21
606
- * against the surface this client actually reaches — the relay's
607
- * `https://api.deepseek.com/anthropic` transport — by measuring output tokens
608
- * over interleaved paired samples (n=12) against an absent-field baseline:
609
- *
610
- * absent 818 · low 772 · medium 836 · high 818 · max 1494
611
- *
612
- * Only `max` separates from sending nothing. `GET /models` reports
613
- * `supported_levels: ["low","high","max"]`, default `high`, on both live ids
614
- * (`deepseek-flash`, `deepseek-v4-pro`) — so `medium` is not a level these
615
- * models have. It passes the deserializer (unknown values *do* 422 with the
616
- * enum, so validation is real) and is then absorbed into the default, which is
617
- * this codebase's worst failure mode: a 200, nothing surfaced, and the model
618
- * thinking at a depth nobody chose.
619
- *
620
- * What the earlier version of this comment asserted — that `reasoning_effort`
621
- * binds and `effort` is ignored — was measured on the vendor's OpenAI-shaped
622
- * `/chat/completions`, a surface this client never reaches, and it led to the
623
- * knob being dead end-to-end: aegis1 forwards `reasoning_effort` only for
624
- * BYOK_REASONING_EFFORT_PROVIDERS (openai/groq/gemini/grok — deepseek is
625
- * absent), so the field was dropped at the relay. The `effort` channel is the
626
- * one aegis1 gates on `provider_id == "deepseek"` (app.py) and that the
627
- * Anthropic adapter nests as `output_config.effort`; it is the only channel
628
- * that reaches the vendor, and the only one that measurably binds.
629
- *
630
- * The map folds `medium` upward for the same reason the Gemini row does: the
631
- * vendor has no such level, and a rung that 200s while doing nothing is worse
632
- * than one that says what it does. `max` is deliberately NOT reachable — it is
633
- * not a rung of this knob, and mapping the default rung onto it would silently
634
- * multiply reasoning spend on every turn nobody asked to deepen.
635
- * `max_tokens` (EFFORT_TOKEN_BUDGET) still scales as the output ceiling, since
636
- * hidden chain-of-thought shares that budget on DeepSeek.
637
- *
638
- * desktop/renderer/budget.js carries the renderer's copy; test/budget.test.mjs
639
- * compares the two tables, so the mirror cannot drift silently.
640
- */
641
- const DEEPSEEK_EFFORT = { low: 'low', medium: 'high', high: 'high' };
642
- /**
643
- * The one rung that is NOT part of the three-rung knob above.
644
- *
645
- * `GET /models` reports `supported_levels: ["low","high","max"]` and the paired
646
- * measurement (`absent 818 · low 772 · medium 836 · high 818 · max 1494`) shows
647
- * `max` is the only level that separates from sending nothing. It is kept out
648
- * of DEEPSEEK_EFFORT on purpose: that table is mirrored byte-for-byte by
649
- * desktop/renderer/budget.js, where `max` is not a rung of the user's dropdown
650
- * and must not become one. A caller that explicitly asks for `max` gets it.
651
- */
652
- const DEEPSEEK_EFFORT_EXTRA = { max: 'max' };
653
-
654
- /**
655
- * Per-family effort translation, mirroring the upstream engine's
656
- * EFFORT_DIALECTS. The knob is one rung here (low|medium|high) but it is NOT
657
- * portable across vendors, and passing it through untranslated is a correctness
658
- * bug rather than a no-op: Groq 400s any level outside a model's supported set,
659
- * and Gemini 3 fails on `medium` outright while low/high succeed. So each
660
- * family states its own wire field and level map, and a family with no such
661
- * field gets NOTHING — an unknown body field either 400s or is silently
662
- * dropped, and both are worse than stating no opinion.
663
- *
664
- * xAI's `*-non-reasoning` row is left alone entirely: the model exists to not
665
- * reason, and sending it an effort field is precisely the request the user
666
- * picked that row to avoid. grok-4.20 and gemini-2.0 stay bare too — no
667
- * documented level field exists for them, and guessing on a strict validator
668
- * is a 400 rather than an upgrade.
669
- */
670
- const EFFORT_IDENTITY = { low: 'low', medium: 'medium', high: 'high' };
671
- const EFFORT_INERT_RE = /non-reasoning/i;
672
- const EFFORT_DIALECTS = [
673
- { provider: 'deepseek', re: DEEPSEEK_REASONING_MODEL_RE, field: 'effort', map: DEEPSEEK_EFFORT, extra: DEEPSEEK_EFFORT_EXTRA },
674
- { provider: 'openai', re: /^(gpt-5|o[0-9])/i, field: 'reasoning_effort', map: EFFORT_IDENTITY },
675
- { provider: 'groq', re: /^(openai\/gpt-oss|qwen\/qwen3)/i, field: 'reasoning_effort', map: EFFORT_IDENTITY },
676
- { provider: 'xai', re: /^grok-(4\.[5-9]|[5-9])/, field: 'reasoning_effort', map: EFFORT_IDENTITY },
677
- { provider: 'google', re: /^gemini-(2\.5|3|[4-9])/, field: 'reasoning_effort', map: { ...EFFORT_IDENTITY, medium: 'high' } },
678
- ];
679
-
680
- /**
681
- * Idle-stream budget for a pooled brain call ("work autonomously"). The
682
- * generic watchdog in vendor/aegis.js kills a stream that goes 60s without a
683
- * byte — right default for one provider call answering, wrong for a worker
684
- * fan-out: pool_brain yields a header chunk, then stays silent until the
685
- * FIRST worker pass *returns*, and each worker is a full reasoning-model call
686
- * at roughly 1/(workers+1) of the effort budget. At high effort, 3 workers,
687
- * that is a multi-thousand-token reasoning pass per worker — easily past a
688
- * minute. Timing out there aborts a perfectly healthy autonomous turn
689
- * mid-flight, after the server has already run and billed every worker.
690
- *
691
- * 15 minutes deliberately outlasts the server's OWN ceiling for that window
692
- * (aegis1 services/pool_brain.py: NEXUS_BRAIN_WORKER_TIMEOUT, default 600s),
693
- * because aborting first leaves the server running and billing a fan-out
694
- * nobody will ever see. Raising that env var past ~14 minutes means raising
695
- * this constant too; the shared client applies the same budget from the
696
- * server's X-AEGIS-Brain response header (see client/aegis.js idleBudgetFor),
697
- * which is what covers a fan-out the caller did not flag — test/
698
- * autonomous-mode.test.mjs pins both halves.
699
- */
700
- const AUTONOMOUS_IDLE_TIMEOUT_MS = 15 * 60_000;
701
-
702
- /**
703
- * The budget a request travels with, resolved from EXACTLY ONE authority per
704
- * call — the engine-side half of the rule desktop/renderer/budget.js mirrors
705
- * and test/budget.test.mjs compares the two halves of, so neither can drift.
706
- *
707
- * 1. a caller-stated number IS the budget and is returned verbatim. It is a
708
- * deliberate liability ceiling (aegis1 pass_budgets honours it downward:
709
- * total = min(ladder, max_tokens x passes)) and no rung may raise it — the
710
- * old `Math.max(stated, EFFORT_TOKEN_BUDGET[eff])` form did exactly that,
711
- * so a caller asking for 1024 silently ran on 32768.
712
- * 2. with nothing stated, a model that reasons against its own output budget
713
- * (DeepSeek bills hidden chain-of-thought against the SAME budget as the
714
- * answer) gets the Effort rung. This is why the renderer's
715
- * max-tokens dropdown was removed rather than fixed: at its 4k default a
716
- * reasoning model spent the entire budget thinking and finished empty —
717
- * no error, no tool call, just a "completed" turn with nothing in it.
718
- * 3. otherwise `undefined` — no `max_tokens` goes on the wire and the
719
- * provider's own output limit governs. The transport used to fill this
720
- * gap with an invented 4096 default, which is the defect in (2).
721
- *
722
- * Truncated and empty turns are still handled where they belong — the
723
- * doubled-budget retry plus emptyTurnError — rather than by inflating the
724
- * caller's ceiling up front.
725
- */
726
- function reasoningBudget(model, maxTokens, effort) {
727
- const stated = Number(maxTokens);
728
- if (Number.isFinite(stated) && stated > 0) return stated;
729
- if (DEEPSEEK_REASONING_MODEL_RE.test(String(model || ''))) {
730
- const eff = effort === 'low' || effort === 'medium' || effort === 'max' ? effort : 'high';
731
- return EFFORT_TOKEN_BUDGET[eff];
732
- }
733
- return undefined;
734
- }
735
-
736
- /**
737
- * The native effort verdict for this provider+model: `{ field, level }`, or
738
- * `undefined` when the family has no effort knob. `undefined` means "say
739
- * nothing", never "send a default" — inventing a level is how the knob silently
740
- * overrides the vendor's own default. Supersedes the DeepSeek-only
741
- * deepseekEffort() it replaces: same DeepSeek mapping, now stated for every
742
- * family that has one instead of only the one that used to be wired.
743
- */
744
- function nativeEffort(provider, model, effort) {
745
- const m = String(model || '');
746
- if (EFFORT_INERT_RE.test(m)) return undefined;
747
- // An EXPLICIT `null` means "send no effort field" — the vendor's own default.
748
- // It is kept distinct from `undefined`, which every existing caller means as
749
- // "unspecified" and which stays on the high rung below. Collapsing the two
750
- // is what made a benchmark's `--effort default` arm silently run at `high`:
751
- // the arm ran, reported `default`, and measured nothing.
752
- if (effort === null) return undefined;
753
- // `max` is its own rung and must not be folded into `high`: the measurement
754
- // quoted above is `absent 818 · low 772 · medium 836 · high 818 · max 1494`,
755
- // so collapsing `max` to `high` left the ONLY level that separates from
756
- // sending nothing unreachable from a caller. But it is not portable either —
757
- // `max` is not a level most families define, and sending it to a strict
758
- // validator is a 400 — so it is carried here and filtered per dialect below.
759
- const eff = effort === 'low' || effort === 'medium' ? effort : effort === 'max' ? 'max' : 'high';
760
- for (const d of EFFORT_DIALECTS) {
761
- if (d.provider === provider && d.re.test(m)) {
762
- // A dialect that does not define this rung sends NO field rather than
763
- // the nearest one: `max` mapped down to `high` would report a level the
764
- // caller did not choose and cannot tell apart from `high` on the wire.
765
- // `extra` carries the rungs that exist on the wire but are not part of
766
- // the mirrored user-facing table (see DEEPSEEK_EFFORT_EXTRA).
767
- const level = Object.prototype.hasOwnProperty.call(d.map, eff)
768
- ? d.map[eff]
769
- : (d.extra && Object.prototype.hasOwnProperty.call(d.extra, eff) ? d.extra[eff] : undefined);
770
- if (level === undefined) return undefined;
771
- return { field: d.field, level };
772
- }
773
- }
774
- return undefined;
775
- }
776
-
777
- /** Relay model entries arrive as ids or objects; keep only real model ids. */
778
- function normalizeCatalog(models) {
779
- if (!Array.isArray(models)) return [];
780
- return models
781
- .map((m) => (typeof m === 'string' ? { id: m } : m))
782
- .filter((m) => m && m.id);
783
- }
784
-
785
- /**
786
- * The Aegis Cloud (pooled) dropdown.
787
- *
788
- * It offers the server's whole catalog (`/api/v1/models`): the pooled brain
789
- * first, under its one name (Nexus), then every per-provider id the account can
790
- * pin (`deepseek`, `anthropic`, `groq`, `openai`, ...).
791
- *
792
- * Two narrower shapes were shipped here and both are reverted, because both
793
- * produced the same report — a user asking where the models went. First the
794
- * class collapsed to a single "Nexus" row (`filterAegisCatalog`), which ended
795
- * the two-host disagreement about the brain's five tier spellings by removing
796
- * the choice: a funded account had `deepseek` advertised to it and no way to
797
- * pin it. Then it offered nothing at all — `omitAegisCloudModels` composed with
798
- * that collapse returns `[]`, because the omission removes the only entry the
799
- * collapse looks for. The rule both hosts call now is `offerableCatalog`:
800
- * everything the server advertises, the tier spellings folded into the one row
801
- * they point at.
802
- *
803
- * What is NOT changed: the account key, and everything the key is *for* — the
804
- * pooled turn itself, cloud memory sync, and the BYOK handling fee that is
805
- * billed to this account (see the byok branch below).
806
- *
807
- * The list itself is one shared rule in `client/brain-catalog.js`, shared with
808
- * the CLI: two copies is how this host and the terminal previously came to
809
- * offer the same account two different model lists. Resolved the two ways this
810
- * repo resolves every shared module — repo-relative in a checkout, and this
811
- * app's staged vendor/ tree.
812
- */
813
- const { offerableCatalog } = requireSharedBrain();
814
-
815
- /**
816
- * The BYOK additions, applied to the server's provider catalog below. Same
817
- * one-copy rule as the brain rule above: the terminal requires this same module
818
- * (cli/src/commands.js, through sharedpaths.js), so neither host can offer a
819
- * provider row the other does not.
820
- */
821
- const { withByokAdditions, canonicalModelId } = requireSharedByokCatalog();
822
- const {
823
- withUserModels,
824
- unmatchedUserProviders,
825
- load: loadUserModels,
826
- addUserModel,
827
- removeUserModel,
828
- } = requireSharedUserModels();
829
- // The server's full catalog, cached on disk (`client/catalog-client.js`),
830
- // resolved the same existence-first way as the two modules above so the
831
- // terminal and the window cannot offer different ids for one account. Layered
832
- // between the shipped additions and the user's own overlay — see the CLI's
833
- // cli/src/commands.js for why that order.
834
- const { withCatalog } = requireSharedCatalogClient();
835
- const {
836
- discoverModels: discoverVendorModels,
837
- canDiscover: canDiscoverVendorModels,
838
- endpointFor: vendorEndpointFor,
839
- discoverableProviders,
840
- } = requireSharedModelDiscovery();
841
-
842
- // ── Agent-loop helpers ──────────────────────────────────────────────────────
843
-
844
- /** Parse a model-supplied argument blob (string or already-parsed object). */
845
- function parseArgs(raw) {
846
- if (raw == null) return {};
847
- if (typeof raw === 'object') return raw;
848
- try {
849
- const v = JSON.parse(String(raw));
850
- return v && typeof v === 'object' ? v : {};
851
- } catch {
852
- return {};
853
- }
854
- }
855
-
856
- /**
857
- * Pull normalised tool calls out of whichever shape the transport returned:
858
- * the shared `result.toolCalls` both local parsers emit, or a provider-native
859
- * `choices[0].message.tool_calls` (the Aegis pool relays the upstream OpenAI
860
- * shape verbatim).
861
- */
862
- function extractToolCalls(res) {
863
- if (!res) return [];
864
- if (Array.isArray(res.toolCalls) && res.toolCalls.length) {
865
- return res.toolCalls
866
- .map((c) => ({ id: c.id || '', name: c.name || '', args: parseArgs(c.args) }))
867
- .filter((c) => c.name);
868
- }
869
- const msg = res.choices && res.choices[0] && res.choices[0].message;
870
- const raw = (msg && msg.tool_calls) || [];
871
- if (!Array.isArray(raw)) return [];
872
- return raw
873
- .map((tc) => {
874
- const fn = (tc && tc.function) || {};
875
- return { id: (tc && tc.id) || '', name: fn.name || (tc && tc.name) || '', args: parseArgs(fn.arguments) };
876
- })
877
- .filter((c) => c.name);
878
- }
879
-
880
- /** The textual content of one assistant turn (empty when it only called tools). */
881
- /**
882
- * The prompt a Pro turn actually hands the child.
883
- *
884
- * `pro` is the one class that does not replay `opts.messages` into its
885
- * transport: the `claude` child runs its own agent loop, so sending this
886
- * engine's transcript would make it re-run every tool call a second time. That
887
- * decision is right for an ordinary turn and silently wrong for the engine's
888
- * RE-ASK rounds — the synthesis pass and the recovery ladder both re-dispatch
889
- * with `prompt: ''` plus a grown `messages`, which is the shape every other
890
- * class reads as "continue this conversation; the new instruction is the last
891
- * user message in the history". The Pro branch read only `opts.prompt`, so each
892
- * of those rounds spawned `claude -p ''`: an empty prompt, on a child whose
893
- * stdin is `'ignore'`, with `--resume` as its only other context.
894
- *
895
- * The consequence was the failure this function exists to prevent. A Pro turn
896
- * whose first round came back empty could never be recovered, because every
897
- * recovery round was guaranteed empty too — the ladder then reported "2 extra
898
- * recovery calls with a larger budget and a changed ask came back empty too"
899
- * over a transport that had been asked nothing at all. Measured on
900
- * claude-code-pro, 2026-10-11.
901
- *
902
- * So when a round carries no prompt of its own, the LAST user message in
903
- * `opts.messages` becomes the child's prompt. The nudges the ladder appends are
904
- * exactly that, and `--resume` reattaches the child to its own session, so the
905
- * instruction lands in a conversation that already holds the findings — which
906
- * is what makes the recovery round a re-ask rather than a fresh, empty one.
907
- *
908
- * An ordinary turn is untouched: it has its own prompt, so the first branch
909
- * returns before `messages` is ever consulted.
910
- */
911
- function proTurnPrompt(opts) {
912
- // `prompt` may be a content-part array when the turn carries dropped
913
- // attachments. PRO is a CHILD PROCESS fed text on stdin, so pictures cannot
914
- // travel there at all — the flattened form is the honest thing to send, and
915
- // the renderer warns before the turn (see the vision-capability gate in
916
- // app.js) rather than letting a dropped picture vanish silently.
917
- const raw = Array.isArray(opts.prompt) ? flattenContent(opts.prompt) : opts.prompt;
918
- const own = typeof raw === 'string' ? raw.trim() : '';
919
- if (own) return raw;
920
- const messages = Array.isArray(opts.messages) ? opts.messages : [];
921
- for (let i = messages.length - 1; i >= 0; i -= 1) {
922
- const m = messages[i];
923
- if (!m || m.role !== 'user') continue;
924
- const text = flattenContent(m.content);
925
- if (text.trim()) return text;
926
- }
927
- // Nothing to borrow: keep the caller's own value rather than inventing text,
928
- // so a round with genuinely no ask still reaches the ladder and is reported
929
- // as the empty round it is.
930
- return raw;
931
- }
932
-
933
- function assistantText(res) {
934
- const msg = res && res.choices && res.choices[0] && res.choices[0].message;
935
- return (msg && typeof msg.content === 'string' && msg.content) || '';
936
- }
937
-
938
- /**
939
- * The provider's stop reason for a completion ('' when it sent none). The two
940
- * wire formats report it in different places and both have to be read: the
941
- * OpenAI shape carries `choices[0].finish_reason` (this is what providers.js
942
- * and vendor/aegis.js emit), while providers.js's Anthropic parser puts
943
- * `stop_reason` on the result and never sets a finish_reason on the choice.
944
- */
945
- function finishReasonOf(res) {
946
- const choice = res && res.choices && res.choices[0];
947
- return (choice && choice.finish_reason) || (res && res.stop_reason) || '';
948
- }
949
-
950
- /**
951
- * True when the provider cut the answer off at the token budget instead of
952
- * the model choosing to stop. This is the diagnosis for the most common
953
- * flavour of the empty turn: DeepSeek (and other reasoning models that bill
954
- * hidden chain-of-thought against max_tokens) can spend the entire budget
955
- * before emitting a single visible token, and the completion still arrives
956
- * as a clean `finish_reason: 'length'` — no error, empty content. A tool
957
- * call whose JSON was truncated mid-argument lands here too, where
958
- * parseArgs() would otherwise silently yield `{}` and run the tool with no
959
- * arguments, which is worse than retrying.
960
- */
961
- function isTruncated(res) {
962
- const reason = finishReasonOf(res);
963
- // 'length' is OpenAI's wording, 'max_tokens' is Anthropic's — same event.
964
- return reason === 'length' || reason === 'max_tokens';
965
- }
966
-
967
- /**
968
- * The hidden chain-of-thought a completion carried, read from every wire shape
969
- * that reports one. DeepSeek returns `message.reasoning_content`, OpenAI's
970
- * o-series/gpt-5 shape returns `message.reasoning`, and the Anthropic parser
971
- * folds thinking into content blocks. All three are the same thing here: tokens
972
- * the model spent out of the same budget as its answer.
973
- */
974
- function reasoningTextOf(res) {
975
- if (!res) return '';
976
- const choice = res.choices && res.choices[0];
977
- const msg = (choice && choice.message) || {};
978
- if (Array.isArray(msg.content)) {
979
- const blocks = msg.content
980
- .filter((b) => b && (b.type === 'thinking' || b.type === 'reasoning'))
981
- .map((b) => b.thinking || b.text || '')
982
- .join('');
983
- if (blocks) return blocks;
984
- }
985
- const fromContent = msg.content && typeof msg.content === 'object' ? msg.content.reasoning_content : '';
986
- const candidates = [
987
- msg.reasoning_content,
988
- msg.reasoning,
989
- choice && choice.reasoning_content,
990
- res.reasoning_content,
991
- res.reasoning,
992
- fromContent,
993
- ];
994
- for (const c of candidates) if (typeof c === 'string' && c) return c;
995
- return '';
996
- }
997
-
998
- /**
999
- * Deliberation the provider MEASURED but withheld, in tokens.
1000
- *
1001
- * The companion to `reasoningTextOf()` above, for the one case where there is no
1002
- * text to read: Claude Code Pro runs extended thinking by default and withholds
1003
- * the deliberation itself, so `thinking_delta.thinking` arrives as the empty
1004
- * string while the billed count climbs. A round like that carries real reasoning
1005
- * and no reasoning TEXT, so a text-only predicate reads it as "the model said
1006
- * nothing" — the wrong diagnosis, and the one that made a Pro turn report
1007
- * "No visible text came back" while the child had in fact been thinking.
1008
- *
1009
- * Read from the message shape first (what `claude-pro.js` `proMessage()` sets)
1010
- * and then from the standard usage detail `completion_tokens_details.
1011
- * reasoning_tokens`, so a provider that meters deliberation on the usage
1012
- * envelope is seen too.
1013
- */
1014
- function reasoningTokensOf(res) {
1015
- if (!res) return 0;
1016
- const choice = res.choices && res.choices[0];
1017
- const msg = (choice && choice.message) || {};
1018
- const usage = res.usage || {};
1019
- const details = usage.completion_tokens_details || usage.output_tokens_details || {};
1020
- const candidates = [
1021
- msg.thinking_tokens,
1022
- msg.reasoning_tokens,
1023
- choice && choice.thinking_tokens,
1024
- res.thinking_tokens,
1025
- details.reasoning_tokens,
1026
- details.thinking_tokens,
1027
- ];
1028
- for (const c of candidates) {
1029
- if (typeof c === 'number' && Number.isFinite(c) && c > 0) return c;
1030
- }
1031
- return 0;
1032
- }
1033
-
1034
- /**
1035
- * The empty turn `isTruncated()` cannot see, and the reason this error survived
1036
- * a truncation retry that was already in place: a reasoning model that spends
1037
- * the budget on hidden chain-of-thought and then finishes with NO visible text
1038
- * still reports `finish_reason: 'stop'` — the provider considers the call
1039
- * complete, because to it the model did stop, it just stopped while thinking.
1040
- * Measured live on byok/deepseek-v4-flash: `stop` + empty content + non-empty
1041
- * `reasoning_content`, which fell straight through both retry gates to
1042
- * emptyTurnError. Reasoning tokens and answer tokens share one budget, so the
1043
- * recovery is identical to a 'length' cut: buy room and ask once more.
1044
- *
1045
- * A round with no reasoning TEXT but a non-zero reasoning-token count counts as
1046
- * reasoning here: that is a Pro turn whose deliberation was withheld, and
1047
- * treating it as genuinely empty is what sent it to the generic nudge instead
1048
- * of the ask that names the problem.
1049
- */
1050
- function reasonedButSilent(res) {
1051
- return !assistantText(res) && (reasoningTextOf(res) !== '' || reasoningTokensOf(res) > 0);
1052
- }
1053
-
1054
- /**
1055
- * The rung a reasoning-only retry is raised to. Every reasoning retry is paid
1056
- * for out of the same budget twice — the chain-of-thought is paid for again
1057
- * before a single visible word can be written — so a rung that merely doubled
1058
- * (the 8k floor -> 16k) still finished silent: the floor is what an unstated
1059
- * budget yields, and it is the rung the live failure had already exhausted.
1060
- */
1061
- const REASONING_RETRY_FLOOR = 32768;
1062
-
1063
- /**
1064
- * The one budget decision every empty-turn retry makes, in one place: is the
1065
- * number we hold ours (a rung we derived, which a retry may raise) or the
1066
- * caller's (a deliberate cap the retry may only double)?
1067
- *
1068
- * It matters exactly here. The floor above is a floor on OUR rung; applying it
1069
- * to a stated cap would turn the flow lane's deliberate 1024-token ceiling into
1070
- * 32768 because the model happened to think out loud — the same "a guessed
1071
- * number goes on the wire as a ceiling" bug statedCapOf() exists to prevent.
1072
- */
1073
- function retryBudgetFor(opts, reasoningOnly) {
1074
- const doubled = doubledBudget(opts.maxTokens);
1075
- if (!reasoningOnly) return doubled;
1076
- // Which number is this? A budget that is one of EFFORT_TOKEN_BUDGET's own
1077
- // rungs (8192/16384/32768) is the rung this call was sized at, so a reasoning
1078
- // retry may raise it to the top of the ladder — that is the live failure this
1079
- // exists for: 16384 burned on hidden chain-of-thought, finish_reason 'stop',
1080
- // empty content. Any OTHER number belongs to someone who chose it (the flow
1081
- // lane's deliberate 1024, a caller's own 4096), and doubling is as far as a
1082
- // retry may go: promoting it by an order of magnitude would put a ceiling the
1083
- // user never asked for on the wire.
1084
- return ladderRung(opts.maxTokens) ? Math.max(doubled, REASONING_RETRY_FLOOR) : doubled;
1085
- }
1086
-
1087
- /** Is this budget one of the effort ladder's own rungs (a size WE derived)? */
1088
- function ladderRung(maxTokens) {
1089
- const n = Number(maxTokens);
1090
- return Number.isFinite(n) && Object.values(EFFORT_TOKEN_BUDGET).includes(n);
1091
- }
1092
-
1093
- /**
1094
- * Double a budget for the one-shot truncation retry. A budget the caller set
1095
- * on purpose (the flow lane's deliberate 1024-token cap, say) is merely
1096
- * doubled — the floor only applies when nothing was set at all, so a retry
1097
- * can never silently override a small cap by an order of magnitude.
1098
- */
1099
- function doubledBudget(maxTokens) {
1100
- const n = Number(maxTokens) || 0;
1101
- return n > 0 ? n * 2 : 8192;
1102
- }
1103
-
1104
- /**
1105
- * The cap the CALLER stated, or `undefined` meaning "none was stated".
1106
- *
1107
- * The two branches resolve one question — whose number is this? — and the
1108
- * first is the fix. An internal re-entry (runSubagent's nested chat()) passes
1109
- * `statedMaxTokens` explicitly, because the `maxTokens` it holds is the rung
1110
- * reasoningBudget() derived from `effort`: a number the server is about to
1111
- * derive for itself. Re-reading that value as the caller's own is what put a
1112
- * guessed 32768 on the wire as a *ceiling over* aegis1's ladder
1113
- * (pass_budgets: total = min(ladder, max_tokens x passes)) — so a
1114
- * high-effort subagent silently ran at 8192 and the ladder the UI advertised
1115
- * was not the budget the call used.
1116
- *
1117
- * A non-numeric or non-positive value means "nothing stated" — never a 0- or
1118
- * NaN-token ceiling.
1119
- */
1120
- function statedCapOf(payload) {
1121
- const asCap = (v) => {
1122
- const n = Number(v);
1123
- return Number.isFinite(n) && n > 0 ? n : undefined;
1124
- };
1125
- if (payload && Object.prototype.hasOwnProperty.call(payload, 'statedMaxTokens')) {
1126
- return asCap(payload.statedMaxTokens);
1127
- }
1128
- return asCap(payload && payload.maxTokens);
1129
- }
1130
-
1131
- /**
1132
- * The follow-up shown to a model that ended its turn with neither text nor a
1133
- * tool call. Sent as a plain user message (never as a tool result — there is
1134
- * no pending tool call to answer) so every provider accepts it verbatim.
1135
- */
1136
- const EMPTY_TURN_NUDGE =
1137
- 'Your previous reply came back empty — it contained no answer and no tool call. ' +
1138
- 'Write your answer now, using only the information already gathered above. ' +
1139
- 'No tools are available in this reply, so do not call any: respond in plain ' +
1140
- 'prose or markdown.';
1141
-
1142
- /**
1143
- * The nudge for an empty round that was NOT really empty: the model spent it
1144
- * thinking. A reasoning model that burns its budget on hidden chain-of-thought
1145
- * and stops without writing a visible word (`finish_reason: 'stop'`, empty
1146
- * content, non-empty `reasoning_content`) is the normal shape of this failure on
1147
- * DeepSeek, and the generic nudge above does not describe it — "write your answer
1148
- * now" invites the same reasoning pass a second time, because nothing told the
1149
- * model that the thinking was the problem.
1150
- *
1151
- * Naming the failure IS the fix, and it is the upstream engine's own last resort
1152
- * (`src/backend.js`, the `thoughtOnly` recovery round). Buying budget is the
1153
- * other lever, already tried below; when that has failed the budget is not what
1154
- * is wrong, so the ask changes instead: answer WITHOUT thinking first.
1155
- */
1156
- const THOUGHT_ONLY_NUDGE =
1157
- 'Your previous round was spent entirely on hidden reasoning and produced no visible reply. ' +
1158
- 'Answer the user directly and briefly now. Do not reason, explain, or think first — write only ' +
1159
- 'the answer, no tools.';
1160
-
1161
- /**
1162
- * The last ask of the recovery ladder, for a turn that stayed silent even after
1163
- * being told not to think first.
1164
- *
1165
- * A model that is going to reason anyway will reason whatever the nudge says, so
1166
- * the final round stops asking it not to: the ask becomes "say anything usable
1167
- * about what you already have", which a model that has demonstrably read the
1168
- * context can always satisfy. Producing a slightly thin write-up is strictly
1169
- * better than the alternative — the transcript keeps the answer, and the user
1170
- * can ask for detail on the one point that was skimped, in a turn where the
1171
- * material is already in context.
1172
- */
1173
- const FINAL_ANSWER_NUDGE =
1174
- 'Write your answer now, in plain prose, using only what is already in this conversation. ' +
1175
- 'If your information is incomplete, say what you have and what is missing — an incomplete ' +
1176
- 'answer is the expected outcome here and is better than none. No tools, no preface.';
1177
-
1178
- /**
1179
- * How many EXTRA calls an empty write-up round is worth before the turn is
1180
- * declared failed.
1181
- *
1182
- * The upstream engine spends additional calls on a silent round rather than
1183
- * telling the reader to go and change a setting (`src/backend.js`'s thoughtOnly
1184
- * recovery), and this is the same trade, made explicit because the trade is the
1185
- * whole point of the number: an extra dispatch costs tokens, a failed turn costs
1186
- * the entire investigation the tool log on screen paid for. Two calls — one
1187
- * after the budget-retry above, one after the ask changes — is where the curve
1188
- * flattens: measured on byok/deepseek-v4-flash, a round that reasons and stays
1189
- * silent either answers on the first changed ask or is not going to answer at
1190
- * all, because the failure is the model's habit and not the wording.
1191
- *
1192
- * Crucially, every one of these rounds runs with `tools: []` on `synthesisOpts`:
1193
- * they re-ask for the write-up out of a context that already holds the findings,
1194
- * so "more calls" can never mean "do the investigation again".
1195
- */
1196
- const RECOVERY_ROUNDS = 2;
1197
-
1198
- /**
1199
- * The follow-up for a turn that STOPPED WITH AN ANSWER BUT MUTATED NOTHING.
1200
- *
1201
- * This is the gap the empty-turn guards above do not cover, and it is the one
1202
- * that costs a *task* its result rather than a reader their write-up. They fire
1203
- * on "no text and no tool call"; a model that investigated correctly, then
1204
- * answered "here is the root cause, so the fix is …" and stopped without ever
1205
- * calling writeFile/editFile passes straight through — the turn is not empty,
1206
- * it is merely unfinished. On a benchmark that scores the diff, that turn is a
1207
- * zero no matter how good the prose was: SWE-bench sympy-12096 was scored as a
1208
- * 0-byte patch after 7 tool calls and 45k tokens of correct investigation.
1209
- *
1210
- * GATED ON A MUTATION-SHAPED ASK, never on "no writes" alone. A question
1211
- * ("why does this throw?"), a review, or a greeting legitimately ends with no
1212
- * edit, and nudging those would be the engine inventing work — the exact
1213
- * failure the prompt's "never invent a task" rule forbids. See
1214
- * wantsMutation() below for what qualifies.
1215
- */
1216
- const UNMUTATED_TURN_NUDGE =
1217
- 'You ended the turn without changing any file, but this request asked for a change. ' +
1218
- 'The tools are still available in this reply: make the edit now with editFile or writeFile. ' +
1219
- 'If you already know what to change, change it — describing the fix is not the fix. ' +
1220
- 'If you genuinely cannot, say precisely what blocks you.';
1221
-
1222
- /**
1223
- * How many extra calls a mutation-shaped ask that produced no edit is worth.
1224
- *
1225
- * One. The measured failure is a model that investigated correctly and stopped
1226
- * one action early, which a single re-ask fixes; a second would be a model that
1227
- * has decided not to edit, and re-asking that is how a turn burns its horizon
1228
- * without ever producing a diff. The guard is entered at most once per turn
1229
- * (`unmutatedRetried` at the loop head), so a provider that keeps declining
1230
- * still terminates.
1231
- */
1232
-
1233
- /** Imperative-shape asks: a verb that means "change the code", in the user's own
1234
- * voice. Deliberately a narrow allowlist rather than a "not a question" test —
1235
- * a false positive here nags a user who asked a question, which is worse than
1236
- * the missed nudge on an ask phrased unusually. */
1237
- const MUTATION_INTENT_RE = new RegExp(
1238
- '\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|' +
1239
- 'patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|' +
1240
- 'resolve|repair|address|apply|introduce|support|wire\\s+up)\\b',
1241
- 'i',
1242
- );
1243
-
1244
- /**
1245
- * Did this ask actually want a file changed?
1246
- *
1247
- * Three conditions, all necessary, so the nudge cannot fire on a question:
1248
- * 1. the turn made a mutation-shaped tool call (so the model ALSO believed a
1249
- * change was wanted — a pure read-only investigation never qualifies, no
1250
- * matter how imperative the prompt reads);
1251
- * 2. it mutated nothing (no writeFile/editFile, and no exec — exec is how a
1252
- * model legitimately writes through a here-doc or a patch apply);
1253
- * 3. the ask is phrased as a change, not as a question.
1254
- *
1255
- * @param {string} ask the turn's own prompt text
1256
- * @param {boolean} mutated any mutating tool succeeded this turn
1257
- * @param {number} mutations mutating tool CALLS attempted this turn
1258
- */
1259
- function wantsMutation(ask, mutated, mutations) {
1260
- if (mutated) return false;
1261
- if (!(mutations > 0)) return false;
1262
- const text = String(ask || '');
1263
- if (!text.trim()) return false;
1264
- // A trailing question mark on the ask is the user asking ABOUT the code, not
1265
- // asking FOR a change — the reference case being "why does this throw?".
1266
- if (/\?\s*$/.test(text.trim())) return false;
1267
- return MUTATION_INTENT_RE.test(text);
1268
- }
1269
-
1270
- /**
1271
- * Last resort for a turn that is still empty after the synthesis pass.
1272
- *
1273
- * Throws rather than returning the blank completion. Returning it is what
1274
- * produces the renderer's undiagnosable "(empty response)" bubble, and
1275
- * synthesising fake assistant text instead would be worse: renderer/app.js
1276
- * persists whatever comes back as the assistant's own message and syncs it
1277
- * to the aegis account, so the notice would re-enter the model's context on
1278
- * the next turn as something it had said. Failing loudly leaves the turn's
1279
- * real tool log on screen, keeps the transcript honest, and names the cause
1280
- * (renderer prints `Error: <message>`).
1281
- */
1282
- function emptyTurnError({ cls, model, finishReason, reasoningChars, reasoningTokens, effort, recoveryRounds }) {
1283
- const calls = Number(recoveryRounds) || 0;
1284
- // A withheld deliberation has no chars to count, so the two signals are
1285
- // reported as the one fact they both are: the round spent its output on
1286
- // thinking. Without this the Pro case printed "No visible text came back from
1287
- // any of those calls", which describes a transport that produced nothing —
1288
- // the opposite of a child that reasoned at length and wrote no answer.
1289
- const tokens = Number(reasoningTokens) || 0;
1290
- const reasoned = !!reasoningChars || tokens > 0;
1291
- const reasonClause = reasoningChars
1292
- ? `, hidden reasoning: ${reasoningChars} chars and no visible text`
1293
- : tokens > 0
1294
- ? `, ~${tokens} thinking tokens billed and no visible text`
1295
- : '';
1296
- const err = new Error(
1297
- `The model returned no answer after ${cls}/${model} was asked to summarise its results` +
1298
- (calls
1299
- ? `, and ${calls} extra recovery call${calls === 1 ? '' : 's'} with a larger budget ` +
1300
- 'and a changed ask came back empty too'
1301
- : '') +
1302
- ` (stop reason: ${finishReason || 'none'}` +
1303
- `${effort ? `, effort: ${effort}` : ''}` +
1304
- `${reasonClause}). ` +
1305
- (reasoned
1306
- ? // Deliberately NOT "raise the Effort rung". The budget was already taken
1307
- // out of the equation before this error could be reached: the recovery
1308
- // calls above ran at the top of the ladder, so pointing at the ceiling
1309
- // would send the reader to change the one setting that is already
1310
- // maxed out. The unchanged thing is the model's habit of answering
1311
- // inside its head, and that is what gets named.
1312
- 'Every one of those calls spent its output on hidden reasoning instead of writing a ' +
1313
- 'word, so this is the model rather than the budget: pick a model that answers without ' +
1314
- 'a thinking pass, or ask for a smaller piece of work.'
1315
- : 'No visible text came back from any of those calls. Send the request again, in smaller ' +
1316
- 'pieces, or from a different model.')
1317
- );
1318
- err.status = 502;
1319
- return err;
1320
- }
1321
-
1322
- function createLocalEngine({
1323
- aegis,
1324
- settings,
1325
- tools,
1326
- promptBuilder,
1327
- // The level's recall breadth, injected by the host that owns the
1328
- // avatar ledger (desktop/main.js builds one from lib/avatar/turn.js). It is a
1329
- // SEAM rather than a call into lib/avatar/* because this engine is shared with
1330
- // the CLI (cli/src/deps.js loads this file): the engine must not grow a
1331
- // dependency on the desktop's avatar directory, and a host with no avatar
1332
- // simply passes nothing and gets the exact pre-Phase-20 turn.
1333
- //
1334
- // `recallProvider({ payload, env, system })` may be sync or async and returns
1335
- // either the final system prompt or `{ system }`. It runs once per turn,
1336
- // before the first dispatch, and its result is the system prompt every round
1337
- // of that turn travels with.
1338
- recallProvider,
1339
- env,
1340
- getConfirmMode,
1341
- // Injectable for tests; defaults to the real transport so every existing
1342
- // caller (desktop/main.js, the CLI's deps.js) wires the local class by
1343
- // simply existing.
1344
- localTransport: localT = localTransport,
1345
- // Injectable for tests (and for a host that fronts the network itself): the
1346
- // fetch used ONLY by `discoverModels`, which asks a vendor's list API. Every
1347
- // other request in this file goes through `localT`, so this is deliberately
1348
- // not the transport — discovery is an outbound call to api.<vendor>, not to
1349
- // the AEGIS relay. Undefined in production, which means the global fetch.
1350
- fetchImpl,
1351
- // Injectable for tests, like `localTransport` above: the git half of the Pro
1352
- // child's sandbox widening (proAddDirs). Production passes nothing and the
1353
- // real `./git-scope.js` is resolved at call time.
1354
- gitScope,
1355
- }) {
1356
- const controllers = new Map(); // sessionId -> AbortController
1357
- const T = tools || toolsModule;
1358
- const buildSystemPrompt = (promptBuilder && promptBuilder.buildSystemPrompt) || promptModule.buildSystemPrompt;
1359
-
1360
- /** "Confirm before running tools" (Settings toggle, persisted by
1361
- * lib/settings.js. Because gatedExecuteTool is called for EVERY tool round
1362
- * it is read per call, not captured once at construction: flipping the
1363
- * switch takes effect on the next tool call, with no restart.
1364
- * An explicit `getConfirmMode` factory arg wins (used by tests); then the
1365
- * settings store's own accessor; then the safe default — ON, i.e. the gate
1366
- * stays up, so a store that predates the toggle can never silently
1367
- * disable it. */
1368
- // Session-scoped round accounting (lib/local/session-rounds.js): the
1369
- // tool-round cap is held against the *session* rather than the single turn,
1370
- // so a turn that reaches its horizon is resumed by the next turn in the same
1371
- // conversation instead of being cut off with the work lost. Module-level
1372
- // state, so it survives `send()` and even a fresh engine instance.
1373
- const sessionRounds = require('./session-rounds.js');
1374
- const confirmModeEnabled = () => {
1375
-
1376
- if (typeof getConfirmMode === 'function') return getConfirmMode() !== false;
1377
- if (settings && typeof settings.getConfirmMode === 'function') {
1378
- const value = settings.getConfirmMode();
1379
- return value === undefined ? true : Boolean(value);
1380
- }
1381
- return true;
1382
- };
1383
-
1384
- // ── Tool-call approval gate (renderer confirms exec/writeFile/editFile
1385
- // before they run) ─────────────────────────────────────────────────────
1386
- //
1387
- // `sessionAllowlists` is keyed by the CONVERSATION's root session id (the
1388
- // one the renderer's `send()` mints once per thread and reuses across
1389
- // turns — see rootSessionId below), never by the per-call sessionId a
1390
- // subagent gets, so "allow for this session" reads the way the user sees
1391
- // it: one decision per open conversation, not per nested tool round.
1392
- // In-memory only, on purpose — never persisted, so a restart (or
1393
- // newChat()'s clearSessionApprovals) always starts from a clean gate.
1394
- const sessionAllowlists = new Map(); // rootSessionId -> Set<toolName>
1395
- // Denials are remembered for the same reason allows are, mirroring it for
1396
- // the other answer. Without this, a "Deny" was forgotten the instant it was
1397
- // given: the model read `… the user denied the request`, re-planned, called
1398
- // the SAME tool again, and the gate raised a SECOND card — so one "no" cost
1399
- // the user a prompt per round for up to maxRounds (24 chat / 40 autonomous)
1400
- // rounds, each round re-sending the whole conversation to the provider. A
1401
- // gate that only remembers "yes" turns a single click into a retry storm;
1402
- // remembering "no" makes the first answer stick.
1403
- const sessionDenials = new Map(); // rootSessionId -> Set<toolName>
1404
- // ── Pro-class conversation continuity ────────────────────────────────────
1405
- //
1406
- // `claude` keeps its own session store, and the Pro child is spawned fresh
1407
- // for every turn. Continuity therefore has to be carried by US: the session
1408
- // id the child reports is remembered here, keyed by the CONVERSATION's root
1409
- // session id, and handed back as `--resume` on the next turn. Without this
1410
- // map every Pro turn is a brand-new conversation — the child is told nothing
1411
- // about the prior turns, because `pro` has no `messages` channel (the child
1412
- // runs its own agent loop), so "Claude has no memory of this conversation"
1413
- // was literally true.
1414
- //
1415
- // Keyed by root, like the allowlists above: one thread, one memory. In-memory
1416
- // only, and cleared by the same newChat()/`/clear` hook that clears the gate,
1417
- // because "clear the conversation" must clear what the child remembers too —
1418
- // a resumed child would otherwise answer from turns the user just erased.
1419
- const proSessions = new Map(); // rootSessionId -> child session UUID
1420
- const pendingApprovals = new Map(); // approvalId -> { resolve }
1421
- const pendingRoundAsks = new Map(); // askId -> { resolve }
1422
-
1423
- function sessionAllows(rootId, name) {
1424
- const set = sessionAllowlists.get(rootId);
1425
- return Boolean(set && set.has(name));
1426
- }
1427
-
1428
- function allowForSession(rootId, name) {
1429
- if (!sessionAllowlists.has(rootId)) sessionAllowlists.set(rootId, new Set());
1430
- sessionAllowlists.get(rootId).add(name);
1431
- }
1432
-
1433
- /** Has this conversation already refused this tool? Checked before the card
1434
- * is raised, so a repeat call is refused outright instead of re-prompting. */
1435
- function sessionDenies(rootId, name) {
1436
- const set = sessionDenials.get(rootId);
1437
- return Boolean(set && set.has(name));
1438
- }
1439
-
1440
- function denyForSession(rootId, name) {
1441
- if (!sessionDenials.has(rootId)) sessionDenials.set(rootId, new Set());
1442
- sessionDenials.get(rootId).add(name);
1443
- }
1444
-
1445
- /**
1446
- * The text a refused tool hands back to the model. The old one-line
1447
- * `"<tool> was not executed — the user denied the request."` read to a
1448
- * capable agent as a transient failure to route around: it would apologise,
1449
- * pick a different command that does the same thing, and call the gate
1450
- * again. This says the durable part out loud (the refusal covers the rest of
1451
- * the conversation, not just that call) and asks for the one response that
1452
- * actually helps — say what you need and stop, so the user can re-enable it.
1453
- */
1454
- function denialText(name) {
1455
- return (
1456
- `${name} was not executed — the user denied this tool for this conversation. ` +
1457
- `Do NOT retry it and do NOT attempt the same effect by another route ` +
1458
- `(another command, a writeFile instead of an edit, a subagent). ` +
1459
- `Stop calling tools and reply in plain text: say what you were trying to do, ` +
1460
- `what you need, and that the user can re-enable ${name} to let it proceed.`
1461
- );
1462
- }
1463
-
1464
- /** newChat() in the renderer calls this so a fresh conversation never
1465
- * inherits a prior thread's blanket allows — or its refusals. A new chat is
1466
- * a new gate in both directions: leaving denials behind would silently
1467
- * refuse a tool in a thread where the user never said no. */
1468
- function clearSessionApprovals(rootSessionId) {
1469
- sessionAllowlists.delete(rootSessionId);
1470
- sessionDenials.delete(rootSessionId);
1471
- // And the Pro child's memory of the conversation, for the same reason: a
1472
- // new chat (or `/clear`) that left the child resumed would let it answer
1473
- // from turns the user just deleted, which looks like the clear failed.
1474
- proSessions.delete(rootSessionId);
1475
- return { ok: true };
1476
- }
1477
-
1478
- /** The renderer's approval card resolves the pending requestApproval()
1479
- * promise below. An unknown/already-answered id is a no-op — the card
1480
- * can only be clicked once (it disables itself), but a duplicate or
1481
- * late message must never throw. */
1482
- function respondApproval(approvalId, decision) {
1483
- const pending = pendingApprovals.get(approvalId);
1484
- if (!pending) return { ok: false };
1485
- pendingApprovals.delete(approvalId);
1486
- pending.resolve(decision === 'session' || decision === 'once' ? decision : 'deny');
1487
- return { ok: true };
1488
- }
1489
-
1490
- /**
1491
- * Ask the renderer to approve one mutating tool call. Resolves 'once',
1492
- * 'session' or 'deny' (an explicit choice by the user) — or 'cancel' when
1493
- * nobody ever answered: no listener able to reply, or the turn was aborted.
1494
- * 'cancel' is kept apart from 'deny' on purpose. Both refuse the call, but
1495
- * only 'deny' is a decision the user made, so only 'deny' may be remembered
1496
- * as "this conversation said no" (see sessionDenials). Folding the two
1497
- * together — which is what the old fail-safe did, resolving 'deny' for an
1498
- * abort — would let a cancelled turn permanently refuse a tool the user
1499
- * never ruled on. Sent over `rootOnDelta` (see chat()) as an `{ approval }`
1500
- * chunk so it rides the exact same streaming channel as tool-activity
1501
- * chunks — no new IPC surface needed on the push side, only on the reply
1502
- * side (respondApproval). Fails safe: an unanswered request refuses the
1503
- * call instead of hanging the tool round forever.
1504
- */
1505
- function requestApproval(rootSessionId, rootOnDelta, signal, info) {
1506
- return new Promise((resolve) => {
1507
- if (signal && signal.aborted) {
1508
- resolve('cancel');
1509
- return;
1510
- }
1511
- const id = randomUUID();
1512
- let settled = false;
1513
- const onAbort = () => finish('cancel');
1514
- const finish = (decision) => {
1515
- if (settled) return;
1516
- settled = true;
1517
- pendingApprovals.delete(id);
1518
- if (signal) signal.removeEventListener('abort', onAbort);
1519
- resolve(decision);
1520
- };
1521
- if (signal) signal.addEventListener('abort', onAbort, { once: true });
1522
- pendingApprovals.set(id, { resolve: finish });
1523
- if (typeof rootOnDelta !== 'function') {
1524
- finish('cancel');
1525
- return;
1526
- }
1527
- rootOnDelta({
1528
- delta: '',
1529
- approval: {
1530
- id,
1531
- sessionId: rootSessionId,
1532
- tool: info.tool,
1533
- args: info.args,
1534
- diff: info.diff || null,
1535
- },
1536
- });
1537
- });
1538
- }
1539
-
1540
- /** The renderer's rounds-dialog answer resolves the pending
1541
- * requestRoundsAsk() promise below. An unknown/already-answered id is a
1542
- * no-op, same contract as respondApproval. */
1543
- function respondRoundsAsk(askId, decision) {
1544
- const pending = pendingRoundAsks.get(askId);
1545
- if (!pending) return { ok: false };
1546
- pendingRoundAsks.delete(askId);
1547
- pending.resolve(decision === true || decision === 'continue');
1548
- return { ok: true };
1549
- }
1550
-
1551
- /**
1552
- * Ask the renderer whether to fund another block of tool rounds, mirroring
1553
- * requestApproval's shape exactly: pushed over `rootOnDelta` as a `{ rounds }`
1554
- * chunk (the one channel a detached renderer has into a running turn) and
1555
- * resolved externally via `respondRoundsAsk`. Resolves `true` (fund one more
1556
- * block) or `false` (stop here) — never throws. Fails safe to `false`: no
1557
- * listener, an aborted turn, or an unanswered ask must not keep the loop
1558
- * waiting forever (or, worse, spend rounds nobody agreed to).
1559
- */
1560
- function requestRoundsAsk(rootSessionId, rootOnDelta, signal, info) {
1561
- return new Promise((resolve) => {
1562
- if (signal && signal.aborted) {
1563
- resolve(false);
1564
- return;
1565
- }
1566
- const id = randomUUID();
1567
- let settled = false;
1568
- const onAbort = () => finish(false);
1569
- const finish = (decision) => {
1570
- if (settled) return;
1571
- settled = true;
1572
- pendingRoundAsks.delete(id);
1573
- if (signal) signal.removeEventListener('abort', onAbort);
1574
- resolve(decision);
1575
- };
1576
- if (signal) signal.addEventListener('abort', onAbort, { once: true });
1577
- pendingRoundAsks.set(id, { resolve: finish });
1578
- if (typeof rootOnDelta !== 'function') {
1579
- finish(false);
1580
- return;
1581
- }
1582
- rootOnDelta({
1583
- delta: '',
1584
- rounds: {
1585
- id,
1586
- sessionId: rootSessionId,
1587
- spent: info.spent,
1588
- extensions: info.extensions,
1589
- max: info.max,
1590
- size: info.size,
1591
- },
1592
- });
1593
- });
1594
- }
1595
-
1596
- /**
1597
- * The gate itself: read-only tools and already-session-allowed mutating
1598
- * tools run exactly like executeTool always did. A first-time mutating
1599
- * call previews writeFile/editFile (a preview failure — e.g. old_string
1600
- * not found — is returned as the ordinary tool error, no approval prompt
1601
- * needed for a call that couldn't succeed anyway), asks the renderer, and
1602
- * on approval either applies with a fresh hash check (writeFile/editFile)
1603
- * or runs normally (exec — nothing to hash-check).
1604
- *
1605
- * Confirm mode off (Settings → "Confirm before running tools") short-circuits
1606
- * ALL of that: no preview, no approval card, no requestApproval() — the call
1607
- * runs straight through exactly like a session-allowed one, so "don't ask"
1608
- * is one switch rather than a per-tool blanket allow in every conversation.
1609
- */
1610
- /**
1611
- * The single place a tool executor is called from the chat loop, so the
1612
- * turn guard cannot be bypassed by reaching a different branch (there are
1613
- * four `return`s in gatedExecuteTool below; all of them come through here).
1614
- *
1615
- * exec is *checked* before running and writeFile/editFile are *recorded*
1616
- * after, and the asymmetry is the point: a refusal has to happen before the
1617
- * command runs, while "this path is mine" is only true once the write
1618
- * actually happened — recording a denied or preview-failed write would hide
1619
- * a genuinely foreign file behind a claim of ownership.
1620
- *
1621
- * A refusal is returned as an ordinary tool error, so the model reads it and
1622
- * adapts (name the paths, or don't do it) with no new IPC or renderer
1623
- * channel — the same reason it works identically in the GUI and the CLI.
1624
- */
1625
- async function guardedExecute(name, args, toolCtx) {
1626
- // Resolve `~/…` and refuse a foreign-OS path BEFORE anything below reads it
1627
- // (tools.js normalizeArgs; idempotent, so executeTool normalising again is a
1628
- // no-op). The covenant assert and recordWrite both inspect `args.file_path`,
1629
- // and a path they rule on must be the path that actually gets written.
1630
- const norm = normalizeToolArgs(T, name, args, toolCtx || {});
1631
- if (!norm.ok) return { ok: false, error: norm.error };
1632
- args = norm.args;
1633
- const guard = toolCtx && toolCtx.guard;
1634
- if (guard && name === 'exec') {
1635
- const verdict = blocksDestructive(guard, args && args.command);
1636
- if (!verdict.ok) return { ok: false, error: verdict.reason };
1637
- }
1638
- // ÆL/1 pre-action assert — Σ1..Σ4 / Λ1,Λ2,Λ4.
1639
- //
1640
- // Placed AFTER the destructive-command guard above (so that guard keeps
1641
- // its own message) and BEFORE every executor call below, which is the
1642
- // only thing that matters: `gatedExecuteTool` has four `return`s into
1643
- // this function, and all of them land above this line, so no branch of
1644
- // the confirmation gate can reach an executor without passing here.
1645
- //
1646
- // §9 amendment invariant: ¬M(Λ1) ∧ ¬M(Λ2) ∧ ¬M(Λ4)
1647
- // This check is deliberately *unconditional* and reads nothing from
1648
- // `toolCtx` — no confirm-mode setting, no remembered per-session "allow",
1649
- // no /permissions rule, no admin path and no IPC payload can skip it or
1650
- // reverse its verdict. An approval that could waive Λ2 would be the exact
1651
- // capture K3 describes. To change what is permitted, the covenant text
1652
- // itself has to be re-sealed — which no runtime input can do.
1653
- //
1654
- // DO NOT MOVE THIS BELOW A SHORT-CIRCUIT. It sits above every `return` of
1655
- // the confirmation gate on purpose (ON8/D8 rule 2): `gatedExecuteTool`
1656
- // short-circuits on `!confirmModeEnabled()`, on a remembered session
1657
- // "allow", and on a `/permissions` skip — and since ON8 the confirm-mode
1658
- // preference is the SHARED store's, i.e. the same value the terminal face
1659
- // reads, and `--dangerously-skip-permissions` can arrive in that store as
1660
- // well. A refactor that hoists this below any of those three would make
1661
- // the covenant waivable by a setting a user can write, which is the one
1662
- // thing D8 rule 2 forbids outright. The frozen classes
1663
- // (`write`/`shell`/`network`/`offDevice`, always `'ask'`; see
1664
- // lib/avatar/level.js `LEVEL_INDEPENDENT_APPROVALS`) have the same floor
1665
- // and are asserted beside this one by one/test/permissions.test.mjs.
1666
- const cv = covenant.preActionAssert({ tool: name, args: args || {} });
1667
- if (!cv.allowed) {
1668
- // Non-silent (never a quiet no-op) and bound for Λ4 accountability.
1669
- const record = covenant.bindRefusal({ tool: name, args: args || {} }, cv);
1670
- return {
1671
- ok: false,
1672
- error: `refused by the ÆGIS covenant — ${cv.clause} (${cv.label}): ${cv.reason}`,
1673
- covenant: record,
1674
- };
1675
- }
1676
- // Awaited, not merely returned: "this path is mine" is only true once the
1677
- // write actually landed, and `executeTool` is async — inspecting `.ok` on
1678
- // an un-awaited promise would read undefined and record every write,
1679
- // including the ones that failed. Ownership is load-bearing in the other
1680
- // direction too: a path wrongly claimed stops being reported as foreign.
1681
- const result = await T.executeTool(name, args, toolCtx);
1682
- if (guard && (name === 'writeFile' || name === 'editFile') && result && result.ok !== false) {
1683
- recordWrite(guard, args && args.file_path);
1684
- }
1685
- return result;
1686
- }
1687
-
1688
- async function gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal }) {
1689
- const { name } = call;
1690
- // Same normalisation as guardedExecute, and for the same reason one layer
1691
- // up: the diff the user approves is rendered from this path, the hash guard
1692
- // re-reads it, and recordWrite claims it. All three must mean one file.
1693
- const normalized = normalizeToolArgs(T, name, call.args, toolCtx || {});
1694
- if (!normalized.ok) return { ok: false, error: normalized.error };
1695
- const args = normalized.args;
1696
- if (!T.MUTATING_TOOLS.has(name)) return guardedExecute(name, args, toolCtx);
1697
- if (!confirmModeEnabled()) return guardedExecute(name, args, toolCtx);
1698
- if (sessionAllows(rootSessionId, name)) return guardedExecute(name, args, toolCtx);
1699
- // Already refused in this conversation: refuse again WITHOUT raising a
1700
- // second card. Before this, the model's retry after a denial re-prompted
1701
- // the user for the same tool — one "no" produced a card per round for up
1702
- // to maxRounds rounds, each one a billed provider call re-sending the
1703
- // whole conversation. Checked after the confirm-mode short-circuit so
1704
- // turning the gate off still overrides an earlier refusal.
1705
- if (sessionDenies(rootSessionId, name)) return { ok: false, error: denialText(name) };
1706
-
1707
- let preview = null;
1708
- if (name === 'writeFile' || name === 'editFile') {
1709
- preview = T.previewMutation(name, args, toolCtx || {});
1710
- if (!preview.ok) return { ok: false, error: preview.error };
1711
- }
1712
-
1713
- const decision = await requestApproval(rootSessionId, rootOnDelta, signal, {
1714
- tool: name,
1715
- args,
1716
- diff: preview && preview.diff,
1717
- });
1718
-
1719
- // Only a click is remembered. 'cancel' (aborted turn / nobody able to
1720
- // answer) refuses this call but must not write a durable "no" the user
1721
- // never gave.
1722
- if (decision === 'deny') {
1723
- denyForSession(rootSessionId, name);
1724
- return { ok: false, error: denialText(name) };
1725
- }
1726
- if (decision !== 'session' && decision !== 'once') {
1727
- return { ok: false, error: `${name} was not executed — the request was cancelled.` };
1728
- }
1729
- if (decision === 'session') allowForSession(rootSessionId, name);
1730
-
1731
- if (preview) {
1732
- const res = T.applyChecked(name, args, preview, toolCtx || {});
1733
- // Recorded on the same condition as guardedExecute's path: only a write
1734
- // that landed is this session's. (The previous form returned here
1735
- // unconditionally, making every line below it unreachable — the
1736
- // approved-write path recorded nothing at all.)
1737
- if (res && res.ok !== false && toolCtx && toolCtx.guard) {
1738
- recordWrite(toolCtx.guard, args && args.file_path);
1739
- }
1740
- return res;
1741
- }
1742
- return guardedExecute(name, args, toolCtx);
1743
- }
1744
-
1745
- async function listClasses() {
1746
- return CLASSES.map((c) => {
1747
- if (c.class === 'aegis') {
1748
- return { ...c, configured: Boolean(aegis.apiKey) };
1749
- }
1750
- if (c.class === 'byok') {
1751
- // Configured means "this host could actually spend a key for at least
1752
- // one provider" — byok holds one row per provider (byokNamespace), so
1753
- // there is no single baseURL+key pair to report. A row whose key lives
1754
- // in `~/.aegiscode/.env` counts: that is the whole point of reading the
1755
- // file, and calling it unconfigured would send the user to a Settings
1756
- // row they do not need. A stored key still short-circuits, so an install
1757
- // with no env file pays one lookup per stored row and nothing else.
1758
- //
1759
- // The authoritative per-provider answer is `listModels`, which has the
1760
- // server's catalog and so can name a provider the user has never opened
1761
- // Settings for. This one can only see providers with a stored row.
1762
- const rows = settings.list() || [];
1763
- const anyConfigured = rows.some((s) => {
1764
- if (!s || typeof s.provider !== 'string' || !s.provider.startsWith('byok:')) return false;
1765
- if (s.configured) return true;
1766
- return Boolean(providerKeyFromEnv(s.provider.slice(BYOK_NAMESPACE_PREFIX.length)));
1767
- });
1768
- return { ...c, configured: anyConfigured };
1769
- }
1770
- if (c.class === 'local') {
1771
- // Always "configured": this class needs no credential at all, which is
1772
- // the entire reason it is free. Whether a daemon is actually listening
1773
- // is a different question, asked where the answer belongs — in
1774
- // listModels, next to the model list the user is looking at, so the
1775
- // state reads "start the daemon" instead of "go and configure
1776
- // something", which is what an unconfigured row would say.
1777
- return { ...c, configured: true };
1778
- }
1779
- if (c.class === 'pro') {
1780
- // Configured means "there is a Claude Code subscription to spend": a
1781
- // credential file with a token in it. Deliberately NOT gated on the
1782
- // `claude` binary being on PATH as well — that is a separate state with
1783
- // its own remedy, and folding the two together would answer "sign in"
1784
- // to someone who is signed in and merely missing the CLI.
1785
- const status = claudePro.claudeProStatus({ env: process.env });
1786
- const seam = claudePro.seamAvailable();
1787
- return { ...c, configured: status.loggedIn, status, seam };
1788
- }
1789
- // Unreachable while CLASSES lists only aegis + byok + local + pro; kept so
1790
- // a future class added without a status rule reads as unconfigured rather
1791
- // than silently appearing ready (the "no saved key" fallback shape).
1792
- return { ...c, configured: false };
1793
- });
1794
- }
1795
-
1796
- async function listModels(cls) {
1797
- if (cls === 'aegis') {
1798
- // The catalog is behind the account's key: GET /api/v1/models answers
1799
- // `401 {"error":{"message":"No API key"}}` without one (verified against
1800
- // aegiscloud.org). Aegis Cloud is the *default* class, so firing the call
1801
- // anyway painted a raw "listModels failed: … 401" over the default model
1802
- // picker for every user who had just installed the app and not yet
1803
- // pasted a key — the one state where the UI must say what unblocks it and
1804
- // not what went wrong. Report the missing key as a state (`needsKey`) and
1805
- // let the renderer invite the user to connect; nothing else about the
1806
- // class changes, and the model dropdown keeps its "server default (auto)"
1807
- // entry so the class is usable the moment a key lands.
1808
- if (!aegis.apiKey) return { class: cls, models: [], needsKey: true };
1809
- const data = await aegis.listModels();
1810
- // The whole catalog, aliases folded — see the rule above. What the list
1811
- // contains does not touch `needsKey` or the renderer's per-class hint.
1812
- return {
1813
- class: cls,
1814
- // One call, because the folding has to see the payload's own `alias_of`
1815
- // bookkeeping: a pre-collapsed row IS the selection, so a renderer must
1816
- // not filter it back out as a hidden alias, and folding what has already
1817
- // been folded would leave a renamed tier (`nexus-brain-v2`, an alias OF
1818
- // the brain under a spelling this release has never seen) on screen.
1819
- models: offerableCatalog(normalizeCatalog(data && data.models)),
1820
- };
1821
- }
1822
- if (cls === 'byok') {
1823
- // The server's catalog names every provider it accepts a key for, the
1824
- // models each unlocks, and whether an AEGIS account key is even needed
1825
- // to ask (it is not — the catalog answers an anonymous request).
1826
- // Deliberately NOT gated on aegis.apiKey the way the pooled class above
1827
- // is: BYOK's whole point is a caller who brings their own credential, and
1828
- // hiding the catalog would hide the answer to "which key do I go and get"
1829
- // from exactly the person deciding whether to bother. Nothing here
1830
- // enforces billing either: the desktop is one client of a route that is
1831
- // unauthenticated by design, so refusing in this process would stop
1832
- // exactly one host out of many. The relay owns that decision, and reports
1833
- // it via `fee.require_balance` below.
1834
- let providers = [];
1835
- let fee = null;
1836
- // Did the CATALOG itself fail to arrive, as opposed to arriving empty?
1837
- // The two are different states and the picker must not confuse them: a
1838
- // 5xx / offline relay used to fall into the bare `catch` below and hand
1839
- // back `providers: []`, which reads on screen exactly like an account
1840
- // with nothing configured — while the user's provider row and their
1841
- // `models.json` declaration sat intact on disk. Reported instead, the
1842
- // same way the 'local' branch reports `listed: false` for a tag list
1843
- // that did not arrive.
1844
- let providersFailed = false;
1845
- let providersError = null;
1846
- try {
1847
- const data = await aegis.byokProviders();
1848
- // The server's catalog, plus the ids it does not name but the vendor
1849
- // serves and the relay will forward (`client/byok-catalog.js`, shared
1850
- // with the CLI so both hosts offer the same rows). Applied HERE, at the
1851
- // single point where the payload enters this engine, so every consumer
1852
- // of `providers` — the model list built just below, the renderer's
1853
- // per-provider Settings rows, and the CLI's own `/byok` listing when it
1854
- // runs on this engine — sees one list instead of three opinions.
1855
- // Three layers, most specific last, exactly as the CLI composes them:
1856
- // the list this package shipped, then whatever the server's cached
1857
- // catalog adds, then the ids the user declared themselves. All three
1858
- // append only what is missing and never invent a provider, so the order
1859
- // decides only which layer wins a collision.
1860
- providers = withUserModels(
1861
- withCatalog(withByokAdditions((data && data.providers) || [])),
1862
- );
1863
- // The handling fee AEGIS adds on top of the caller's vendor bill. It is
1864
- // the server's own published rate (services/pricing.price_byok_call) and
1865
- // is passed through untouched — never re-derived here, because a client
1866
- // that hardcodes a fee is a client that can disagree with the ledger.
1867
- // Absent until the server publishes one, and the UI must then say
1868
- // nothing rather than show a guess.
1869
- fee = (data && data.fee) || null;
1870
- } catch (err) {
1871
- // Keep the empty list (nothing to offer) but SAY why, so the renderer
1872
- // can distinguish "catalog unreachable" from "catalog said none". The
1873
- // message is carried rather than a boolean alone because the two cases
1874
- // need different copy: offline wants a retry, a server error wants the
1875
- // status. `err.message` is the transport's own text, already shaped
1876
- // elsewhere in this file.
1877
- providers = [];
1878
- providersFailed = true;
1879
- providersError = (err && err.message) || String(err);
1880
- }
1881
- const models = [];
1882
- for (const p of providers) {
1883
- if (!p || !p.id) continue;
1884
- const rowCfg = settings.get(byokNamespace(p.id)) || {};
1885
- // A key from `~/.aegiscode/.env` makes the provider usable, so it must
1886
- // read as configured here — this is the flag `needsProviderKey` is built
1887
- // on, and the one the renderer's per-provider rows mirror. Reporting it
1888
- // unconfigured while `chat()` happily spends the env key is exactly the
1889
- // "no saved key" contradiction this file removes.
1890
- const envRec = providerKeyRecord(p.id);
1891
- const fromEnv = envRec.key || '';
1892
- const rawModels = Array.isArray(p.models) ? p.models : [];
1893
- for (const m of rawModels) {
1894
- const modelId = typeof m === 'string' ? m : m && m.id;
1895
- if (!modelId) continue;
1896
- models.push({
1897
- id: `${p.id}:${modelId}`,
1898
- label: `${p.label || p.id} — ${modelId}`,
1899
- provider: p.id,
1900
- configured: Boolean(rowCfg.configured || fromEnv),
1901
- // Why a row with no usable key is keyless, when the env file refused
1902
- // the value it was given rather than never being given one. Carried
1903
- // on the row because the renderer's per-provider line is the only
1904
- // place the user can see it before they send a turn. Null when there
1905
- // is nothing to explain (a saved key, or no env value at all).
1906
- keyRejected: envRec.rejected || null,
1907
- });
1908
- }
1909
- }
1910
- return {
1911
- class: cls, models, providers,
1912
- needsProviderKey: models.length > 0 && !models.some((m) => m.configured),
1913
- needsAegisKey: !aegis.apiKey,
1914
- fee,
1915
- // True only when the catalog did not arrive — never merely because it
1916
- // arrived with no providers. `withUserModels` never fabricates a
1917
- // provider, so this list is the same either side of the fold above.
1918
- providersFailed,
1919
- providersError,
1920
- // Declarations in `models.json` naming a provider the catalog does not
1921
- // list — a typo, or a provider renamed/dropped server-side. `withUserModels`
1922
- // deliberately does NOT invent a row for them (it would 401 on its first
1923
- // turn), but silence is the other wrong answer: the model stays in the
1924
- // file and the user is entitled to know the picker cannot show it.
1925
- // Carried as the ids alone; the renderer names them.
1926
- unmatchedProviders: unmatchedUserProviders(providers),
1927
- };
1928
- }
1929
- if (cls === 'local') {
1930
- // No credential to check, so the only question is whether anything is
1931
- // listening. The probe never throws (local.js), so a machine with no
1932
- // daemon reports a STATE and the renderer invites the user to start one —
1933
- // the same shape as the pooled class's `needsKey` above, and for the same
1934
- // reason: an install in its default state must be told what unblocks it,
1935
- // not shown a transport error.
1936
- const cfg = settings.get('local') || {};
1937
- const baseURL = cfg.baseURL || localT.DEFAULT_BASE;
1938
- const status = await localT.probe(baseURL);
1939
- if (!status.running) {
1940
- return { class: cls, models: [], baseURL: status.baseURL, needsDaemon: true };
1941
- }
1942
- // The daemon is up. Its tag list is Ollama's native endpoint, so a
1943
- // non-Ollama server on the same box (llama.cpp, LM Studio, vLLM) answers
1944
- // 404 here — recoverable, and it must not cost the class its usability:
1945
- // the renderer falls back to letting the user type a model name, and the
1946
- // transport itself never needs this call.
1947
- let tags = [];
1948
- let listed = true;
1949
- try {
1950
- tags = await localT.listTags(baseURL);
1951
- } catch {
1952
- listed = false;
1953
- }
1954
- return { class: cls, models: tags, baseURL: status.baseURL, listed };
1955
- }
1956
- if (cls === 'pro') {
1957
- // The model list is the CLI's OWN aliases. The subscription does not
1958
- // expose an id list this process may query, and inventing full model
1959
- // names here would be exactly the "client names a model the transport
1960
- // cannot address" defect — `claude --model` takes these aliases, so these
1961
- // are the rows (claude-pro.js PRO_MODELS).
1962
- const status = claudePro.claudeProStatus({ env: process.env });
1963
- const models = claudePro.PRO_MODELS.map((m) => ({
1964
- id: m.id,
1965
- label: m.label,
1966
- note: m.note,
1967
- configured: status.loggedIn,
1968
- }));
1969
- return {
1970
- class: cls,
1971
- models,
1972
- // Nothing to key: the subscription IS the credential, and there is no
1973
- // AEGIS spend on this class for the relay's balance gate to consider.
1974
- needsProviderKey: false,
1975
- needsAegisKey: false,
1976
- subscription: status.subscription,
1977
- loggedIn: status.loggedIn,
1978
- credentialFile: status.file,
1979
- // A shell `ANTHROPIC_API_KEY` too short to be a credential makes the CLI
1980
- // prefer that name over the subscription, so a signed-in machine ran
1981
- // turns as "API key: he". The child is fixed either way (claude-pro.js
1982
- // childEnvPlan); reported here so the picker can name the var instead of
1983
- // leaving it to be discovered from `claude auth status` by hand.
1984
- shadowed: status.shadowed || null,
1985
- seam: claudePro.seamAvailable(),
1986
- };
1987
- }
1988
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
1989
- // and 'pro', all returned above. Thrown rather than falling through to an
1990
- // empty list, because "no models" is a state the renderer renders as a
1991
- // normal empty picker — an unknown class would look like a
1992
- // configured-but-empty account instead of the bug it is. Same shape as
1993
- // dispatch's tail.
1994
- throw new Error(
1995
- `listModels: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
1996
- );
1997
- }
1998
-
1999
- /**
2000
- * The environment facts the model needs to stop asking which OS it is on.
2001
- * Everything is best-effort: a missing field is simply omitted.
2002
- */
2003
- function envFor(payload) {
2004
- return hostEnv(env || {}, (payload && payload.env) || {}, payload);
2005
- }
2006
-
2007
- /**
2008
- * The directories the Claude Pro child is additionally allowed to work in,
2009
- * for a turn running in `cwd` — the Pro path's half of "the model is not
2010
- * walled into one subdirectory".
2011
- *
2012
- * Two candidates, and only two:
2013
- *
2014
- * · the repository root, from `git-scope.js` — the module the turn guard and
2015
- * the queue already share, so "where does this work happen" is answered in
2016
- * one place rather than re-derived here;
2017
- * · the project data directory (`$AEGISCODE_HOME`, else `~/.aegiscode`),
2018
- * because a turn asked to look at its own session/queue/memory files is
2019
- * otherwise asked to read a path outside its sandbox — the second real
2020
- * report of this wall.
2021
- *
2022
- * Resolved at CALL time, not at load: `git-scope.js` is staged beside this
2023
- * file in both layouts (one/scripts/predist.mjs), and a checkout that has not
2024
- * been staged must still load the engine. A missing module therefore degrades
2025
- * to "no widening", which is the pre-existing behaviour — never to a second,
2026
- * local implementation of git root discovery.
2027
- *
2028
- * Deduplicated against `cwd` itself: telling the child that its own working
2029
- * directory is also an extra directory is noise in the argv, in the record and
2030
- * in the run-log line, and noise is where a real widening hides.
2031
- */
2032
- function proAddDirs(cwd) {
2033
- const out = [];
2034
- // Separator-normalised comparison only — this file deliberately does not
2035
- // grow a `node:path` dependency at module scope for two string checks, and
2036
- // both candidates arrive absolute from modules that already resolved them.
2037
- const norm = (p) => String(p || '').replace(/[\\/]+$/, '');
2038
- const here = norm(cwd);
2039
- const add = (dir) => {
2040
- const abs = norm(dir);
2041
- if (!abs || abs === here || out.includes(abs)) return;
2042
- out.push(abs);
2043
- };
2044
- let scope = gitScope;
2045
- if (scope === undefined) {
2046
- try {
2047
- scope = require('./git-scope.js');
2048
- } catch {
2049
- scope = null;
2050
- }
2051
- }
2052
- try {
2053
- if (scope && typeof scope.gitRoot === 'function') add(scope.gitRoot(cwd));
2054
- } catch {
2055
- /* not a repo, or git is absent: no wider tree to grant */
2056
- }
2057
- try {
2058
- if (credentialsLib && typeof credentialsLib.aegisHome === 'function') add(credentialsLib.aegisHome());
2059
- } catch {
2060
- /* no data directory resolved: nothing to add */
2061
- }
2062
- return out;
2063
- }
2064
-
2065
- /** One transport round for the chosen class. */
2066
- async function dispatch(cls, opts) {
2067
- if (cls === 'aegis') {
2068
- // `undefined` = "leave the model id's own default alone" (a real user
2069
- // turn on the pooled class: the selected Nexus id is what decides, so
2070
- // today's behaviour is unchanged). `false` = an explicit single provider
2071
- // call, for a pass that is a continuation rather than a new
2072
- // investigation. `true` = the autonomous fan-out.
2073
- const brainFlag = opts.singlePass ? false : opts.autonomous ? true : undefined;
2074
- return aegis.chatCompletion({
2075
- prompt: opts.prompt,
2076
- system: opts.system,
2077
- messages: opts.messages,
2078
- model: opts.model,
2079
- mode: opts.mode,
2080
- // Only a cap the caller STATED travels; an effort-derived one does not.
2081
- // The server derives its own budget from `effort` (aegis1 pass_budgets
2082
- // splits its ladder across workers + synthesis), so forwarding the
2083
- // derived number states one decision twice — and the copies had already
2084
- // drifted: 974adc5 doubled aegis1's ladder while this side stood still,
2085
- // leaving the client capping below the budget it displayed. The cap was
2086
- // never the one the renderer showed either (the Max tokens dropdown
2087
- // that used to claim a figure for the pooled class is gone — see
2088
- // desktop/renderer/budget.js). Omitting the field is
2089
- // what tells aegis1 "no cap stated — let effort decide", the same
2090
- // contract the upstream engine sends.
2091
- //
2092
- // A cap the caller DID state is a different thing, and dropping it was
2093
- // a bug: aegis1 reads a body max_tokens as a ceiling over its ladder,
2094
- // so omitting it does not bound the call — it grants the full top rung
2095
- // instead. A deliberate 4096 would have run at 32768, which is the same
2096
- // "only ever raise the caller's ceiling" failure the old
2097
- // Math.max(Number(maxTokens) || 0, EFFORT_TOKEN_BUDGET[eff]) had.
2098
- maxTokens: opts.statedMaxTokens,
2099
- stream: opts.stream !== false,
2100
- // The pooled (Nexus) brain is streamed, and an OpenAI-compatible SSE
2101
- // stream reports no token usage unless asked. Without this the Aegis
2102
- // Cloud class — the desktop's default — was the one class that answered
2103
- // with text but never a token count, so a pooled turn's spend was
2104
- // invisible here while the same model through the MCP path reported it.
2105
- includeUsage: true,
2106
- onStream: opts.onDelta,
2107
- // Extended-reasoning trace (the fan-out's worker findings). Its own
2108
- // channel so it never counts as answer text — see vendor/aegis.js.
2109
- onReasoning: opts.onReasoning,
2110
- // A brain fan-out is silent between passes; give it room (see
2111
- // AUTONOMOUS_IDLE_TIMEOUT_MS). Undefined elsewhere -> 60s default.
2112
- idleTimeoutMs: opts.idleTimeoutMs,
2113
- signal: opts.signal,
2114
- // aegis_recall — the read half of aegis_memory, and the only half a
2115
- // client on this engine should send.
2116
- //
2117
- // aegis_memory is both halves: it injects the account's synced memory
2118
- // into context AND persists this turn back into it, charging sync
2119
- // quota for the write. That pairing is right for aegis-online, whose
2120
- // chat has nowhere else to live. It is wrong here, because this engine
2121
- // is shared by the GUI and the CLI (cli/src/deps.js loads this file):
2122
- // either would be billed for every "hey" and would fill the user's
2123
- // memory with greetings. Verified against aegis1 app.py: every
2124
- // write-back site (the note/upsert calls) is gated on aegis_memory,
2125
- // and aegis_memory implies aegis_recall there — so dropping the write
2126
- // half leaves /online unchanged and costs nothing on the read side.
2127
- //
2128
- // Writing is still available, explicitly: the aegis_memory_save tool
2129
- // (mcp/tools.js; the CLI exposes it as /memory). Recall on every turn,
2130
- // store only what the user asks for — which is what the upstream engine's
2131
- // own cross-session memory does, and what this comment claimed to
2132
- // match while sending both halves.
2133
- //
2134
- // Recall was previously unreachable for a client that would not pay
2135
- // for it: services/tiered_recall.py only ran behind a flag that also
2136
- // bought a write, so the tiered path existed with no caller able to
2137
- // afford it. The split is what makes it reachable. The DEEP tier of the
2138
- // same read is a third flag with its own price — see `opts.recallDeep`
2139
- // below, which is off unless the session opted in.
2140
- extra: {
2141
- aegis_recall: true,
2142
- // The DEEP tier of that read — brain corrections plus the semantic
2143
- // answer cache — is not the same price, so it does not ride along.
2144
- // aegis1 app.py:8367 reads `aegis_recall_deep` (or the
2145
- // X-AEGIS-Recall-Deep header) and services/brain_memory.py
2146
- // find_cached_answer embeds the query: one provider embedding per
2147
- // turn, metered. The server deliberately implies it from
2148
- // `aegis_memory` and NOT from `aegis_recall`, so that a terminal
2149
- // client can buy the cheap read without the embedding.
2150
- //
2151
- // This client is that terminal client (the CLI loads this file via
2152
- // cli/src/deps.js), so it must not opt itself in: the flag is sent
2153
- // only when the SESSION asked for it — CLI `/memory-deep on`, a
2154
- // desktop payload with `recallDeep: true` — and it defaults false
2155
- // everywhere. It also travels only on the user's own turn
2156
- // (`opts.recallDeep` is cleared for every other dispatch below): a
2157
- // tool round, the doubled-budget retry and the write-up re-dispatch
2158
- // all re-send a context whose embedding the first round already
2159
- // bought, which would turn one embedding per turn into one per round.
2160
- ...(opts.recallDeep ? { aegis_recall_deep: true } : {}),
2161
- session: opts.sessionId,
2162
- // The fan-out is opt-in per dispatch. `brain` is sent EXPLICITLY
2163
- // whenever this dispatch is not the autonomous one, because the
2164
- // model id this class sends (``nexus-brain``) enables the pooled
2165
- // brain on its own: without the flag a continuation pass — the
2166
- // doubled-budget retry, or the "write up what you already found"
2167
- // re-dispatch — silently re-ran the whole workers+1 fan-out for a
2168
- // pass whose documented cost is a single request. aegis1
2169
- // services/pool_brain.py parse_brain_request honours the opt-out.
2170
- ...(brainFlag === undefined ? {} : { brain: brainFlag }),
2171
- // An opted-out pass is also told WHICH band to run on. A single call
2172
- // on a brain model id infers its band from the id and lands on
2173
- // "fast" (the cheapest id in the pool); "brain" is the band the
2174
- // workers themselves run on (cheapest model that can think). Same
2175
- // model as the fan-out, one sample instead of four — otherwise
2176
- // dropping the fan-out would have quietly changed the model too.
2177
- ...(brainFlag === false ? { mode: 'brain' } : {}),
2178
- // `effort` is the budget rung, and it is sent whenever the caller has
2179
- // one — not only alongside a fan-out. The fan-out is triggered by the
2180
- // model id (this class sends ``nexus-brain``), so a caller that never
2181
- // ticked "work autonomously" still ran a pooled call and had no way to
2182
- // say how big it should be: the server fell through to its own default
2183
- // rung. That is how a one-word prompt came to reserve the top of the
2184
- // ladder. A single-pass pass carries it too — inert on that path, but
2185
- // it keeps the request honest about what it asked for.
2186
- ...(opts.effort ? { effort: opts.effort } : {}),
2187
- // Only meaningful with a running fan-out — aegis1 services/pool_brain.py
2188
- // parse_brain_request reads `workers` straight off the body and clamps
2189
- // it itself (MAX_WORKERS), so no client-side validation here.
2190
- ...(brainFlag === true && opts.workers ? { workers: opts.workers } : {}),
2191
- // The pool forwards `tools` to the provider and returns tool_calls
2192
- // (aegis1 app.py:7765 → provider, pool_brain synthesis keeps them).
2193
- ...(opts.tools.length ? { tools: opts.tools } : {}),
2194
- ...(opts.toolChoice ? { tool_choice: opts.toolChoice } : {}),
2195
- },
2196
- // aegis1's agent-key gate (services/agent_gate.py) 403s a pooled turn
2197
- // whose `tools` names a code-capable verb (writeFile/editFile/exec —
2198
- // this engine's builtin set — normalise to the server's CODE_TOOLS
2199
- // entries) unless X-AEGIS-Agent-Key is attached. `AEGIS_API_KEY` says
2200
- // who pays; this says who may change code, and is deliberately a
2201
- // separate credential (see agent_gate.py's module docstring). Read
2202
- // from `~/.aegiscode/.env` via the same loadEnvFile() both hosts
2203
- // already run at startup — no new key store. Absent by default: an
2204
- // account with no agent key simply gets the same 403 as before,
2205
- // scoped to turns that actually carry tools.
2206
- agentKey: opts.tools.length ? (process.env.AEGIS_AGENT_KEY || '').trim() || undefined : undefined,
2207
- });
2208
- }
2209
-
2210
- if (cls === 'byok') {
2211
- // opts.model is still the compound "provider:model" id here — the
2212
- // relay wants them split (a `provider` field plus a bare `model`).
2213
- // opts.apiKey is the PROVIDER key resolved by chat() above (from the
2214
- // byokNamespace(provider) settings row), never the account's own AEGIS
2215
- // key — that one is baked into the `aegis` client already and attached
2216
- // automatically by byokChatCompletion() as X-AEGIS-Key so the account
2217
- // gets billed the handling fee; see client/aegis.js.
2218
- const { provider, model: bareModel } = splitByokModel(opts.model);
2219
- // Repair a retired/renamed picker id into the id this provider actually
2220
- // serves, BEFORE it reaches the wire or the effort table. A picker label
2221
- // and a wire id are different facts, and only the picker is free to drift:
2222
- // DeepSeek displays "DeepSeek-V4.1-Flash" but serves it as
2223
- // `deepseek-flash`, so selecting the entry whose id is
2224
- // `deepseek-v4.1-flash` sent an id the API rejects with
2225
- // "The supported API model names are deepseek-flash, deepseek-v4-pro".
2226
- // That 400 killed the user's first turn for a model that was, by display
2227
- // name, one DeepSeek really serves. Applying it here — and through the
2228
- // SAME shared table the CLI reads — is what keeps both hosts repairing the
2229
- // id identically instead of each growing its own map. A canonical id maps
2230
- // to itself, so this is a no-op for every provider without an entry.
2231
- const wireModel = canonicalModelId(provider, bareModel);
2232
- // Translate the rung for THIS vendor once, and carry the verdict rather
2233
- // than a bare level: the relay validates strictly upstream and the field
2234
- // name is not portable (DeepSeek's `/anthropic` transport takes `effort`,
2235
- // OpenAI-shaped vendors take `reasoning_effort`). Undefined for a family
2236
- // with no dialect, which the transport then omits entirely.
2237
- const effort = nativeEffort(provider, wireModel, opts.effort);
2238
- try {
2239
- return await aegis.byokChatCompletion({
2240
- provider,
2241
- model: wireModel,
2242
- providerKey: opts.apiKey,
2243
- // Only meaningful for provider "custom" (aegis1 reads it ONLY on
2244
- // that id) — forwarded unconditionally anyway, same as the other
2245
- // fields above, rather than special-cased per provider here.
2246
- // `cfg` is this provider's settings row (byokNamespace(provider)),
2247
- // the same row /byok-key and /model-add write.
2248
- baseURL: opts.cfg && opts.cfg.baseURL,
2249
- prompt: opts.prompt,
2250
- system: opts.system,
2251
- messages: opts.messages,
2252
- maxTokens: opts.maxTokens,
2253
- // aegis1's byok_chat_completions has read and forwarded `tools`/
2254
- // `tool_choice` since 926069b (2026-09-10) — this call simply never
2255
- // sent them, so every BYOK turn (DeepSeek, Anthropic, OpenAI alike)
2256
- // ran with no write/exec/editFile schema at all. A model told in its
2257
- // system prompt that it "writes and edits files" but never given the
2258
- // JSON shape to do so improvises a DeepSeek-native DSML call from
2259
- // prose alone when it's confident, and falls back to prose ADVICE
2260
- // (a shell script to run by hand) when it isn't — which is exactly
2261
- // the bug this line closes.
2262
- tools: opts.tools,
2263
- toolChoice: opts.toolChoice,
2264
- // Native effort knob, field and level both from the dialect table.
2265
- // `bareModel` is already provider-less, so it matches the dialect
2266
- // regexes without further stripping. Both wire channels are live, and
2267
- // which one is used is the dialect's decision, not this call site's:
2268
- // DeepSeek's `/anthropic` transport takes `effort` (aegis1 gates it on
2269
- // provider_id == "deepseek" and the adapter nests it as
2270
- // `output_config.effort`), while the OpenAI-shaped vendors take
2271
- // `reasoning_effort`. Routing on the field name is what keeps a
2272
- // dialect from being silently dropped here — the previous form
2273
- // forwarded only `reasoning_effort`, so turning DeepSeek's dialect
2274
- // over to `effort` would have died at this line.
2275
- effort: effort && effort.field === 'effort' ? effort.level : undefined,
2276
- reasoningEffort: effort && effort.field === 'reasoning_effort' ? effort.level : undefined,
2277
- stream: true,
2278
- onStream: opts.onDelta,
2279
- signal: opts.signal,
2280
- });
2281
- } catch (e) {
2282
- // The relay's own balance gate (aegis1 `AEGIS_BYOK_REQUIRE_BALANCE`,
2283
- // app.py `byok_chat_completions`) answers 402 with a body aimed at an
2284
- // API consumer — "Insufficient balance. Top up to continue using
2285
- // BYOK." Shown raw in a chat transcript that reads as a crash rather
2286
- // than a bill, so the one thing the user has to DO is said here, in the
2287
- // hosts' own voice. The status is preserved so every existing caller
2288
- // (the CLI's error painter, the desktop turn guard) still sees a 402.
2289
- //
2290
- // The provider key is untouched by this: it is the caller's own and it
2291
- // is still valid. What ran out is the AEGIS balance the handling fee
2292
- // is billed against, which is the whole reason this lane has a fee.
2293
- if (e && e.status === 402) {
2294
- const err = new Error(
2295
- 'byok: this account has no AEGIS balance left, and the BYOK handling fee is ' +
2296
- 'billed there — your provider key is still valid, this is not a key problem. ' +
2297
- 'Top up the account, then try again (or /class aegis to use the pooled lane).'
2298
- );
2299
- err.status = 402;
2300
- throw err;
2301
- }
2302
- throw e;
2303
- }
2304
- }
2305
-
2306
- if (cls === 'local') {
2307
- // The one class whose turn leaves this machine for hardware the user
2308
- // owns. `baseURL` comes from the 'local' settings row and is re-checked
2309
- // by the transport on every call (local.js `remoteRefusal`), so a row
2310
- // hand-edited to a public address after it was saved still cannot be
2311
- // dialed — the engine is not the only gate, it is the first one.
2312
- const baseURL = (opts.cfg && opts.cfg.baseURL) || localT.DEFAULT_BASE;
2313
- const call = (useTools) =>
2314
- localT.chat({
2315
- baseURL,
2316
- model: opts.model,
2317
- prompt: opts.prompt,
2318
- system: opts.system,
2319
- messages: opts.messages,
2320
- maxTokens: opts.maxTokens,
2321
- signal: opts.signal,
2322
- onDelta: opts.onDelta,
2323
- ...(useTools && opts.tools.length ? { tools: opts.tools, toolChoice: opts.toolChoice } : {}),
2324
- });
2325
- try {
2326
- return await call(true);
2327
- } catch (e) {
2328
- // An older daemon 400s on `tools` it does not understand. Sending none
2329
- // gets the turn answered — without tool access, which is worse than the
2330
- // full loop and far better than a 400 the user cannot act on. Retried
2331
- // once, and only for that one status: a 400 about the model name or the
2332
- // message shape is not fixed by dropping schemas, and retrying it would
2333
- // send the same broken turn twice.
2334
- if (opts.tools.length && e && e.status === 400) return call(false);
2335
- throw e;
2336
- }
2337
- }
2338
-
2339
- if (cls === 'pro') {
2340
- // The user's own Claude subscription. This transport is unlike the other
2341
- // three in a way that decides its whole shape: the `claude` child runs
2342
- // its OWN agent loop, with its own tools, so there is no `tools` argument
2343
- // to send and none is invented — passing this engine's schemas would ask
2344
- // a process that already has a tool loop to re-run our tools inside it.
2345
- // `opts.messages`/`opts.tools` are deliberately unused here for that
2346
- // reason, and the dispatch returns the child's own final answer.
2347
- //
2348
- // ── … and the consequence of that, which used to be a bug ─────────────
2349
- //
2350
- // Because the transcript is NOT replayed into the child, the child's own
2351
- // session store was the only thing that could carry context between
2352
- // turns — and nothing ever told it to resume one. Every turn was a
2353
- // brand-new conversation: "Claude has no memory of this conversation"
2354
- // was literally true, and no amount of `messages` upstream could fix it,
2355
- // because they were dropped on purpose one paragraph above.
2356
- //
2357
- // So the child's reported session id is remembered per CONVERSATION and
2358
- // handed back as `--resume`. Keyed by the conversation (rootSessionId),
2359
- // never by `sessionId`: the CLI mints a fresh uuid per turn for
2360
- // cancellation, so keying by it would resume nothing, every turn.
2361
- //
2362
- // We deliberately do NOT pass `sessionId` (`--session-id`) to name the
2363
- // conversation upfront: the CLI's own `/new` mints `aegis-xxxxxxxx`,
2364
- // which is not a UUID the child accepts, and the child's self-minted id
2365
- // is authoritative anyway. It is read back off the `result` line instead.
2366
- const convKey = opts.sessionKey || opts.rootSessionId || opts.sessionId;
2367
- const remembered = convKey ? proSessions.get(convKey) : null;
2368
- // ── the sandbox the child is actually given ───────────────────────────
2369
- //
2370
- // A headless `claude` child resolves every relative path and every tool's
2371
- // root against the directory it was spawned in, so a turn started in a
2372
- // SUBDIRECTORY of the repo cannot read or run anything above it. Reported
2373
- // from this product for real: a session launched in `cli/` that needed
2374
- // `test/` came back with "I can't run outside the sandboxed directory
2375
- // `cli/`" — the model, not a bug in the tools, describing this boundary.
2376
- //
2377
- // The repo root is the right width: it is the tree the user opened, it is
2378
- // one directory (never a glob, never the home dir), and it is derived
2379
- // rather than guessed — `git-scope.js` is the module the turn guard and
2380
- // the queue already ask for "where is this work happening". Best-effort:
2381
- // outside a repo there is no wider directory to grant and the child keeps
2382
- // exactly the posture it had.
2383
- // The turn's own working directory rides on `opts.cwd` (threaded in by
2384
- // `chat()` as `turnCwd`), never on the enclosing scope's local — that
2385
- // reference is the exact `ReferenceError: turnCwd is not defined` this
2386
- // file already carries a regression case for.
2387
- const addDir = proAddDirs(opts.cwd);
2388
- //
2389
- // The permission half of the argv is NOT built here. It comes from
2390
- // resolvePosture() inside runClaudePro, through the one argv builder
2391
- // (one/src/child.js), so this host and AEGISONE's faces cannot disagree
2392
- // about what the child was allowed to do.
2393
- const proRes = await claudePro.runClaudePro({
2394
- // The re-ask round's instruction, when this round has none of its own.
2395
- // See proTurnPrompt(): without it every recovery round spawned the
2396
- // child with an empty prompt and the turn could never be recovered.
2397
- prompt: proTurnPrompt(opts),
2398
- model: opts.model && opts.model !== 'default' ? opts.model : undefined,
2399
- system: opts.system,
2400
- cwd: opts.cwd,
2401
- // The widened sandbox, threaded through to the ONE argv builder. A
2402
- // directory the engine could not derive (or that adds nothing, e.g. the
2403
- // turn already runs at the repo root) is simply absent from this list,
2404
- // and absent means "exactly the posture the child had before".
2405
- addDir,
2406
- // Carry the conversation, if we have one to carry.
2407
- resumeSessionId: remembered || undefined,
2408
- // The stored posture this host already reads for its own gate, handed
2409
- // to the resolver rather than re-read there — one answer per turn.
2410
- gate: typeof getConfirmMode === 'function' ? !getConfirmMode() : undefined,
2411
- signal: opts.signal,
2412
- onDelta: opts.onDelta,
2413
- onSpawn: (child, record) => {
2414
- // Rule 4's "recorded, never inferred": the child's real flags are
2415
- // reported on the same channel tool activity uses, so a Pro turn's
2416
- // transcript shows what it was allowed to do.
2417
- if (opts.onDelta && record) {
2418
- opts.onDelta({ delta: '', note: claudePro.childLine(record) });
2419
- }
2420
- void child;
2421
- },
2422
- });
2423
- // Remember the id the child reported, so the NEXT turn in this thread
2424
- // resumes this conversation. Recorded only on a turn that actually
2425
- // produced one: a failed turn must not overwrite a good id with
2426
- // `undefined` and silently turn the next turn into a new conversation.
2427
- if (convKey && proRes && proRes.sessionId && !proRes.error) {
2428
- proSessions.set(convKey, proRes.sessionId);
2429
- }
2430
- return proRes;
2431
- }
2432
-
2433
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
2434
- // and 'pro', all returned above. Thrown rather than falling through to a
2435
- // default transport, because a class that silently borrows another's wire
2436
- // format is this file's recurring failure mode.
2437
- throw new Error(
2438
- `dispatch: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
2439
- );
2440
- }
2441
-
2442
- async function chat(payload, onDelta) {
2443
- const cls = payload && payload.class;
2444
- const model = payload && payload.model;
2445
- // byok's model id is "provider:model" (see splitByokModel) — strip the
2446
- // provider prefix before pattern-matching, or a DeepSeek reasoning model
2447
- // selected under byok ("byok" model "deepseek:deepseek-v4-flash") never
2448
- // matches DEEPSEEK_REASONING_MODEL_RE's anchored pattern and silently
2449
- // gets no stated budget, which is exactly the "hidden CoT ate the whole
2450
- // default and returned nothing" failure this budget exists to prevent.
2451
- const reasoningModelId = cls === 'byok' ? splitByokModel(model).model : model;
2452
- const maxTokens = reasoningBudget(reasoningModelId, payload && payload.maxTokens, payload && payload.effort);
2453
- // The caller's OWN number, kept apart from `maxTokens` above. That one
2454
- // collapses two different facts into a single value — "the caller stated
2455
- // 4096" and "effort implies 32768" — and the pooled path must treat them
2456
- // differently. A stated cap is a liability ceiling the server honours
2457
- // downward (aegis1 pass_budgets: total = min(ladder, max_tokens x passes));
2458
- // an effort-derived one is the server's own arithmetic stated twice, and
2459
- // sending it is how the two copies came to disagree. So the pooled call
2460
- // forwards only what the caller actually asked for.
2461
- // ...and it is read through statedCapOf(), so a nested chat() that states
2462
- // the key overrides its own derived `maxTokens` instead of being mistaken
2463
- // for a caller who asked for that number (see statedCapOf).
2464
- const statedMaxTokens = statedCapOf(payload);
2465
- // "Work autonomously" — routes this call through aegis1's pool_brain
2466
- // worker fan-out (services/pool_brain.py: N reasoning workers + a
2467
- // synthesis pass) instead of a single provider call. UI-gated to the
2468
- // 'aegis' class only (see AUTONOMOUS_CLASS in app.js).
2469
- const autonomous = cls === 'aegis' && Boolean(payload && payload.autonomous);
2470
- // Opt-in only: the round-horizon dialog (requestRoundsAsk below) needs a
2471
- // live renderer on the other end of `rootOnDelta` able to answer it. The
2472
- // interactive CLI session sets this; the queue worker and `-p` one-shot
2473
- // runs never do (nobody is there to click), so they keep the old
2474
- // stop-and-record-session behaviour (sessionRounds below) untouched.
2475
- const roundsAsk = Boolean(payload && payload.roundsAsk);
2476
- const sessionId = (payload && payload.sessionId) || randomUUID();
2477
- // Recursion depth for the task tool: 0 for a real user turn, N+1 for a
2478
- // subagent spawned by depth N. Never set by an IPC caller — only by
2479
- // runSubagent's own recursive chat() call below.
2480
- const depth = Number.isInteger(payload && payload.depth) ? payload.depth : 0;
2481
- // The approval gate's identity for this whole conversation, regardless of
2482
- // depth: a real user turn defines it (defaults to its own sessionId); a
2483
- // subagent's nested chat() call always receives it explicitly from
2484
- // runSubagent below, so "allow for this session" means the same thing
2485
- // whether the call came from the top-level turn or three subagents deep.
2486
- const rootSessionId = (payload && payload.rootSessionId) || sessionId;
2487
- // Likewise, approval requests must always reach the ORIGINAL caller's
2488
- // stream — a subagent's own chat() call is invoked with a no-op onDelta
2489
- // (its tool activity/text is not streamed to the renderer), so without
2490
- // this a nested approval request would call that no-op and hang forever
2491
- // waiting for a response nobody can ever send.
2492
- const rootOnDelta = (payload && payload.rootOnDelta) || onDelta;
2493
-
2494
- // A pooled brain call streams each worker's finding as extended reasoning
2495
- // before the synthesis pass writes the visible answer. Forward it on its
2496
- // own channel so the renderer can show the fan-out working instead of an
2497
- // apparently idle bubble for the whole worker phase. Uses `onDelta` (not
2498
- // rootOnDelta) on purpose: a subagent's reasoning should be suppressed
2499
- // exactly as its text already is.
2500
- const onReasoning =
2501
- typeof onDelta === 'function' ? (text) => text && onDelta({ reasoning: text }) : undefined;
2502
-
2503
- const controller = new AbortController();
2504
- controllers.set(sessionId, controller);
2505
- const signal = controller.signal;
2506
-
2507
- // A caller can opt out of the agent loop entirely (`tools: false`) and get
2508
- // the old single-shot turn back. byok used to be forced into that same
2509
- // single-shot shape unconditionally: aegis1's byok relay had no
2510
- // tools/tool_choice parameter at all, so sending schemas would build a
2511
- // prompt promising tool access the transport silently dropped — the model
2512
- // would reason about exec/readFile and never see a result. That stopped
2513
- // being true at aegis1 926069b (2026-09-10, byok_chat_completions reads
2514
- // and forwards both), but this carve-out was never revisited, so every
2515
- // BYOK turn since kept running with no tool schema at all regardless —
2516
- // the model told in its own system prompt that it writes and edits files,
2517
- // and never given the JSON shape to do so. Reported live: asked to save a
2518
- // file to the Desktop, DeepSeek had no write tool to call and answered
2519
- // with a PowerShell script for the user to run by hand instead.
2520
- const toolsEnabled = !(payload && payload.tools === false);
2521
- const toolSchemas = toolsEnabled ? T.toolsFor({ includeSubagent: depth < MAX_SUBAGENT_DEPTH }) : [];
2522
- const toolChoice = (payload && payload.toolChoice) || null;
2523
-
2524
- const system = (payload && payload.system) || buildSystemPrompt(envFor(payload));
2525
- const history = Array.isArray(payload && payload.messages) ? payload.messages.filter(Boolean).slice() : [];
2526
- // Index into `history` of everything THIS turn added as opposed to what the
2527
- // caller brought with it. Reset after the resume rehydration below, so a
2528
- // restored transcript is never re-recorded as if this turn had produced it
2529
- // (which would double it on every interruption in a chain).
2530
- let historyStart = history.length;
2531
- let prompt = (payload && payload.prompt) || '';
2532
- // The user's OWN ask, frozen here before anything prepends to it. The
2533
- // resume preamble and every nudge below are engine text; scoping the
2534
- // mutation intent test to this value is what keeps "continued from a
2535
- // previous turn" from reading as an instruction to change a file.
2536
- const turnAsk = String(prompt || '');
2537
- // Dropped attachments turn the round-1 ask into an OpenAI content-part
2538
- // array. `prompt` stays the plain STRING (the paths/text the user sees and
2539
- // the value every string-shaped path below relies on — proTurnPrompt, the
2540
- // fold identity test, the truncation notes), while `promptContent` is what
2541
- // actually goes on the wire. They are equal for every turn with no drops,
2542
- // which is why an ordinary send behaves exactly as it did before.
2543
- // Capped HERE, not only in the renderer. The renderer refuses the ninth
2544
- // drop, but main must not depend on a peer for its own request size: the
2545
- // same payload reaching this function from anywhere else would put every
2546
- // image in one provider request.
2547
- const attachments = Array.isArray(payload && payload.attachments)
2548
- ? payload.attachments
2549
- .filter((a) => a && typeof a === 'object')
2550
- .slice(0, attachmentsModule.MAX_ATTACHMENTS)
2551
- : [];
2552
- let promptContent = attachments.length ? attachmentsModule.buildContent(prompt, attachments) : prompt;
2553
-
2554
- // Lazily start ONE shell session for this turn; the exec tool shares it so
2555
- // cd/env/state persist across calls. Only spawned if exec actually runs,
2556
- // and always disposed when the turn ends.
2557
- let shell = null;
2558
- const getShell = () => shell || (shell = new ShellSession({ cwd: envFor(payload).cwd }));
2559
- // The turn's working directory. It rides on every tool frame because a
2560
- // tool row's args are the command or the path — never the directory the
2561
- // command runs in — which left "where is it working in" unanswerable from
2562
- // the transcript. It also has to ride on `toolCtx`, which is what
2563
- // normalizeArgs (tools.js) actually resolves a RELATIVE readFile/writeFile/
2564
- // editFile/listDir/glob/grep path against — omitting `cwd` here meant that
2565
- // resolution fell back to the HOST PROCESS's own cwd (the Electron install
2566
- // dir off Linux, per baseDir()'s comment in tools.js, which fixed this for
2567
- // the no-path default but never for a path the model actually supplied).
2568
- // `desktopdir` rides the same way so resolvePath can correct a model's
2569
- // literal "Desktop" guess to the real one (platform.js's own alias fix).
2570
- const turnEnv = envFor(payload);
2571
- const turnCwd = turnEnv.cwd;
2572
- const toolCtx = { getShell, signal, cwd: turnCwd, desktopdir: turnEnv.desktopdir };
2573
-
2574
- try {
2575
- // byok's settings row lives under the provider named IN THE MODEL id
2576
- // ("anthropic:claude-sonnet-5" -> byokNamespace('anthropic')), never
2577
- // under the literal class name — one flat 'byok' row could not hold
2578
- // more than one provider's key at a time.
2579
- const byokParts = cls === 'byok' ? splitByokModel(model) : null;
2580
- // aegis carries its own credential on the `aegis` client; byok is the
2581
- // only class whose key comes out of the settings store, and it comes from
2582
- // the provider named in the model id.
2583
- const cfg =
2584
- cls === 'byok' ? settings.get(byokNamespace(byokParts.provider)) || {}
2585
- : cls === 'local' ? settings.get('local') || {}
2586
- : {};
2587
- // Where a byok key comes from, in order: the encrypted store (a key saved
2588
- // through the app), then the shared `~/.aegiscode/.env` (client/env-file.js,
2589
- // read into process.env at start-up). The store wins when it holds one, so
2590
- // removing a key there still means removed — the file is the convenience,
2591
- // not a second authority.
2592
- const storedKey = cls === 'byok' ? settings.rawKey(byokNamespace(byokParts.provider)) : null;
2593
- const apiKey = cls !== 'byok'
2594
- ? null
2595
- : (storedKey || providerKeyFromEnv(byokParts.provider));
2596
-
2597
- if (cls === 'byok' && (!byokParts.provider || !byokParts.model)) {
2598
- const err = new Error(
2599
- "byok: model must be \"<provider>:<model>\" (pick one from /models) — got " +
2600
- JSON.stringify(model || '')
2601
- );
2602
- err.status = 400;
2603
- throw err;
2604
- }
2605
- if (cls === 'byok' && !apiKey) {
2606
- // Anthropic is the one provider with a SECOND, non-API route, and it is
2607
- // the one a user with a Claude subscription actually owns. Pinning
2608
- // `anthropic:claude-sonnet-5` is a promise that this machine has a
2609
- // console API key for api.anthropic.com; a Pro/Max subscription is NOT
2610
- // one and is deliberately not usable as one (claude-pro.js's own
2611
- // header). So when the machine holds a subscription and no usable
2612
- // anthropic key, the honest instruction is the Pro class — it spends
2613
- // the subscription they already pay for instead of a key they do not
2614
- // have. Checked through claudeProStatus() rather than by looking for a
2615
- // token here, so this message and the picker cannot disagree about
2616
- // whether a subscription is present.
2617
- const pro = byokParts.provider === 'anthropic' ? claudePro.claudeProStatus({ env: process.env }) : null;
2618
- // A key the env file REFUSED outranks both of the messages below. The
2619
- // generic "no key yet" tells a user to go paste one, which is the wrong
2620
- // instruction when the file already holds a value that cannot be a
2621
- // credential: they will paste the same broken thing again, or conclude
2622
- // their account is broken. This is the exact state that produced an
2623
- // upstream `{"type":"authentication_error","message":"Invalid bearer
2624
- // token"}` and read to the user as "Anthropic auth failed".
2625
- const refused = providerKeyRecord(byokParts.provider).rejected;
2626
- const err = new Error(
2627
- refused
2628
- ? `${refused}. That is why this turn has no ${byokParts.provider} key: an env value ` +
2629
- `that short is a paste that lost its payload, not a credential. Fix ${refused.split(' ')[0]} ` +
2630
- `in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: ` +
2631
- `/byok-key ${byokParts.provider} <key> to set one here.`
2632
- : pro && pro.loggedIn
2633
- ? `No Anthropic API key on this machine — an "anthropic:…" id is served by your own ` +
2634
- `console key, which a Claude subscription is not. Use the subscription instead: ` +
2635
- `/class pro (it spends your Claude Code ${pro.subscription || 'Pro'} plan through the ` +
2636
- `claude CLI) — or add a real console key: /byok-key anthropic <key>.`
2637
- : `No key for "${byokParts.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, ` +
2638
- `no setup) — or add this provider's own key: /byok-key ${byokParts.provider} <key>.`
2639
- );
2640
- err.status = 400;
2641
- throw err;
2642
- }
2643
- // …and the AEGIS account key is what makes the turn BILLABLE at all. The
2644
- // relay authenticates on the provider key and resolves the payer
2645
- // separately, from X-AEGIS-Key (app.py `_byok_identify_user`): with no
2646
- // account key the server can attribute the handling fee to no one, so it
2647
- // is logged against user 0 as uncollected — an anonymous free ride the
2648
- // fee exists to close. Require the account key here so EVERY BYOK turn is
2649
- // attributed and every caller pays the handling fee: a funded balance is
2650
- // debited immediately, an unfunded one records the fee as owed
2651
- // (token_bank.charge_byok clamps to zero and never refuses), and nobody
2652
- // is served free. Balance is the server's own concern, not this gate's —
2653
- // with a balance or without one, the account still pays. `listModels`
2654
- // still answers anonymously (the catalog is how a user finds out which
2655
- // key to get), so this refuses only the send, and only until a key lands.
2656
- if (cls === 'byok' && !aegis.apiKey) {
2657
- const err = new Error(
2658
- 'No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — ' +
2659
- 'or add your AEGIS key with /login, then try again.'
2660
- );
2661
- err.status = 401;
2662
- throw err;
2663
- }
2664
-
2665
- // The direct-dial gate, restored for the one class that legitimately
2666
- // dials. It policed a lane that could reach ANY user-supplied URL, which
2667
- // billed nobody — no pooled margin, no BYOK handling fee, no account key
2668
- // attached — so a remote URL there was an unpaid turn to refuse rather
2669
- // than meter. That open-ended lane is gone for good. `local` is the case
2670
- // its own reasoning carved out: a model on a machine the user owns, where
2671
- // there is no vendor to pay in the first place, so there is nothing to
2672
- // bill and nobody being cheated. Checked here before any byte goes out,
2673
- // and again inside the transport, because a settings row can be edited on
2674
- // disk after it was written. Anything not local is refused, not metered —
2675
- // remote models belong on `aegis` or `byok`, both of which bill.
2676
- if (cls === 'local') {
2677
- const refusal = localT.remoteRefusal(cfg.baseURL || localT.DEFAULT_BASE);
2678
- if (refusal) throw refusal;
2679
- }
2680
- // `custom` is the mirror of `local`: both are rows whose payload is an
2681
- // ADDRESS rather than a credential, and both are unusable without it.
2682
- // They differ in what absence MEANS. A blank `local` row falls back to
2683
- // DEFAULT_BASE (the stock Ollama port) because there is exactly one
2684
- // sensible address to guess. A blank `custom` row has no default at all —
2685
- // the catalog descriptor pins none, so the server refuses the call with a
2686
- // bare 400 that says nothing about which half of the setup is missing.
2687
- //
2688
- // Caught here, before any byte goes out, so the message can name the
2689
- // command that fixes it. Reachable in practice: `/byok-key custom <key>`
2690
- // stores a key with no address, and the CLI explicitly trusts an
2691
- // unreachable catalog rather than refusing the id — so a user who typed
2692
- // the key first and the endpoint never has a row that looks configured.
2693
- // Keyed on the provider, not the class: every other byok provider's host
2694
- // is a server-side constant and needs no address from us.
2695
- if (cls === 'byok' && byokParts.provider === 'custom' && !(cfg.baseURL || '').trim()) {
2696
- const err = new Error(
2697
- 'No endpoint saved for the "custom" provider — its key is on this machine but the address ' +
2698
- 'it dials is not, and no default exists for a vendor AEGIS does not know. Fix: ' +
2699
- '/model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the ' +
2700
- 'endpoint field in Settings › Provider (custom).'
2701
- );
2702
- err.status = 400;
2703
- err.code = 'custom_endpoint_missing';
2704
- throw err;
2705
- }
2706
- const base = {
2707
- cls, model, mode: payload && payload.mode, maxTokens, statedMaxTokens, autonomous, sessionId, signal, onDelta, cfg, apiKey, toolChoice,
2708
- // The turn's working directory, computed above as `turnCwd` — `dispatch`
2709
- // is its own function, not a closure over `chat`'s locals, so the 'pro'
2710
- // branch (the only one that spawns a child in a directory) needs it
2711
- // threaded through here rather than reaching for the enclosing scope's
2712
- // variable, which does not exist from inside `dispatch`.
2713
- cwd: turnCwd,
2714
- // The CONVERSATION's identity, distinct from `sessionId` (which both
2715
- // hosts mint fresh per TURN — the CLI in ask(), for cancellation).
2716
- // Continuity that must outlive one turn is keyed by these, never by
2717
- // `sessionId`: the Pro child's remembered session is one per open
2718
- // thread, so keying it by a per-turn id would start a new child
2719
- // conversation every single turn and look exactly like no memory.
2720
- rootSessionId,
2721
- sessionKey: (payload && payload.sessionKey) || undefined,
2722
- effort: payload && payload.effort,
2723
- workers: payload && payload.workers,
2724
- // Deep recall (`aegis_recall_deep`) is an explicit per-session opt-in
2725
- // and never a default: it costs one provider embedding per turn
2726
- // server-side (aegis1 services/brain_memory.py find_cached_answer), so
2727
- // a client that pays per turn must not turn it on for itself. Only a
2728
- // literal `true` from the caller counts — an absent or `undefined`
2729
- // field is off, which is what keeps every existing caller (the
2730
- // renderer's IPC payloads included) on the cheap read.
2731
- recallDeep: payload && payload.recallDeep === true,
2732
- // The fan-out opt-out, and it must be an explicit `true` for the same
2733
- // reason `recallDeep` is. `undefined` is NOT an opt-out: the wire flag
2734
- // below is `singlePass ? false : autonomous ? true : undefined`, and an
2735
- // absent `brain` flag lets the *model id* turn the fan-out on by itself
2736
- // (aegis1 pool_brain.parse_brain_request: `is_brain_model(spec)` alone
2737
- // enables it). So a clamped task on a brain model fanned out anyway
2738
- // while the log claimed a single pass — the caller's intent never
2739
- // reached the wire. Forwarding it here is what lets the refusal be real
2740
- // rather than a local boolean nobody downstream could see.
2741
- singlePass: payload && payload.singlePass === true,
2742
- onReasoning,
2743
- idleTimeoutMs: autonomous ? AUTONOMOUS_IDLE_TIMEOUT_MS : undefined,
2744
- // A caller with no live streaming surface (a `--no-stream` CLI flag, a
2745
- // one-shot script) can ask for the buffered non-stream wire form
2746
- // instead. Undefined/anything but `false` keeps every existing caller
2747
- // (the desktop renderer never sets this) on the streamed path.
2748
- stream: payload && payload.stream === false ? false : true,
2749
- };
2750
-
2751
- // No round cap: a model that keeps calling tools keeps going for as
2752
- // long as it wants to. The old fixed cap (12 rounds) cut off genuinely
2753
- // long research/exploration turns mid-investigation. A turn ends when
2754
- // the model answers with text, or the user cancels.
2755
- //
2756
- // Both of those exit paths need a guard, because a provider's
2757
- // "I'm finished" signal can arrive with no answer attached — which is
2758
- // exactly how the renderer came to paint "(empty response)" over a turn
2759
- // that had actually done real work:
2760
- // - truncated (finish_reason 'length'): the budget was consumed
2761
- // before any visible text (DeepSeek's hidden reasoning bills
2762
- // against max_tokens), or mid tool-call JSON. One doubled retry.
2763
- // - empty (no tool call AND no text): re-dispatch once with no tools
2764
- // and a nudge, so the model has to write up what it already found.
2765
- // Each guard fires at most once per turn, so a provider that is simply
2766
- // broken still terminates instead of looping.
2767
- let truncationRetried = false;
2768
- let synthesisDone = false;
2769
-
2770
- // Round cap — a bound the upstream engine has had all along and this engine
2771
- // did not. Removing the old fixed cap (12) was right in spirit and wrong
2772
- // in effect: it left the turn with NO horizon, and on 2026-09-15 the
2773
- // question "can you check the plan" ran ~70 rounds, grew the context
2774
- // from 2,260 to 116,011 tokens, cost about EUR 2, and spent those rounds
2775
- // writing 400 lines of unrequested code into the source tree. Each round
2776
- // re-sends the whole conversation, so an unbounded loop gets more
2777
- // expensive the longer it runs.
2778
- //
2779
- // The numbers match the upstream engine's (src/autonomous.js) so both clients
2780
- // behave the same: 24 rounds for a chat turn, 40 for an autonomous one.
2781
- // Env-overridable for a deliberately long job.
2782
- // A stated horizon (env) still wins outright — an explicit number is the
2783
- // user overriding the engine, not something the ledger may pad.
2784
- const roundEnvName = autonomous ? 'AEGIS_AUTONOMOUS_MAX_ROUNDS' : 'AEGIS_CHAT_MAX_ROUNDS';
2785
- const statedRounds = (() => {
2786
- const raw = Number.parseInt(process.env[roundEnvName] || '', 10);
2787
- return Number.isFinite(raw) && raw > 0 ? raw : 0;
2788
- })();
2789
- const baseRounds = statedRounds || (autonomous ? 40 : 24);
2790
-
2791
- // Did the previous turn in this session die at its horizon? If so, this
2792
- // turn is a continuation of it: same job, unfinished, and the model has
2793
- // to be told — a cold restart is what made the old cap lose work.
2794
- let roundSessionKey = sessionRounds.keyFor(payload, history);
2795
- let resumed = sessionRounds.take(roundSessionKey);
2796
- if (!resumed && !sessionRounds.isStatedKey(payload)) {
2797
- // adopt() is a bridge for a caller that mints a fresh key every turn
2798
- // (no stated session id, no cwd) — it has no way to ask for ITS OWN
2799
- // held work back, so the most recent one in the process-wide ledger
2800
- // is the best guess available. A caller that DID state an id or a
2801
- // cwd and simply has nothing recorded under it is a different case
2802
- // entirely: a miss there means this conversation never hit the
2803
- // horizon, full stop — grabbing someone else's interruption instead
2804
- // is how an unrelated chat opened with another session's "[session
2805
- // resume]" preamble and tool-call transcript spliced into it.
2806
- const adopted = sessionRounds.adopt();
2807
- if (adopted) {
2808
- resumed = adopted.entry;
2809
- roundSessionKey = adopted.key;
2810
- }
2811
- }
2812
- if (resumed) {
2813
- const preamble = sessionRounds.resumePreamble(resumed);
2814
- // Restore the interrupted turn's transcript, because the preamble alone
2815
- // says HOW MUCH was done, not WHAT. The two callers need different
2816
- // halves of it, so `session-rounds` files both (see `record`):
2817
- //
2818
- // · a caller who brings no conversation of its own — the queue
2819
- // worker's fresh dispatch; autonomous.js never sends `messages` —
2820
- // has nothing, so it gets the FULL transcript;
2821
- // · an interactive chat already carries the prior turns (and the
2822
- // "stopped at N rounds" note), so it gets only what THIS turn added
2823
- // that the caller never saw: the tool calls and their results. Full
2824
- // restore here would duplicate the caller's own text.
2825
- //
2826
- // The old `history.length === 0` guard did the first and not the second,
2827
- // so the resume it was written for a queue task never reached the
2828
- // interactive sessions this feature is actually used from.
2829
- if (history.length === 0) {
2830
- if (Array.isArray(resumed.messages) && resumed.messages.length) history.push(...resumed.messages);
2831
- } else if (Array.isArray(resumed.added) && resumed.added.length) {
2832
- history.push(...resumed.added);
2833
- }
2834
- // Round 1's ask travels as `prompt`; a follow-up dispatch (and every
2835
- // turn that skips the shorthand) has to receive it through history.
2836
- //
2837
- // `promptContent` is what actually goes on the wire, and it was built
2838
- // from `prompt` BEFORE this point — so mutating `prompt` alone left the
2839
- // continuation preamble out of the dispatch entirely. Round 1 then went
2840
- // out as the bare new ask with no "[session resume]" instruction, which
2841
- // is precisely the cold restart this feature exists to prevent (pinned
2842
- // by test/session-rounds.test.mjs, "turn 2 dispatches with the
2843
- // continuation preamble"). Rebuild it here so the two stay in step: for
2844
- // an attachment turn the preamble becomes a text part alongside the
2845
- // dropped files, and for an ordinary send the two are simply equal.
2846
- if (prompt) {
2847
- prompt = `${preamble}\n\n${prompt}`;
2848
- promptContent = attachments.length ? attachmentsModule.buildContent(prompt, attachments) : prompt;
2849
- } else {
2850
- history.push({ role: 'user', content: preamble });
2851
- promptContent = '';
2852
- }
2853
- if (rootOnDelta) {
2854
- rootOnDelta({
2855
- delta:
2856
- `\n\n[resuming work this session left unfinished at ${resumed.rounds} tool rounds` +
2857
- `${resumed.interruptions > 1 ? ` (cut off ${resumed.interruptions}×)` : ''}…]\n`,
2858
- });
2859
- }
2860
- }
2861
- // A resumed turn gets a small bonus on top of the base horizon so
2862
- // re-orientation does not consume the new budget before any work lands.
2863
- let maxRounds = statedRounds || baseRounds + (resumed ? sessionRounds.bonus(baseRounds) : 0);
2864
- let round = 0;
2865
- // Rounds bought by one confirmed extension, and a hard cap on how many
2866
- // extensions a single turn may spend — matching the upstream engine's
2867
- // numbers (src/autonomous.js ROUND_EXTENSION_SIZE/MAX_ROUND_EXTENSIONS)
2868
- // so a turn behaves the same whether it runs there or here. The cap
2869
- // exists even though the renderer is the one asking: a dialog that
2870
- // always says yes must still terminate (8 x baseRounds extra rounds).
2871
- const ROUND_EXTENSION_SIZE = baseRounds;
2872
- const MAX_ROUND_EXTENSIONS = 8;
2873
- let extensions = 0;
2874
-
2875
- // Token accounting for the whole TURN, not just its last round. An
2876
- // agentic turn makes one provider call per tool round, and returning only
2877
- // the final round's `usage` (what this did) reported a fraction of what
2878
- // was actually spent — the tool phase's tokens simply disappeared. Every
2879
- // dispatch is summed, including the truncation retry and the synthesis
2880
- // re-dispatch: both are real, separately billed provider calls.
2881
- const turnUsage = { calls: 0 };
2882
- // The cache fields MUST be listed here, not just summed at the top level.
2883
- // DeepSeek reports its hit count as `prompt_cache_hit_tokens` and its
2884
- // miss count as `prompt_cache_miss_tokens`, and neither name was in this
2885
- // list — so every tool-using turn dropped them on the way out and handed
2886
- // its caller a usage object with no cache information at all. The CLI's
2887
- // `--json` republishes exactly this accumulator, `usageBuckets` then had
2888
- // nothing to read, and the published cost of an agentic run was priced
2889
- // entirely at the miss rate. Measured on the 3-task sweep: `cache_read: 0`
2890
- // on all three trials (tokens_in 210,904) while the row's own baseline
2891
- // showed 72,448 cached tokens. The same defect the CLI's per-turn readout
2892
- // was fixed for, here one layer below it.
2893
- const USAGE_FIELDS = [
2894
- 'input_tokens', 'output_tokens', 'prompt_tokens', 'completion_tokens', 'total_tokens',
2895
- // Anthropic spelling (disjoint from its input count).
2896
- 'cache_read_input_tokens', 'cache_creation_input_tokens',
2897
- // DeepSeek/OpenAI spelling (both SUBSETs of the prompt count, which is
2898
- // what `usageBuckets` detects and subtracts rather than double-billing).
2899
- 'prompt_cache_hit_tokens', 'prompt_cache_miss_tokens',
2900
- // Hidden deliberation, which every provider here bills as OUTPUT but
2901
- // none of them split out for free. These were absent from the list
2902
- // while `reasoningTokensOf` (below) already knew how to read them, so
2903
- // the one place that could have separated "wrote more code" from
2904
- // "thought longer" threw the split away at the accumulator and handed
2905
- // its caller a single `output_tokens` with CoT folded in. A benchmark
2906
- // row could therefore see that a turn cost 1.9x another's output and
2907
- // still have no way to say which half moved.
2908
- 'reasoning_tokens', 'thinking_tokens',
2909
- ];
2910
- const addUsage = (res) => {
2911
- const u = res && res.usage;
2912
- if (!u || typeof u !== 'object') return;
2913
- turnUsage.calls += 1;
2914
- for (const key of USAGE_FIELDS) {
2915
- if (typeof u[key] === 'number' && Number.isFinite(u[key])) {
2916
- turnUsage[key] = (turnUsage[key] || 0) + u[key];
2917
- }
2918
- }
2919
- // A provider that reports only the split (Anthropic-compatible) has no
2920
- // total to sum, so derive one or the renderer has nothing to print.
2921
- if (typeof u.total_tokens !== 'number') {
2922
- const derived =
2923
- (u.prompt_tokens ?? u.input_tokens ?? 0) + (u.completion_tokens ?? u.output_tokens ?? 0);
2924
- if (derived) turnUsage.total_tokens = (turnUsage.total_tokens || 0) + derived;
2925
- }
2926
- };
2927
- // The turn's totals win over any single round's, so the attached usage is
2928
- // never the last round wearing the whole turn's label.
2929
- const withTurnUsage = (res) => {
2930
- if (!res || typeof res !== 'object' || !turnUsage.calls) return res;
2931
- // Built from the accumulator alone: every field already present in a
2932
- // round's usage was summed into it, so merging the last round back in
2933
- // could only reintroduce a partial number under a whole-turn label.
2934
- return { ...res, usage: { ...turnUsage } };
2935
- };
2936
-
2937
- // Round 1's shorthand prompt was sent as `prompt`, not as a message, so
2938
- // any follow-up dispatch in this turn must fold it into the history
2939
- // first or the model would be shown a nudge with no question above it.
2940
- const foldPromptIntoHistory = () => {
2941
- if (promptContent === '') return;
2942
- const last = history[history.length - 1];
2943
- // Identity test against the FLATTENED form: once a drop is present the
2944
- // wire content is a content-part array, so a `===` against the prompt
2945
- // string would never match and the ask would be folded twice — the
2946
- // model would see the question, the picture, and then the question
2947
- // again below it.
2948
- const lastText = last && last.role === 'user' ? flattenContent(last.content) : null;
2949
- if (!(last && last.role === 'user' && lastText === flattenContent(promptContent))) {
2950
- history.push({ role: 'user', content: promptContent });
2951
- }
2952
- prompt = '';
2953
- promptContent = '';
2954
- };
2955
-
2956
- // From here on, everything pushed into `history` is this turn's own work:
2957
- // the restored transcript above (if any) belongs to the turn it came from,
2958
- // and re-recording it would double the ledger on every interruption.
2959
- historyStart = history.length;
2960
-
2961
- // ── mutation ledger for this turn ──────────────────────────────────────
2962
- // The empty-turn guards above prove the model SAID nothing; these prove
2963
- // it CHANGED nothing. Kept here rather than derived after the fact
2964
- // because the tool loop is the only place that sees each call's name and
2965
- // result — by the time the turn returns, the evidence is a transcript.
2966
- // `turnAsk` (the user's own ask) is declared above, beside `prompt`.
2967
- const mutatingTools = (T && T.MUTATING_TOOLS) || new Set();
2968
- let mutationsAttempted = 0; // mutating tool CALLS seen this turn
2969
- let mutationsSucceeded = 0; // of those, the ones that actually ran
2970
- let unmutatedRetried = false;
2971
-
2972
- for (;;) {
2973
- // Stop and SAY so. A turn that reaches its horizon has usually done
2974
- // real work; ending silently would paint an empty answer over it,
2975
- // which is the same "(empty response)" failure the guards below exist
2976
- // to prevent.
2977
- if (round >= maxRounds) {
2978
- // Before conceding, give an interactive caller the chance to fund
2979
- // another block of rounds instead of ending the turn outright — the
2980
- // upstream engine's "asks" contract (src/backend.js requestExtension).
2981
- // Only reachable with `roundsAsk` AND a live signal: a caller with no
2982
- // renderer on the other end (queue, `-p`) falls straight through to
2983
- // the session-hold stop below, unchanged.
2984
- if (roundsAsk && extensions < MAX_ROUND_EXTENSIONS && !signal.aborted) {
2985
- const granted = await requestRoundsAsk(rootSessionId, rootOnDelta, signal, {
2986
- spent: maxRounds,
2987
- extensions: extensions + 1,
2988
- max: MAX_ROUND_EXTENSIONS,
2989
- size: ROUND_EXTENSION_SIZE,
2990
- });
2991
- if (granted) {
2992
- extensions += 1;
2993
- const spent = maxRounds;
2994
- maxRounds += ROUND_EXTENSION_SIZE;
2995
- history.push({
2996
- role: 'user',
2997
- content: `You have used all ${spent} tool rounds allowed for this turn; ` +
2998
- `${ROUND_EXTENSION_SIZE} more have been granted (do not restart). Continue the task ` +
2999
- 'from exactly where you stopped — do not re-plan, do not repeat work already done, ' +
3000
- 'and finish with an answer.',
3001
- });
3002
- continue;
3003
- }
3004
- // Declined (or the extension cap is spent): fall through to the
3005
- // same session-hold stop a non-interactive caller gets, so a "no"
3006
- // here is bit-for-bit the old hard stop rather than a dead end.
3007
- }
3008
- // The knob is only advice where nobody could have been asked about
3009
- // it. An interactive caller was already offered another block of
3010
- // rounds (requestRoundsAsk above) and declined or spent the cap, so
3011
- // pointing it at an env var it cannot set from inside the app — and
3012
- // would have to restart to apply — is obsolete text: drop it. The
3013
- // queue worker and `-p` one-shots have no dialog, so for them the
3014
- // variable remains the only lever and is still named.
3015
- const knob = roundsAsk ? '' : `, or raise ${roundEnvName} for a longer single turn`;
3016
- const note =
3017
- `[stopped at ${maxRounds} tool rounds` +
3018
- `${turnUsage.total_tokens ? `, ${turnUsage.total_tokens.toLocaleString()} tokens` : ''}` +
3019
- `. This session holds the work: your next message here resumes it automatically` +
3020
- ` (with a continuation preamble)${knob}.]`;
3021
- // File the interruption before returning, so the horizon is a pause
3022
- // in the session rather than the end of the job. `chain` carries the
3023
- // count forward across resumes.
3024
- const held = sessionRounds.record(roundSessionKey, {
3025
- rounds: round,
3026
- tokens: turnUsage.total_tokens || 0,
3027
- note,
3028
- chain: resumed ? resumed.interruptions : 0,
3029
- // The actual tool-call/tool-result transcript built up this turn —
3030
- // everything folded/pushed into `history` by completed rounds — so
3031
- // a resume can restore real memory of the work, not just a count
3032
- // of it (see the `resumed.messages` rehydration above).
3033
- messages: history,
3034
- // …and only what this turn itself added, for the caller that
3035
- // already has the rest of `history` in its own conversation.
3036
- added: history.slice(historyStart),
3037
- });
3038
- if (rootOnDelta) rootOnDelta({ delta: `\n\n${note}` });
3039
- return withTurnUsage({
3040
- model: base.model,
3041
- choices: [{ message: { content: note }, finish_reason: 'length' }],
3042
- stoppedOnRounds: true,
3043
- heldForSession: true,
3044
- heldRounds: held.rounds,
3045
- sessionInterruptions: held.interruptions,
3046
- resumedFrom: roundSessionKey,
3047
- });
3048
- }
3049
- round += 1;
3050
- // `round === 1` is the user's own ask, and the ONLY dispatch allowed to
3051
- // carry the deep-recall opt-in: the deep tier embeds the query once per
3052
- // dispatch, so leaving it on for an agentic turn would charge one
3053
- // embedding per tool round instead of one per turn (the retries below
3054
- // clear it explicitly, being re-dispatches inside round 1).
3055
- // `promptContent`, not `prompt`: round 1 is the only dispatch that can
3056
- // carry the dropped pictures, and after this point
3057
- // foldPromptIntoHistory() moves the same value into `history` so every
3058
- // follow-up round and recovery re-dispatch keeps them.
3059
- const opts = { ...base, system, messages: history, prompt: promptContent, tools: toolSchemas, recallDeep: base.recallDeep && round === 1 };
3060
- let res;
3061
- res = await dispatch(cls, opts);
3062
- addUsage(res);
3063
-
3064
- // A cancelled turn is over. Both recoveries below exist for "the model
3065
- // said nothing", and an aborted request resolves with exactly that —
3066
- // no text — so without this guard a user pressing Esc to stop a slow
3067
- // turn immediately issued ANOTHER billed provider call (and, because
3068
- // every transport concatenates the deltas it forwards, streamed the
3069
- // partial answer a second time onto the same bubble). Measured before
3070
- // the guard: one interrupted turn == two dispatches.
3071
- if (signal.aborted) return withTurnUsage(res);
3072
-
3073
- // Budget exhausted before the answer was written. Doubling it costs
3074
- // one request and converts a dead turn into a real one; a second
3075
- // 'length' result is accepted as-is so a hard-capped model can't
3076
- // spin here forever.
3077
- //
3078
- // Gated on empty text on purpose. Every transport builds `content`
3079
- // by concatenating the deltas it already forwarded to onDelta, so
3080
- // empty content means nothing was streamed and re-dispatching cannot
3081
- // double up in the renderer's live view. When text *has* arrived the
3082
- // turn is not empty — the answer is merely truncated — and a retry
3083
- // would stream it a second time onto the same bubble.
3084
- if (!truncationRetried && !assistantText(res) && (isTruncated(res) || reasonedButSilent(res))) {
3085
- truncationRetried = true;
3086
- const reasoningOnly = reasonedButSilent(res);
3087
- // singlePass: this retry buys *budget*, not a second investigation.
3088
- // The fan-out's workers would re-run the whole task from scratch for
3089
- // it — 3 extra reasoning passes + a synthesis — which is the opposite
3090
- // of what "one doubled request" means (and what the note above
3091
- // promises). The pass itself is unchanged apart from that.
3092
- res = await dispatch(cls, {
3093
- ...opts,
3094
- singlePass: true,
3095
- // A re-dispatch, not a new ask: the deep tier's embedding was
3096
- // bought by round 1, and buying it again here would charge a
3097
- // second one for the same context.
3098
- recallDeep: false,
3099
- // A reasoning-only completion gets the high rung AND high effort:
3100
- // the model is about to re-pay for the same chain-of-thought, and
3101
- // on DeepSeek that pair is what actually moves the ceiling.
3102
- effort: reasoningOnly ? 'high' : opts.effort,
3103
- maxTokens: retryBudgetFor(opts, reasoningOnly),
3104
- // Doubling applies to the pooled path only when the caller stated a
3105
- // number. With none stated, the server's effort ladder IS the
3106
- // budget, and sending doubledBudget's 8192 floor would *lower* it
3107
- // (aegis1 reads max_tokens as a ceiling over the ladder) — a
3108
- // "double the budget" retry that halves it at high effort.
3109
- statedMaxTokens: opts.statedMaxTokens ? doubledBudget(opts.statedMaxTokens) : undefined,
3110
- });
3111
- addUsage(res);
3112
- // Same guard as line ~1499, for the same reason: an abort landing
3113
- // during THIS dispatch also resolves as empty text, and without
3114
- // this check that "no answer" would fall straight into the
3115
- // empty-turn nudge below instead of ending the turn — a cancelled
3116
- // request quietly buying a THIRD billed call.
3117
- if (signal.aborted) return withTurnUsage(res);
3118
- }
3119
-
3120
- const calls = toolSchemas.length ? extractToolCalls(res) : [];
3121
- if (!calls.length) {
3122
- if (assistantText(res) || synthesisDone || !toolsEnabled) {
3123
- // ── the wrote-nothing guard ──────────────────────────────────────
3124
- // The turn has an answer, so it is not empty and every guard above
3125
- // lets it end here. But an answer is not a result when the ask was
3126
- // "fix this": a model that investigated, narrated the fix and
3127
- // stopped one action short returns a turn that reads complete and
3128
- // scores zero. Re-ask ONCE, with the tools still attached.
3129
- if (
3130
- !unmutatedRetried &&
3131
- toolsEnabled &&
3132
- wantsMutation(turnAsk, mutationsSucceeded > 0, mutationsAttempted)
3133
- ) {
3134
- unmutatedRetried = true;
3135
- foldPromptIntoHistory();
3136
- // The model's own closing text stays in history as the assistant
3137
- // turn, so the nudge can point at it ("describing the fix is not
3138
- // the fix") rather than arriving as an unexplained instruction.
3139
- history.push({ role: 'assistant', content: assistantText(res) });
3140
- history.push({ role: 'user', content: UNMUTATED_TURN_NUDGE });
3141
- if (rootOnDelta) rootOnDelta({ delta: '' });
3142
- continue;
3143
- }
3144
- return withTurnUsage(res);
3145
- }
3146
- // The model stopped without calling a tool and without saying
3147
- // anything. Force the summary out of the context it already holds
3148
- // instead of handing the renderer a blank completion. Skipped when
3149
- // the caller opted out of the agent loop (`tools: false`): there is
3150
- // no gathered context to rescue, so a bare completion is just that.
3151
- synthesisDone = true;
3152
- foldPromptIntoHistory();
3153
- // The nudge is chosen by what the empty round actually WAS, not by the
3154
- // fact that it was empty. A round that spent its budget on hidden
3155
- // reasoning and stopped without writing a word needs to be told not to
3156
- // think; the generic wording invites the same silent pass a second
3157
- // time, which is precisely how a recoverable turn became
3158
- // `emptyTurnError` on byok/deepseek-v4-flash (2026-10-11).
3159
- history.push({ role: 'user', content: reasonedButSilent(res) ? THOUGHT_ONLY_NUDGE : EMPTY_TURN_NUDGE });
3160
- // singlePass: same reasoning as the truncation retry above, and it is
3161
- // the same comment's literal promise ("force the summary out of the
3162
- // context it already holds"). Escalating a write-up back into the
3163
- // worker fan-out asked three fresh workers to redo an investigation
3164
- // whose findings are already in `history`, at 4x the cost, to produce
3165
- // a paragraph the model had all the material for.
3166
- const synthesisOpts = {
3167
- ...opts,
3168
- singlePass: true,
3169
- // Same as the truncation retry above: this pass writes up findings
3170
- // already in `history`, and a fresh embedding buys it nothing.
3171
- recallDeep: false,
3172
- messages: history,
3173
- prompt: '',
3174
- tools: [],
3175
- };
3176
- res = await dispatch(cls, synthesisOpts);
3177
- // The ceiling and the rung of the last dispatch that came back empty,
3178
- // so the failure below reports the call that actually failed instead of
3179
- // the original one it was retried away from.
3180
- let lastBudget = synthesisOpts.maxTokens;
3181
- let lastEffort = synthesisOpts.effort;
3182
- addUsage(res);
3183
- // Same guard again: a cancel landing during the synthesis pass
3184
- // resolves empty too, and without this check it fell through to
3185
- // emptyTurnError — a real exception, so the renderer painted a red
3186
- // "no answer" failure over what was actually just the user hitting
3187
- // Cancel.
3188
- if (signal.aborted) return withTurnUsage(res);
3189
- // The SAME truncation retry the main round gets, one level down: the
3190
- // write-up pass is itself a fresh dispatch billed against `opts.maxTokens`,
3191
- // and a reasoning model can burn that whole budget on hidden
3192
- // chain-of-thought a SECOND time while composing the summary — history
3193
- // is bigger than round 1's, so if anything this pass is more likely to
3194
- // need the room. Without this, "the synthesis pass also got
3195
- // truncated" and "the model is simply done" were indistinguishable —
3196
- // both threw the same emptyTurnError — even though the first is
3197
- // recoverable with the exact one-line fix already proven above.
3198
- if (!assistantText(res) && (isTruncated(res) || reasonedButSilent(res))) {
3199
- const reasoningOnly = reasonedButSilent(res);
3200
- lastBudget = retryBudgetFor(synthesisOpts, reasoningOnly);
3201
- lastEffort = reasoningOnly ? 'high' : synthesisOpts.effort;
3202
- res = await dispatch(cls, {
3203
- ...synthesisOpts,
3204
- effort: lastEffort,
3205
- maxTokens: lastBudget,
3206
- statedMaxTokens: synthesisOpts.statedMaxTokens
3207
- ? doubledBudget(synthesisOpts.statedMaxTokens)
3208
- : undefined,
3209
- });
3210
- addUsage(res);
3211
- if (signal.aborted) return withTurnUsage(res);
3212
- }
3213
- // ── The recovery ladder: extra calls, not a verdict ────────────────
3214
- // Everything above bought a bigger ceiling; this changes the ASK —
3215
- // and repeats it — because a round that reasoned and then stayed
3216
- // silent has already been handed more room and still did not write a
3217
- // word.
3218
- //
3219
- // This is the upstream engine's own trade (`src/backend.js`, the
3220
- // `thoughtOnly` recovery round): spend another call rather than hand
3221
- // the reader a red "backend error: … raise the Effort rung" over work
3222
- // that is finished and already sitting in `history`. Telling someone
3223
- // to go and raise a setting is not a recovery, and the ceiling it
3224
- // points at was raised by the retry above — so the ladder spends
3225
- // calls, with a variant of the ask each time, and only reports
3226
- // failure when every one of them comes back empty as well.
3227
- //
3228
- // Bounded by construction: `RECOVERY_ROUNDS` caps the calls,
3229
- // `synthesisDone` is already true, and each nudge JOINS `history`
3230
- // rather than replacing it — every round here runs with `tools: []`,
3231
- // so a round is a re-ask out of context the model already holds and
3232
- // can never become a fresh investigation.
3233
- //
3234
- // The ceiling lift below is computed ONCE, not per round. A ladder
3235
- // that doubled the budget each time would turn "two more calls" into
3236
- // "two more calls at double the price" for a model whose problem is
3237
- // demonstrably not the price, and Math.max keeps it monotone: for a
3238
- // rung this is the top of the ladder, and a number a previous retry
3239
- // already raised past it (a caller's doubled cap) is never lowered.
3240
- const ladderBudget = (() => {
3241
- const owned = Number(lastBudget) || 0;
3242
- // No number in hand — the caller stated none and the model is not a
3243
- // reasoning model, so `reasoningBudget()` sends no `max_tokens` at
3244
- // all and the provider's own limit governs. Inventing one here
3245
- // (retryBudgetFor's 8192 floor) would put a ceiling on the wire that
3246
- // nobody asked for, which is the very defect this file's budget
3247
- // comments were written about. The ladder's extra call is then the
3248
- // same price as the call it repeats, and only the ask changes.
3249
- if (!owned) return lastBudget;
3250
- const ask = { maxTokens: lastBudget };
3251
- if (synthesisOpts.statedMaxTokens) ask.statedMaxTokens = synthesisOpts.statedMaxTokens;
3252
- return Math.max(owned, retryBudgetFor(ask, true));
3253
- })();
3254
- let recoveryRounds = 0;
3255
- while (!assistantText(res) && recoveryRounds < RECOVERY_ROUNDS && !signal.aborted) {
3256
- const reasoningOnly = reasonedButSilent(res);
3257
- recoveryRounds += 1;
3258
- history.push({
3259
- role: 'user',
3260
- content: reasoningOnly
3261
- ? recoveryRounds === 1
3262
- ? THOUGHT_ONLY_NUDGE
3263
- : FINAL_ANSWER_NUDGE
3264
- : EMPTY_TURN_NUDGE,
3265
- });
3266
- if (reasoningOnly) lastEffort = 'high';
3267
- lastBudget = ladderBudget;
3268
- res = await dispatch(cls, {
3269
- ...synthesisOpts,
3270
- messages: history,
3271
- effort: lastEffort,
3272
- maxTokens: lastBudget,
3273
- statedMaxTokens: synthesisOpts.statedMaxTokens
3274
- ? doubledBudget(synthesisOpts.statedMaxTokens)
3275
- : undefined,
3276
- });
3277
- addUsage(res);
3278
- if (signal.aborted) return withTurnUsage(res);
3279
- }
3280
- if (!assistantText(res)) {
3281
- throw emptyTurnError({
3282
- cls,
3283
- model,
3284
- // What the LAST call looked like, and how many extra calls the
3285
- // ladder already spent: the report describes the call that failed
3286
- // rather than the first one it was retried away from.
3287
- effort: lastEffort,
3288
- recoveryRounds,
3289
- finishReason: finishReasonOf(res),
3290
- reasoningChars: reasoningTextOf(res).length,
3291
- // The withheld-deliberation case (a Pro turn with extended
3292
- // thinking on): no chars to count, but the provider billed the
3293
- // thinking. Without this the report claims nothing came back.
3294
- reasoningTokens: reasoningTokensOf(res),
3295
- });
3296
- }
3297
- return withTurnUsage(res);
3298
- }
3299
-
3300
- foldPromptIntoHistory();
3301
-
3302
- // Thread the assistant turn (its tool_calls) and each result back in
3303
- // the OpenAI shape the relay accepts.
3304
- history.push({
3305
- role: 'assistant',
3306
- content: assistantText(res),
3307
- tool_calls: calls.map((c) => ({
3308
- id: c.id,
3309
- type: 'function',
3310
- function: { name: c.name, arguments: JSON.stringify(c.args) },
3311
- })),
3312
- });
3313
-
3314
- // ── dispatch: reads in parallel, mutations in order ──────────────────
3315
- //
3316
- // Every call used to be awaited one at a time, in a plain `for` loop:
3317
- //
3318
- // for (const call of calls) { … await … }
3319
- //
3320
- // which made the engine strictly SERIAL even though the system prompt
3321
- // has always told the model to batch ("Batch independent tool calls
3322
- // into ONE turn"). The model complied — pi's logs show 7/10 SWE-bench
3323
- // instances emitting multi-call assistant messages, one with 14 of 19
3324
- // rounds — and the engine then drained them one by one, paying the sum
3325
- // of their latencies for a round the model meant to cost the max. That
3326
- // is the whole shape of the wall-time gap against pi: MEDIANS matched
3327
- // (120s vs 126s) while the TAIL diverged (764s vs 265s worst case,
3328
- // 2223s vs 1322s total), because only a turn that batches has a tail
3329
- // to lose.
3330
- //
3331
- // The split is on MUTATION, not on tool name, because two rules make
3332
- // wholesale parallelism wrong here:
3333
- //
3334
- // 1. `exec` runs in ONE persistent shell per turn (see getShell), so
3335
- // two execs in flight would interleave into one stdin and lose the
3336
- // sentinel correlation — `cd`/`export` state would also race.
3337
- // 2. mutations are ordered intent. `editFile` then `editFile` on the
3338
- // same file, or `writeFile` then `exec` to run it, is a sequence
3339
- // the model wrote in order; reordering it would be the engine
3340
- // second-guessing the plan.
3341
- //
3342
- // So a round is split into RUNS of consecutive calls: a run of
3343
- // read-only calls executes concurrently, and each mutating call is its
3344
- // own run, executed alone and in place. Serial order is preserved
3345
- // across every mutation, and reads never reorder around one. This is
3346
- // the same rule pi's harness gets for free from a single-threaded shell
3347
- // plus a stateless file layer.
3348
- // `exec` is in MUTATING_TOOLS, but most exec calls are READS run through
3349
- // a shell (81.7% of the measured SWE-bench tool calls were exec; 57.5%
3350
- // of those commands were read-shaped grep/sed/ls/git). Those may join a
3351
- // parallel run when the classifier proves they are self-contained — see
3352
- // `planExec` below and exec-plan.js. `plan` is cached on the call so the
3353
- // classifier runs once per call, not once per test.
3354
- const plans = new WeakMap();
3355
- const planOf = (call) => {
3356
- if (call.name !== 'exec') return null;
3357
- if (plans.has(call)) return plans.get(call);
3358
- const p = planExec(call.args && call.args.command, { baseCwd: turnCwd });
3359
- plans.set(call, p);
3360
- return p;
3361
- };
3362
- const readOnly = (call) => {
3363
- if (call.name === T.SUBAGENT_TOOL) return false;
3364
- if (!mutatingTools.has(call.name)) return true;
3365
- const p = planOf(call);
3366
- return Boolean(p && p.oneShot);
3367
- };
3368
- const runs = [];
3369
- for (const call of calls) {
3370
- const last = runs[runs.length - 1];
3371
- if (readOnly(call) && last && last.parallel) last.calls.push(call);
3372
- else runs.push({ parallel: readOnly(call), calls: [call] });
3373
- }
3374
-
3375
- // One call, run to completion, with its frames and its history row.
3376
- // Resolves (never rejects) so a concurrent run is all-or-nothing per
3377
- // call rather than per round, matching the serial loop's contract.
3378
- const runOne = async (call) => {
3379
- // Open the live row BEFORE the tool runs. The CLI paints
3380
- // `Running N … · 3s` off a `phase: 'run'` frame and ticks it while
3381
- // the tool is still going; reporting the tool only once, after it
3382
- // finished, left the transcript showing a spinner verb and nothing
3383
- // else for the whole exec timeout (120s, up to 600s) — which reads
3384
- // as a wedged turn rather than a working one.
3385
- if (onDelta) {
3386
- onDelta({
3387
- delta: '',
3388
- tool: { name: call.name, args: call.args, id: call.id, cwd: turnCwd, phase: 'run' },
3389
- });
3390
- }
3391
- const plan = planOf(call);
3392
- // A one-shot-eligible exec gets its own ctx: the flag that routes it
3393
- // away from the shared shell, and the cwd the classifier recovered
3394
- // from its leading `cd`. Everything else in the ctx is identical, so
3395
- // the approval gate, the covenant assert and the destructive-command
3396
- // guard all still see this call exactly as they did before.
3397
- const callCtx = plan && plan.oneShot
3398
- ? { ...toolCtx, oneShotExec: true, cwd: plan.cwd || toolCtx.cwd }
3399
- : toolCtx;
3400
- const result = call.name === T.SUBAGENT_TOOL
3401
- ? await runSubagent(call.args, {
3402
- cls, model, statedMaxTokens, effort: payload && payload.effort,
3403
- mode: payload && payload.mode, parentSignal: signal, depth, rootSessionId, rootOnDelta,
3404
- })
3405
- : await gatedExecuteTool(call, { toolCtx: callCtx, rootSessionId, rootOnDelta, signal });
3406
- // A subagent's spend rides back on its tool result (see runSubagent).
3407
- if (result && result.usage) addUsage({ usage: result.usage });
3408
- // The id is carried on both frames: the CLI pairs them by id first,
3409
- // precisely so parallel same-name calls don't collapse into one row
3410
- // with the wrong plural.
3411
- if (onDelta) {
3412
- onDelta({
3413
- delta: '',
3414
- tool: { name: call.name, args: call.args, ok: result.ok, id: call.id, cwd: turnCwd, phase: 'done' },
3415
- });
3416
- }
3417
- return result;
3418
- };
3419
-
3420
- for (const run of runs) {
3421
- const results = run.parallel && run.calls.length > 1
3422
- ? await Promise.all(run.calls.map((c) => runOne(c)))
3423
- : [await runOne(run.calls[0])];
3424
- // Results are threaded back in the ORDER THE MODEL WROTE THEM, not in
3425
- // completion order: the OpenAI wire shape pairs each `tool` message
3426
- // to its `tool_call_id`, and a transcript whose results arrive in a
3427
- // different order than the calls reads as a model that acted out of
3428
- // order. `Promise.all` preserves index order, which is why it is used
3429
- // rather than `Promise.race`-style collection.
3430
- run.calls.forEach((call, i) => {
3431
- const result = results[i];
3432
- // Mutation accounting for the wrote-nothing guard above. A mutating
3433
- // tool that FAILED is not a mutation, but it IS evidence the model
3434
- // meant to change something — which is why the two counters are
3435
- // kept apart.
3436
- if (mutatingTools.has(call.name)) {
3437
- mutationsAttempted += 1;
3438
- if (result && result.ok) mutationsSucceeded += 1;
3439
- }
3440
- history.push({
3441
- role: 'tool',
3442
- tool_call_id: call.id,
3443
- name: call.name,
3444
- content: T.toolResultText(result),
3445
- });
3446
- });
3447
- }
3448
- }
3449
- } catch (e) {
3450
- // Stamp the stop at the one place it is known for certain.
3451
- //
3452
- // `cancel(sessionId)` aborts THIS turn's controller, and the in-flight
3453
- // transport unwinds as a rejection. The host has to tell that rejection
3454
- // apart from a genuine provider/transport failure before it can stop
3455
- // printing Ctrl-X as an application crash — and it used to guess from the
3456
- // message text, which is exactly how a real failure ("connection aborted
3457
- // by peer", "upstream aborted the connection") gets relabelled as a
3458
- // deliberate stop and leaves the user with a silently empty answer. The
3459
- // message is not evidence. This is: the signal reads aborted only because
3460
- // the user asked for it, so it cannot be confused with anything upstream
3461
- // did. Attached to the error object itself so it survives any rethrow,
3462
- // and read by `isAbortShapedError` in desktop/main.js.
3463
- if (signal.aborted && e && typeof e === 'object') e.aegisCancelled = true;
3464
- throw e;
3465
- } finally {
3466
- if (shell) shell.dispose();
3467
- controllers.delete(sessionId);
3468
- }
3469
- }
3470
-
3471
- /**
3472
- * Run a `task` tool call as a subagent: a nested chat() turn on the same
3473
- * class/model, primed with the chosen specialist's system prompt (agents.js)
3474
- * and its own tool access (including task, until MAX_SUBAGENT_DEPTH cuts
3475
- * it off), returning the subagent's final text as the tool result. Never
3476
- * throws — resolves { ok, output } or { ok:false, error }, matching
3477
- * tools.js's executor contract so the caller treats it identically.
3478
- */
3479
- async function runSubagent(
3480
- { description, subagent_type, prompt: subPrompt } = {},
3481
- { cls, model, statedMaxTokens, effort, mode, parentSignal, depth, rootSessionId, rootOnDelta } = {}
3482
- ) {
3483
- const task = String(subPrompt || description || '').trim();
3484
- if (!task) return { ok: false, error: 'task requires a prompt' };
3485
- const label = subagent_type && subagent_type !== 'general' ? agentRoleLabel(subagent_type) : 'general';
3486
- const system = agentSystemPrompt(subagent_type);
3487
- const subSessionId = randomUUID();
3488
-
3489
- // Aborting the parent turn must also stop a running subagent instead of
3490
- // leaving it to finish on its own (or sit out the whole turn timeout).
3491
- let onParentAbort;
3492
- if (parentSignal) {
3493
- if (parentSignal.aborted) return { ok: false, error: 'aborted' };
3494
- onParentAbort = () => cancel(subSessionId);
3495
- parentSignal.addEventListener('abort', onParentAbort, { once: true });
3496
- }
3497
-
3498
- try {
3499
- // rootSessionId/rootOnDelta ride along explicitly (see chat()) so the
3500
- // subagent's own mutating tool calls still gate through the SAME
3501
- // approval card the user sees for the top-level turn, instead of
3502
- // silently hanging behind this call's no-op onDelta below.
3503
- const res = await chat(
3504
- {
3505
- class: cls, model, mode, system, prompt: task, sessionId: subSessionId, depth: (depth || 0) + 1,
3506
- rootSessionId, rootOnDelta,
3507
- // The parent's budget AUTHORITY is forwarded, not the number it
3508
- // implies. `maxTokens` is deliberately absent: it is the rung this
3509
- // turn derived from `effort`, and a re-entry that hands it back gets
3510
- // read as the caller's own cap (statedCapOf). The rung itself rides
3511
- // along as `effort`, which is what aegis1 sizes the fan-out and its
3512
- // ladder from — so a subagent now runs at the effort the user chose
3513
- // instead of at a number that only meant anything for this model id.
3514
- statedMaxTokens,
3515
- effort,
3516
- },
3517
- () => {}
3518
- );
3519
- const text = assistantText(res);
3520
- // The subagent's tokens were billed to the same account as the parent
3521
- // turn, so its usage travels back on the tool result and is summed into
3522
- // the parent's total. Attached even on the no-output branch: a subagent
3523
- // that burned a full context and said nothing is precisely the spend the
3524
- // user most needs to see.
3525
- const spent = res && res.usage ? { usage: res.usage } : {};
3526
- return text
3527
- ? { ok: true, output: text, ...spent }
3528
- : { ok: false, error: `subagent (${label}) produced no output`, ...spent };
3529
- } catch (e) {
3530
- return { ok: false, error: `subagent (${label}) failed: ${e && e.message ? e.message : e}` };
3531
- } finally {
3532
- if (parentSignal && onParentAbort) parentSignal.removeEventListener('abort', onParentAbort);
3533
- }
3534
- }
3535
-
3536
- function cancel(sessionId) {
3537
- const controller = controllers.get(sessionId);
3538
- if (controller) controller.abort();
3539
- return { ok: Boolean(controller) };
3540
- }
3541
-
3542
- /**
3543
- * Unload every local model this engine warmed, across every daemon it
3544
- * talked to (local.js `unloadAll`). The desktop host calls this on its quit
3545
- * path so closing the app also closes the model — the local lane bills
3546
- * nothing precisely because it is YOUR hardware, and hardware left running
3547
- * a model nobody is using anymore after the app exits is the one cost that
3548
- * lane was supposed to never have.
3549
- */
3550
- function unloadLocalModels() {
3551
- return localT.unloadAll();
3552
- }
3553
-
3554
- /**
3555
- * The vendor key for a provider, resolved in the order the NEXT TURN will
3556
- * resolve it: the saved `byok:<provider>` row first, then `~/.aegiscode/.env`
3557
- * (loaded into the environment at host start-up by `client/env-file.js`) and
3558
- * the shell. Discovery must ask with the key the call will run on — a list
3559
- * fetched with a different one describes a catalog this machine cannot reach.
3560
- *
3561
- * Read-only by construction: it never writes a key, never hands the value to
3562
- * a renderer and never logs it.
3563
- */
3564
- function byokKeyForProviderLookup(providerId) {
3565
- const id = String(providerId == null ? '' : providerId).trim().toLowerCase();
3566
- if (!id) return '';
3567
- try {
3568
- if (settings && typeof settings.rawKey === 'function') {
3569
- const stored = settings.rawKey(byokNamespace(id));
3570
- if (typeof stored === 'string' && stored.trim()) return stored.trim();
3571
- }
3572
- } catch { /* a store that throws has no key, and that is a reportable state */ }
3573
- return providerKeyFromEnv(id);
3574
- }
3575
-
3576
- return {
3577
- CLASSES,
3578
- listClasses,
3579
- listModels,
3580
- chat,
3581
- cancel,
3582
- respondApproval,
3583
- respondRoundsAsk,
3584
- clearSessionApprovals,
3585
- settings,
3586
- unloadLocalModels,
3587
- // The user's own model declarations (`$AEGISCODE_HOME/models.json`), read,
3588
- // added and removed through ONE implementation because THREE faces write
3589
- // them: the desktop's Settings row (via main.js's model dispatch), the
3590
- // CLI's `/model-add`, and the user's own editor. `userModels()` returns
3591
- // `{ dir, file, map, invalid }` so a host can SHOW where the file is and
3592
- // name the rows it refused (`invalid`), instead of a declaration vanishing
3593
- // into a picker that looks like the feature did nothing.
3594
- //
3595
- // Add/remove THROW on a malformed provider or model id (that is the point —
3596
- // an id the relay would forward to a vendor 404s on the user's first turn,
3597
- // where a rejected input 404s never), so every caller surfaces the message
3598
- // rather than storing it.
3599
- userModels: () => loadUserModels(),
3600
- addUserModel: (provider, model) => addUserModel(provider, model),
3601
- removeUserModel: (provider, model) => removeUserModel(provider, model),
3602
- // ── asking the vendor, so the user does not have to remember ids ───────
3603
- //
3604
- // `discoverModels(provider)` resolves and returns the ids the provider's own
3605
- // list API serves RIGHT NOW, which is the fix for the chore that produced
3606
- // `client/byok-catalog.js`'s hand-copied Anthropic table. It never throws:
3607
- // the shape is the discovery module's own
3608
- // `{ ok, provider, ids, others, count }` / `{ ok:false, error }`, and the
3609
- // renderer prints `error` verbatim. A window that guessed at an id and
3610
- // silently pinned a 404 is the outcome this exists to prevent.
3611
- //
3612
- // The key comes from the SAME chain the next turn will use (the saved
3613
- // `byok:<provider>` row, then `~/.aegiscode/.env`, then the shell), because
3614
- // a list fetched with a different key than the call runs on would describe
3615
- // somebody else's catalog.
3616
- discoverModels: async (provider) => {
3617
- const id = String(provider == null ? '' : provider).trim().toLowerCase();
3618
- const key = byokKeyForProviderLookup(id);
3619
- const res = await discoverVendorModels(id, { key, fetchImpl });
3620
- // Say what the caller needs to offer the next step: which of these the
3621
- // relay itself already lists, and which this machine has declared, so the
3622
- // UI can mark a row instead of the user diffing two lists by eye.
3623
- if (!res || !res.ok) return res;
3624
- const declared = [];
3625
- try {
3626
- const map = loadUserModels().map;
3627
- for (const m of Array.isArray(map[id]) ? map[id] : []) declared.push(m);
3628
- } catch { /* a store that cannot be read marks nothing */ }
3629
- return { ...res, declared, endpoint: (vendorEndpointFor(id) || {}).url || '' };
3630
- },
3631
- // The bulk write (`/model-add <provider> '*'` and the desktop's "Add all"
3632
- // button): declare every id in one pass, skipping what is already there and
3633
- // NAMING what was refused rather than aborting the whole batch on one bad
3634
- // row. Returns counts, never a bare boolean, so both faces can report
3635
- // "3 added, 2 already declared" instead of claiming work they did not do.
3636
- addUserModels: (provider, ids) => {
3637
- const list = Array.isArray(ids) ? ids : [];
3638
- const out = { provider, added: 0, already: [], failed: [], capped: 0, file: '' };
3639
- for (const raw of list) {
3640
- try {
3641
- const res = addUserModel(provider, raw);
3642
- out.file = res.file || out.file;
3643
- if (res.added) out.added += 1;
3644
- else out.already.push(res.model);
3645
- } catch (err) {
3646
- const message = (err && err.message) || String(err);
3647
- // The store's per-provider ceiling ends the batch as a CEILING. A
3648
- // vendor serves a hundred ids and the store holds 32, so reporting
3649
- // that as sixty-eight refused models would describe one deliberate
3650
- // limit as sixty-eight broken ids.
3651
- if (/the cap/.test(message)) {
3652
- out.capped = list.length - out.added - out.already.length - out.failed.length;
3653
- break;
3654
- }
3655
- out.failed.push({ id: String(raw), reason: message });
3656
- }
3657
- }
3658
- return out;
3659
- },
3660
- // What the Settings row uses to decide whether to OFFER a list at all: a
3661
- // provider this client cannot ask (or has no key for) falls back to the
3662
- // free-form input, which is the path that always works.
3663
- canDiscoverModels: (provider) => canDiscoverVendorModels(provider),
3664
- discoverableProviders: () => discoverableProviders(),
3665
- };
3666
- }
3667
-
3668
- module.exports = { CLASSES, createLocalEngine, extractToolCalls, parseArgs, reasoningBudget, nativeEffort, hostEnv };
3
+ const{randomUUID:e}=require("node:crypto"),o=require("node:os"),t=require("./tools.js"),n=require("./attachments.js"),{flattenContent:r}=n,s=require("./prompt.js"),a=require("./local.js"),{ShellSession:i}=require("./shell.js"),{planExec:l}=require("./exec-plan.js"),c=require("./claude-pro.js"),{agentSystemPrompt:d,agentRoleLabel:u}=require("./agents.js"),{beginTurnGuard:f,recordWrite:p,blocksDestructive:m}=require("./turn-guard.js"),{acquireWorktreeLock:h,releaseWorktreeLock:g}=require("./worktree-lock.js"),y=require("./covenant.js");let k=null;try{k=require("../../../client/env-file.js")}catch{try{k=require("../../vendor/env-file.js")}catch{k=null}}let v=null;try{v=require("../../../client/platform.js")}catch{try{v=require("../../vendor/platform.js")}catch{v=null}}let w=null;try{w=require("../../../client/credentials.js")}catch{try{w=require("../../vendor/credentials.js")}catch{w=null}}function b(e,o,n,r){const s=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof t.normalizeArgs&&t.normalizeArgs||null;return s?s(o,n,r):{ok:!0,args:n&&"object"==typeof n?n:{},error:null}}function x(e){if(!e)return null;try{const o=require("node:fs"),t=require("node:path");let n=t.resolve(String(e));for(let e=0;e<8;e+=1){if(o.existsSync(t.join(n,".git")))return"git";const e=t.dirname(n);if(e===n)break;n=e}return""}catch{return null}}function S(e={},t={},n=null){const r=e||{},s=t||{},a=(e,o)=>null!=s[e]?s[e]:o;let i=r.homedir,l=r.cwd;try{i||(i=o.homedir()),l||(l=process.cwd())}catch{}let c=r.shell,d=r.shellKind;try{if(!c||!d){const e=require("./shell.js").resolveSessionShell();c=c||e.cmd,d=d||e.kind}}catch{}let u=r.desktopdir;try{!u&&v&&(u=v.desktopDir())}catch{}let f=r.dataDir;try{!f&&w&&(f=w.aegisHome())}catch{}let p=r.locale,m=r.localeName;try{!p&&v&&"function"==typeof v.appLocale&&(p=v.appLocale()),p&&!m&&v&&"function"==typeof v.languageName&&(m=v.languageName(p))}catch{}return{platform:a("platform",r.platform||process.platform),arch:a("arch",r.arch||process.arch),homedir:a("homedir",i),desktopdir:a("desktopdir",u),dataDir:a("dataDir",f),locale:a("locale",p),localeName:a("localeName",m),languages:a("languages",r.languages),cwd:a("cwd",l),vcs:a("vcs",null!=r.vcs?r.vcs:x(l)),shell:a("shell",c),shellKind:a("shellKind",d),roots:a("roots",r.roots),appVersion:a("appVersion",r.appVersion),model:a("model",n&&n.model)}}const _=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],A="byok:";function T(e){return`${A}${e}`}function M(e){const o="string"==typeof e?e:"",t=o.indexOf(":");return t<0?{provider:"",model:o}:{provider:o.slice(0,t),model:o.slice(t+1)}}function j(e){const o={key:"",env:"",rejected:null};if(!k||"function"!=typeof k.providerKeyFromEnv)return o;try{const t=k.providerKeyFromEnv(e)||o;return{key:"string"==typeof t.key?t.key:"",env:"string"==typeof t.env?t.env:"",rejected:"string"==typeof t.rejected&&t.rejected?t.rejected:null}}catch{return o}}function E(e){if(!k||"function"!=typeof k.providerKeyFromEnv)return"";try{return k.providerKeyFromEnv(e).key||""}catch{return""}}const C=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,I={low:8192,medium:16384,high:32768,max:32768},$={low:"low",medium:"medium",high:"high"},N=/non-reasoning/i,q=[{provider:"deepseek",re:C,field:"effort",map:{low:"low",medium:"high",high:"high"},extra:{max:"max"}},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:$},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:$},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:$},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...$,medium:"high"}}];function D(e,o,t){const n=Number(o);return Number.isFinite(n)&&n>0?n:C.test(String(e||""))?I["low"===t||"medium"===t||"max"===t?t:"high"]:void 0}function L(e,o,t){const n=String(o||"");if(N.test(n))return;if(null===t)return;const r="low"===t||"medium"===t?t:"max"===t?"max":"high";for(const o of q)if(o.provider===e&&o.re.test(n)){const e=Object.prototype.hasOwnProperty.call(o.map,r)?o.map[r]:o.extra&&Object.prototype.hasOwnProperty.call(o.extra,r)?o.extra[r]:void 0;if(void 0===e)return;return{field:o.field,level:e}}}const{offerableCatalog:O}=function(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withByokAdditions:U,canonicalModelId:P}=function(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withUserModels:R,unmatchedUserProviders:K,load:F,addUserModel:B,removeUserModel:G}=function(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{withCatalog:z}=function(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}(),{discoverModels:W,canDiscover:Y,endpointFor:H,discoverableProviders:J}=function(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}();function V(e){if(null==e)return{};if("object"==typeof e)return e;try{const o=JSON.parse(String(e));return o&&"object"==typeof o?o:{}}catch{return{}}}function X(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:V(e.args)}))).filter((e=>e.name));const o=e.choices&&e.choices[0]&&e.choices[0].message,t=o&&o.tool_calls||[];return Array.isArray(t)?t.map((e=>{const o=e&&e.function||{};return{id:e&&e.id||"",name:o.name||e&&e.name||"",args:V(o.arguments)}})).filter((e=>e.name)):[]}function Q(e){const o=Array.isArray(e.prompt)?r(e.prompt):e.prompt;if("string"==typeof o&&o.trim())return o;const t=Array.isArray(e.messages)?e.messages:[];for(let e=t.length-1;e>=0;e-=1){const o=t[e];if(!o||"user"!==o.role)continue;const n=r(o.content);if(n.trim())return n}return o}function Z(e){const o=e&&e.choices&&e.choices[0]&&e.choices[0].message;return o&&"string"==typeof o.content&&o.content||""}function ee(e){const o=e&&e.choices&&e.choices[0];return o&&o.finish_reason||e&&e.stop_reason||""}function oe(e){const o=ee(e);return"length"===o||"max_tokens"===o}function te(e){if(!e)return"";const o=e.choices&&e.choices[0],t=o&&o.message||{};if(Array.isArray(t.content)){const e=t.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const n=t.content&&"object"==typeof t.content?t.content.reasoning_content:"",r=[t.reasoning_content,t.reasoning,o&&o.reasoning_content,e.reasoning_content,e.reasoning,n];for(const e of r)if("string"==typeof e&&e)return e;return""}function ne(e){if(!e)return 0;const o=e.choices&&e.choices[0],t=o&&o.message||{},n=e.usage||{},r=n.completion_tokens_details||n.output_tokens_details||{},s=[t.thinking_tokens,t.reasoning_tokens,o&&o.thinking_tokens,e.thinking_tokens,r.reasoning_tokens,r.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function re(e){return!Z(e)&&(""!==te(e)||ne(e)>0)}function se(e,o){const t=ae(e.maxTokens);return o&&function(e){const o=Number(e);return Number.isFinite(o)&&Object.values(I).includes(o)}(e.maxTokens)?Math.max(t,32768):t}function ae(e){const o=Number(e)||0;return o>0?2*o:8192}const ie="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",le="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",ce=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function de(e,o,t){if(o)return!1;if(!(t>0))return!1;const n=String(e||"");return!!n.trim()&&!/\?\s*$/.test(n.trim())&&ce.test(n)}function ue({cls:e,model:o,finishReason:t,reasoningChars:n,reasoningTokens:r,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(r)||0,c=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${t||"none"}`+(s?`, effort: ${s}`:"")+(n?`, hidden reasoning: ${n} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(n||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}module.exports={CLASSES:_,createLocalEngine:function({aegis:o,settings:f,tools:h,promptBuilder:g,recallProvider:k,env:v,getConfirmMode:x,localTransport:A=a,fetchImpl:$,gitScope:C}){const I=new Map,N=h||t,q=g&&g.buildSystemPrompt||s.buildSystemPrompt,V=require("./session-rounds.js"),ce=()=>{if("function"==typeof x)return!1!==x();if(f&&"function"==typeof f.getConfirmMode){const e=f.getConfirmMode();return void 0===e||Boolean(e)}return!0},fe=new Map,pe=new Map,me=new Map,he=new Map,ge=new Map;function ye(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function ke(o,t,n,r){return new Promise((s=>{if(n&&n.aborted)return void s(!1);const a=e();let i=!1;const l=()=>c(!1),c=e=>{i||(i=!0,ge.delete(a),n&&n.removeEventListener("abort",l),s(e))};n&&n.addEventListener("abort",l,{once:!0}),ge.set(a,{resolve:c}),"function"==typeof t?t({delta:"",rounds:{id:a,sessionId:o,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):c(!1)}))}async function ve(e,o,t){const n=b(N,e,o,t||{});if(!n.ok)return{ok:!1,error:n.error};o=n.args;const r=t&&t.guard;if(r&&"exec"===e){const e=m(r,o&&o.command);if(!e.ok)return{ok:!1,error:e.reason}}const s=y.preActionAssert({tool:e,args:o||{}});if(!s.allowed){const t=y.bindRefusal({tool:e,args:o||{}},s);return{ok:!1,error:`refused by the ÆGIS covenant — ${s.clause} (${s.label}): ${s.reason}`,covenant:t}}const a=await N.executeTool(e,o,t);return r&&("writeFile"===e||"editFile"===e)&&a&&!1!==a.ok&&p(r,o&&o.file_path),a}async function we(o,{toolCtx:t,rootSessionId:n,rootOnDelta:r,signal:s}){const{name:a}=o,i=b(N,a,o.args,t||{});if(!i.ok)return{ok:!1,error:i.error};const l=i.args;if(!N.MUTATING_TOOLS.has(a))return ve(a,l,t);if(!ce())return ve(a,l,t);if(function(e,o){const t=fe.get(e);return Boolean(t&&t.has(o))}(n,a))return ve(a,l,t);if(function(e,o){const t=pe.get(e);return Boolean(t&&t.has(o))}(n,a))return{ok:!1,error:ye(a)};let c=null;if(("writeFile"===a||"editFile"===a)&&(c=N.previewMutation(a,l,t||{}),!c.ok))return{ok:!1,error:c.error};const d=await function(o,t,n,r){return new Promise((s=>{if(n&&n.aborted)return void s("cancel");const a=e();let i=!1;const l=()=>c("cancel"),c=e=>{i||(i=!0,he.delete(a),n&&n.removeEventListener("abort",l),s(e))};n&&n.addEventListener("abort",l,{once:!0}),he.set(a,{resolve:c}),"function"==typeof t?t({delta:"",approval:{id:a,sessionId:o,tool:r.tool,args:r.args,diff:r.diff||null}}):c("cancel")}))}(n,r,s,{tool:a,args:l,diff:c&&c.diff});if("deny"===d)return function(e,o){pe.has(e)||pe.set(e,new Set),pe.get(e).add(o)}(n,a),{ok:!1,error:ye(a)};if("session"!==d&&"once"!==d)return{ok:!1,error:`${a} was not executed — the request was cancelled.`};if("session"===d&&function(e,o){fe.has(e)||fe.set(e,new Set),fe.get(e).add(o)}(n,a),c){const e=N.applyChecked(a,l,c,t||{});return e&&!1!==e.ok&&t&&t.guard&&p(t.guard,l&&l.file_path),e}return ve(a,l,t)}function be(e){return S(v||{},e&&e.env||{},e)}async function xe(e,t){if("aegis"===e){const e=!t.singlePass&&(!!t.autonomous||void 0);return o.chatCompletion({prompt:t.prompt,system:t.system,messages:t.messages,model:t.model,mode:t.mode,maxTokens:t.statedMaxTokens,stream:!1!==t.stream,includeUsage:!0,onStream:t.onDelta,onReasoning:t.onReasoning,idleTimeoutMs:t.idleTimeoutMs,signal:t.signal,extra:{aegis_recall:!0,...t.recallDeep?{aegis_recall_deep:!0}:{},session:t.sessionId,...void 0===e?{}:{brain:e},...!1===e?{mode:"brain"}:{},...t.effort?{effort:t.effort}:{},...!0===e&&t.workers?{workers:t.workers}:{},...t.tools.length?{tools:t.tools}:{},...t.toolChoice?{tool_choice:t.toolChoice}:{}},agentKey:t.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===e){const{provider:n,model:r}=M(t.model),s=P(n,r),a=L(n,s,t.effort);try{return await o.byokChatCompletion({provider:n,model:s,providerKey:t.apiKey,baseURL:t.cfg&&t.cfg.baseURL,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,tools:t.tools,toolChoice:t.toolChoice,effort:a&&"effort"===a.field?a.level:void 0,reasoningEffort:a&&"reasoning_effort"===a.field?a.level:void 0,stream:!0,onStream:t.onDelta,signal:t.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===e){const o=t.cfg&&t.cfg.baseURL||A.DEFAULT_BASE,n=e=>A.chat({baseURL:o,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...e&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await n(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return n(!1);throw e}}if("pro"===e){const e=t.sessionKey||t.rootSessionId||t.sessionId,o=e?me.get(e):null,n=function(e){const o=[],t=e=>String(e||"").replace(/[\\/]+$/,""),n=t(e),r=e=>{const r=t(e);r&&r!==n&&!o.includes(r)&&o.push(r)};let s=C;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&r(s.gitRoot(e))}catch{}try{w&&"function"==typeof w.aegisHome&&r(w.aegisHome())}catch{}return o}(t.cwd),r=await c.runClaudePro({prompt:Q(t),model:t.model&&"default"!==t.model?t.model:void 0,system:t.system,cwd:t.cwd,addDir:n,resumeSessionId:o||void 0,gate:"function"==typeof x?!x():void 0,signal:t.signal,onDelta:t.onDelta,onSpawn:(e,o)=>{t.onDelta&&o&&t.onDelta({delta:"",note:c.childLine(o)})}});return e&&r&&r.sessionId&&!r.error&&me.set(e,r.sessionId),r}throw new Error(`dispatch: unknown model class ${JSON.stringify(e)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Se(t,s){const a=t&&t.class,d=t&&t.model,u=D("byok"===a?M(d).model:d,t&&t.maxTokens,t&&t.effort),p=function(e){const o=e=>{const o=Number(e);return Number.isFinite(o)&&o>0?o:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?o(e.statedMaxTokens):o(e&&e.maxTokens)}(t),m="aegis"===a&&Boolean(t&&t.autonomous),h=Boolean(t&&t.roundsAsk),g=t&&t.sessionId||e(),y=Number.isInteger(t&&t.depth)?t.depth:0,k=t&&t.rootSessionId||g,v=t&&t.rootOnDelta||s,w="function"==typeof s?e=>e&&s({reasoning:e}):void 0,b=new AbortController;I.set(g,b);const x=b.signal,S=!(t&&!1===t.tools),_=S?N.toolsFor({includeSubagent:y<4}):[],$=t&&t.toolChoice||null,C=t&&t.system||q(be(t)),L=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let O=L.length,U=t&&t.prompt||"";const P=String(U||""),R=Array.isArray(t&&t.attachments)?t.attachments.filter((e=>e&&"object"==typeof e)).slice(0,n.MAX_ATTACHMENTS):[];let F=R.length?n.buildContent(U,R):U,K=null;const B=be(t),G=B.cwd,z={getShell:()=>K||(K=new i({cwd:be(t).cwd})),signal:x,cwd:G,desktopdir:B.desktopdir};try{const e="byok"===a?M(d):null,i="byok"===a?f.get(T(e.provider))||{}:"local"===a&&f.get("local")||{},b="byok"===a?f.rawKey(T(e.provider)):null,I="byok"!==a?null:b||E(e.provider);if(!("byok"!==a||e.provider&&e.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(d||""));throw e.status=400,e}if("byok"===a&&!I){const o="anthropic"===e.provider?c.claudeProStatus({env:process.env}):null,t=j(e.provider).rejected,n=new Error(t?`${t}. That is why this turn has no ${e.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${t.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${e.provider} <key> to set one here.`:o&&o.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${o.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${e.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${e.provider} <key>.`);throw n.status=400,n}if("byok"===a&&!o.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===a){const e=A.remoteRefusal(i.baseURL||A.DEFAULT_BASE);if(e)throw e}if("byok"===a&&"custom"===e.provider&&!(i.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const q={cls:a,model:d,mode:t&&t.mode,maxTokens:u,statedMaxTokens:p,autonomous:m,sessionId:g,signal:x,onDelta:s,cfg:i,apiKey:I,toolChoice:$,cwd:G,rootSessionId:k,sessionKey:t&&t.sessionKey||void 0,effort:t&&t.effort,workers:t&&t.workers,recallDeep:t&&!0===t.recallDeep,singlePass:t&&!0===t.singlePass,onReasoning:w,idleTimeoutMs:m?9e5:void 0,stream:!t||!1!==t.stream};let D=!1,K=!1;const B=m?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",W=(()=>{const e=Number.parseInt(process.env[B]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=W||(m?40:24);let H=V.keyFor(t,L),J=V.take(H);if(!J&&!V.isStatedKey(t)){const e=V.adopt();e&&(J=e.entry,H=e.key)}if(J){const e=V.resumePreamble(J);0===L.length?Array.isArray(J.messages)&&J.messages.length&&L.push(...J.messages):Array.isArray(J.added)&&J.added.length&&L.push(...J.added),U?(U=`${e}\n\n${U}`,F=R.length?n.buildContent(U,R):U):(L.push({role:"user",content:e}),F=""),v&&v({delta:`\n\n[resuming work this session left unfinished at ${J.rounds} tool rounds`+(J.interruptions>1?` (cut off ${J.interruptions}×)`:"")+"…]\n"})}let Q=W||Y+(J?V.bonus(Y):0),ce=0;const fe=Y,pe=8;let me=0;const he={calls:0},ge=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],ye=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){he.calls+=1;for(const e of ge)"number"==typeof o[e]&&Number.isFinite(o[e])&&(he[e]=(he[e]||0)+o[e]);if("number"!=typeof o.total_tokens){const e=(o.prompt_tokens??o.input_tokens??0)+(o.completion_tokens??o.output_tokens??0);e&&(he.total_tokens=(he.total_tokens||0)+e)}}},ve=e=>e&&"object"==typeof e&&he.calls?{...e,usage:{...he}}:e,be=()=>{if(""===F)return;const e=L[L.length-1],o=e&&"user"===e.role?r(e.content):null;e&&"user"===e.role&&o===r(F)||L.push({role:"user",content:F}),U="",F=""};O=L.length;const Se=N&&N.MUTATING_TOOLS||new Set;let Ae=0,Te=0,Me=!1;for(;;){if(ce>=Q){if(h&&me<pe&&!x.aborted&&await ke(k,v,x,{spent:Q,extensions:me+1,max:pe,size:fe})){me+=1;const e=Q;Q+=fe,L.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${fe} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=h?"":`, or raise ${B} for a longer single turn`,o=`[stopped at ${Q} tool rounds`+(he.total_tokens?`, ${he.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=V.record(H,{rounds:ce,tokens:he.total_tokens||0,note:o,chain:J?J.interruptions:0,messages:L,added:L.slice(O)});return v&&v({delta:`\n\n${o}`}),ve({model:q.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:H})}ce+=1;const e={...q,system:C,messages:L,prompt:F,tools:_,recallDeep:q.recallDeep&&1===ce};let o;if(o=await xe(a,e),ye(o),x.aborted)return ve(o);if(!D&&!Z(o)&&(oe(o)||re(o))){D=!0;const t=re(o);if(o=await xe(a,{...e,singlePass:!0,recallDeep:!1,effort:t?"high":e.effort,maxTokens:se(e,t),statedMaxTokens:e.statedMaxTokens?ae(e.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}const n=_.length?X(o):[];if(!n.length){if(Z(o)||K||!S){if(!Me&&S&&de(P,Te>0,Ae)){Me=!0,be(),L.push({role:"assistant",content:Z(o)}),L.push({role:"user",content:"You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you."}),v&&v({delta:""});continue}return ve(o)}K=!0,be(),L.push({role:"user",content:re(o)?le:ie});const t={...e,singlePass:!0,recallDeep:!1,messages:L,prompt:"",tools:[]};o=await xe(a,t);let n=t.maxTokens,r=t.effort;if(ye(o),x.aborted)return ve(o);if(!Z(o)&&(oe(o)||re(o))){const e=re(o);if(n=se(t,e),r=e?"high":t.effort,o=await xe(a,{...t,effort:r,maxTokens:n,statedMaxTokens:t.statedMaxTokens?ae(t.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}const s=(()=>{const e=Number(n)||0;if(!e)return n;const o={maxTokens:n};return t.statedMaxTokens&&(o.statedMaxTokens=t.statedMaxTokens),Math.max(e,se(o,!0))})();let i=0;for(;!Z(o)&&i<2&&!x.aborted;){const e=re(o);if(i+=1,L.push({role:"user",content:e?1===i?le:"Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.":ie}),e&&(r="high"),n=s,o=await xe(a,{...t,messages:L,effort:r,maxTokens:n,statedMaxTokens:t.statedMaxTokens?ae(t.statedMaxTokens):void 0}),ye(o),x.aborted)return ve(o)}if(!Z(o))throw ue({cls:a,model:d,effort:r,recoveryRounds:i,finishReason:ee(o),reasoningChars:te(o).length,reasoningTokens:ne(o)});return ve(o)}be(),L.push({role:"assistant",content:Z(o),tool_calls:n.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const r=new WeakMap,i=e=>{if("exec"!==e.name)return null;if(r.has(e))return r.get(e);const o=l(e.args&&e.args.command,{baseCwd:G});return r.set(e,o),o},c=e=>{if(e.name===N.SUBAGENT_TOOL)return!1;if(!Se.has(e.name))return!0;const o=i(e);return Boolean(o&&o.oneShot)},u=[];for(const e of n){const o=u[u.length-1];c(e)&&o&&o.parallel?o.calls.push(e):u.push({parallel:c(e),calls:[e]})}const f=async e=>{s&&s({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:G,phase:"run"}});const o=i(e),n=o&&o.oneShot?{...z,oneShotExec:!0,cwd:o.cwd||z.cwd}:z,r=e.name===N.SUBAGENT_TOOL?await _e(e.args,{cls:a,model:d,statedMaxTokens:p,effort:t&&t.effort,mode:t&&t.mode,parentSignal:x,depth:y,rootSessionId:k,rootOnDelta:v}):await we(e,{toolCtx:n,rootSessionId:k,rootOnDelta:v,signal:x});return r&&r.usage&&ye({usage:r.usage}),s&&s({delta:"",tool:{name:e.name,args:e.args,ok:r.ok,id:e.id,cwd:G,phase:"done"}}),r};for(const e of u){const o=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>f(e)))):[await f(e.calls[0])];e.calls.forEach(((e,t)=>{const n=o[t];Se.has(e.name)&&(Ae+=1,n&&n.ok&&(Te+=1)),L.push({role:"tool",tool_call_id:e.id,name:e.name,content:N.toolResultText(n)})}))}}}catch(e){throw x.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{K&&K.dispose(),I.delete(g)}}async function _e({description:o,subagent_type:t,prompt:n}={},{cls:r,model:s,statedMaxTokens:a,effort:i,mode:l,parentSignal:c,depth:f,rootSessionId:p,rootOnDelta:m}={}){const h=String(n||o||"").trim();if(!h)return{ok:!1,error:"task requires a prompt"};const g=t&&"general"!==t?u(t):"general",y=d(t),k=e();let v;if(c){if(c.aborted)return{ok:!1,error:"aborted"};v=()=>Ae(k),c.addEventListener("abort",v,{once:!0})}try{const e=await Se({class:r,model:s,mode:l,system:y,prompt:h,sessionId:k,depth:(f||0)+1,rootSessionId:p,rootOnDelta:m,statedMaxTokens:a,effort:i},(()=>{})),o=Z(e),t=e&&e.usage?{usage:e.usage}:{};return o?{ok:!0,output:o,...t}:{ok:!1,error:`subagent (${g}) produced no output`,...t}}catch(e){return{ok:!1,error:`subagent (${g}) failed: ${e&&e.message?e.message:e}`}}finally{c&&v&&c.removeEventListener("abort",v)}}function Ae(e){const o=I.get(e);return o&&o.abort(),{ok:Boolean(o)}}return{CLASSES:_,listClasses:async function(){return _.map((e=>{if("aegis"===e.class)return{...e,configured:Boolean(o.apiKey)};if("byok"===e.class){const o=(f.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(E(e.provider.slice(5))))));return{...e,configured:o}}if("local"===e.class)return{...e,configured:!0};if("pro"===e.class){const o=c.claudeProStatus({env:process.env}),t=c.seamAvailable();return{...e,configured:o.loggedIn,status:o,seam:t}}return{...e,configured:!1}}))},listModels:async function(e){if("aegis"===e){if(!o.apiKey)return{class:e,models:[],needsKey:!0};const n=await o.listModels();return{class:e,models:O((t=n&&n.models,Array.isArray(t)?t.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]))}}var t;if("byok"===e){let t=[],n=null,r=!1,s=null;try{const e=await o.byokProviders();t=R(z(U(e&&e.providers||[]))),n=e&&e.fee||null}catch(e){t=[],r=!0,s=e&&e.message||String(e)}const a=[];for(const e of t){if(!e||!e.id)continue;const o=f.get(T(e.id))||{},t=j(e.id),n=t.key||"",r=Array.isArray(e.models)?e.models:[];for(const s of r){const r="string"==typeof s?s:s&&s.id;r&&a.push({id:`${e.id}:${r}`,label:`${e.label||e.id} — ${r}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:t.rejected||null})}}return{class:e,models:a,providers:t,needsProviderKey:a.length>0&&!a.some((e=>e.configured)),needsAegisKey:!o.apiKey,fee:n,providersFailed:r,providersError:s,unmatchedProviders:K(t)}}if("local"===e){const o=(f.get("local")||{}).baseURL||A.DEFAULT_BASE,t=await A.probe(o);if(!t.running)return{class:e,models:[],baseURL:t.baseURL,needsDaemon:!0};let n=[],r=!0;try{n=await A.listTags(o)}catch{r=!1}return{class:e,models:n,baseURL:t.baseURL,listed:r}}if("pro"===e){const o=c.claudeProStatus({env:process.env});return{class:e,models:c.PRO_MODELS.map((e=>({id:e.id,label:e.label,note:e.note,configured:o.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:o.subscription,loggedIn:o.loggedIn,credentialFile:o.file,shadowed:o.shadowed||null,seam:c.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(e)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Se,cancel:Ae,respondApproval:function(e,o){const t=he.get(e);return t?(he.delete(e),t.resolve("session"===o||"once"===o?o:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,o){const t=ge.get(e);return t?(ge.delete(e),t.resolve(!0===o||"continue"===o),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){return fe.delete(e),pe.delete(e),me.delete(e),{ok:!0}},settings:f,unloadLocalModels:function(){return A.unloadAll()},userModels:()=>F(),addUserModel:(e,o)=>B(e,o),removeUserModel:(e,o)=>G(e,o),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),t=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(f&&"function"==typeof f.rawKey){const e=f.rawKey(T(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return E(o)}(o),n=await W(o,{key:t,fetchImpl:$});if(!n||!n.ok)return n;const r=[];try{const e=F().map;for(const t of Array.isArray(e[o])?e[o]:[])r.push(t)}catch{}return{...n,declared:r,endpoint:(H(o)||{}).url||""}},addUserModels:(e,o)=>{const t=Array.isArray(o)?o:[],n={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const o of t)try{const t=B(e,o);n.file=t.file||n.file,t.added?n.added+=1:n.already.push(t.model)}catch(e){const r=e&&e.message||String(e);if(/the cap/.test(r)){n.capped=t.length-n.added-n.already.length-n.failed.length;break}n.failed.push({id:String(o),reason:r})}return n},canDiscoverModels:e=>Y(e),discoverableProviders:()=>J()}},extractToolCalls:X,parseArgs:V,reasoningBudget:D,nativeEffort:L,hostEnv:S};