aegiscode 7.0.14 → 7.0.16

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