aegiscode 7.0.13 → 7.0.15

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 +3 -2
  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 -3008
  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 -3987
  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 -2054
  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 -85
  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 -125
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -330
  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 -3228
  90. package/vendor/desktop/lib/local/entitlement.js +1 -654
  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,3230 +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
- load: loadUserModels,
749
- addUserModel,
750
- removeUserModel,
751
- } = requireSharedUserModels();
752
- const {
753
- discoverModels: discoverVendorModels,
754
- canDiscover: canDiscoverVendorModels,
755
- endpointFor: vendorEndpointFor,
756
- discoverableProviders,
757
- } = requireSharedModelDiscovery();
758
-
759
- // ── Agent-loop helpers ──────────────────────────────────────────────────────
760
-
761
- /** Parse a model-supplied argument blob (string or already-parsed object). */
762
- function parseArgs(raw) {
763
- if (raw == null) return {};
764
- if (typeof raw === 'object') return raw;
765
- try {
766
- const v = JSON.parse(String(raw));
767
- return v && typeof v === 'object' ? v : {};
768
- } catch {
769
- return {};
770
- }
771
- }
772
-
773
- /**
774
- * Pull normalised tool calls out of whichever shape the transport returned:
775
- * the shared `result.toolCalls` both local parsers emit, or a provider-native
776
- * `choices[0].message.tool_calls` (the Aegis pool relays the upstream OpenAI
777
- * shape verbatim).
778
- */
779
- function extractToolCalls(res) {
780
- if (!res) return [];
781
- if (Array.isArray(res.toolCalls) && res.toolCalls.length) {
782
- return res.toolCalls
783
- .map((c) => ({ id: c.id || '', name: c.name || '', args: parseArgs(c.args) }))
784
- .filter((c) => c.name);
785
- }
786
- const msg = res.choices && res.choices[0] && res.choices[0].message;
787
- const raw = (msg && msg.tool_calls) || [];
788
- if (!Array.isArray(raw)) return [];
789
- return raw
790
- .map((tc) => {
791
- const fn = (tc && tc.function) || {};
792
- return { id: (tc && tc.id) || '', name: fn.name || (tc && tc.name) || '', args: parseArgs(fn.arguments) };
793
- })
794
- .filter((c) => c.name);
795
- }
796
-
797
- /** The textual content of one assistant turn (empty when it only called tools). */
798
- /**
799
- * The prompt a Pro turn actually hands the child.
800
- *
801
- * `pro` is the one class that does not replay `opts.messages` into its
802
- * transport: the `claude` child runs its own agent loop, so sending this
803
- * engine's transcript would make it re-run every tool call a second time. That
804
- * decision is right for an ordinary turn and silently wrong for the engine's
805
- * RE-ASK rounds — the synthesis pass and the recovery ladder both re-dispatch
806
- * with `prompt: ''` plus a grown `messages`, which is the shape every other
807
- * class reads as "continue this conversation; the new instruction is the last
808
- * user message in the history". The Pro branch read only `opts.prompt`, so each
809
- * of those rounds spawned `claude -p ''`: an empty prompt, on a child whose
810
- * stdin is `'ignore'`, with `--resume` as its only other context.
811
- *
812
- * The consequence was the failure this function exists to prevent. A Pro turn
813
- * whose first round came back empty could never be recovered, because every
814
- * recovery round was guaranteed empty too — the ladder then reported "2 extra
815
- * recovery calls with a larger budget and a changed ask came back empty too"
816
- * over a transport that had been asked nothing at all. Measured on
817
- * claude-code-pro, 2026-10-11.
818
- *
819
- * So when a round carries no prompt of its own, the LAST user message in
820
- * `opts.messages` becomes the child's prompt. The nudges the ladder appends are
821
- * exactly that, and `--resume` reattaches the child to its own session, so the
822
- * instruction lands in a conversation that already holds the findings — which
823
- * is what makes the recovery round a re-ask rather than a fresh, empty one.
824
- *
825
- * An ordinary turn is untouched: it has its own prompt, so the first branch
826
- * returns before `messages` is ever consulted.
827
- */
828
- function proTurnPrompt(opts) {
829
- const own = typeof opts.prompt === 'string' ? opts.prompt.trim() : '';
830
- if (own) return opts.prompt;
831
- const messages = Array.isArray(opts.messages) ? opts.messages : [];
832
- for (let i = messages.length - 1; i >= 0; i -= 1) {
833
- const m = messages[i];
834
- if (!m || m.role !== 'user') continue;
835
- if (typeof m.content === 'string' && m.content.trim()) return m.content;
836
- }
837
- // Nothing to borrow: keep the caller's own value rather than inventing text,
838
- // so a round with genuinely no ask still reaches the ladder and is reported
839
- // as the empty round it is.
840
- return opts.prompt;
841
- }
842
-
843
- function assistantText(res) {
844
- const msg = res && res.choices && res.choices[0] && res.choices[0].message;
845
- return (msg && typeof msg.content === 'string' && msg.content) || '';
846
- }
847
-
848
- /**
849
- * The provider's stop reason for a completion ('' when it sent none). The two
850
- * wire formats report it in different places and both have to be read: the
851
- * OpenAI shape carries `choices[0].finish_reason` (this is what providers.js
852
- * and vendor/aegis.js emit), while providers.js's Anthropic parser puts
853
- * `stop_reason` on the result and never sets a finish_reason on the choice.
854
- */
855
- function finishReasonOf(res) {
856
- const choice = res && res.choices && res.choices[0];
857
- return (choice && choice.finish_reason) || (res && res.stop_reason) || '';
858
- }
859
-
860
- /**
861
- * True when the provider cut the answer off at the token budget instead of
862
- * the model choosing to stop. This is the diagnosis for the most common
863
- * flavour of the empty turn: DeepSeek (and other reasoning models that bill
864
- * hidden chain-of-thought against max_tokens) can spend the entire budget
865
- * before emitting a single visible token, and the completion still arrives
866
- * as a clean `finish_reason: 'length'` — no error, empty content. A tool
867
- * call whose JSON was truncated mid-argument lands here too, where
868
- * parseArgs() would otherwise silently yield `{}` and run the tool with no
869
- * arguments, which is worse than retrying.
870
- */
871
- function isTruncated(res) {
872
- const reason = finishReasonOf(res);
873
- // 'length' is OpenAI's wording, 'max_tokens' is Anthropic's — same event.
874
- return reason === 'length' || reason === 'max_tokens';
875
- }
876
-
877
- /**
878
- * The hidden chain-of-thought a completion carried, read from every wire shape
879
- * that reports one. DeepSeek returns `message.reasoning_content`, OpenAI's
880
- * o-series/gpt-5 shape returns `message.reasoning`, and the Anthropic parser
881
- * folds thinking into content blocks. All three are the same thing here: tokens
882
- * the model spent out of the same budget as its answer.
883
- */
884
- function reasoningTextOf(res) {
885
- if (!res) return '';
886
- const choice = res.choices && res.choices[0];
887
- const msg = (choice && choice.message) || {};
888
- if (Array.isArray(msg.content)) {
889
- const blocks = msg.content
890
- .filter((b) => b && (b.type === 'thinking' || b.type === 'reasoning'))
891
- .map((b) => b.thinking || b.text || '')
892
- .join('');
893
- if (blocks) return blocks;
894
- }
895
- const fromContent = msg.content && typeof msg.content === 'object' ? msg.content.reasoning_content : '';
896
- const candidates = [
897
- msg.reasoning_content,
898
- msg.reasoning,
899
- choice && choice.reasoning_content,
900
- res.reasoning_content,
901
- res.reasoning,
902
- fromContent,
903
- ];
904
- for (const c of candidates) if (typeof c === 'string' && c) return c;
905
- return '';
906
- }
907
-
908
- /**
909
- * Deliberation the provider MEASURED but withheld, in tokens.
910
- *
911
- * The companion to `reasoningTextOf()` above, for the one case where there is no
912
- * text to read: Claude Code Pro runs extended thinking by default and withholds
913
- * the deliberation itself, so `thinking_delta.thinking` arrives as the empty
914
- * string while the billed count climbs. A round like that carries real reasoning
915
- * and no reasoning TEXT, so a text-only predicate reads it as "the model said
916
- * nothing" — the wrong diagnosis, and the one that made a Pro turn report
917
- * "No visible text came back" while the child had in fact been thinking.
918
- *
919
- * Read from the message shape first (what `claude-pro.js` `proMessage()` sets)
920
- * and then from the standard usage detail `completion_tokens_details.
921
- * reasoning_tokens`, so a provider that meters deliberation on the usage
922
- * envelope is seen too.
923
- */
924
- function reasoningTokensOf(res) {
925
- if (!res) return 0;
926
- const choice = res.choices && res.choices[0];
927
- const msg = (choice && choice.message) || {};
928
- const usage = res.usage || {};
929
- const details = usage.completion_tokens_details || usage.output_tokens_details || {};
930
- const candidates = [
931
- msg.thinking_tokens,
932
- msg.reasoning_tokens,
933
- choice && choice.thinking_tokens,
934
- res.thinking_tokens,
935
- details.reasoning_tokens,
936
- details.thinking_tokens,
937
- ];
938
- for (const c of candidates) {
939
- if (typeof c === 'number' && Number.isFinite(c) && c > 0) return c;
940
- }
941
- return 0;
942
- }
943
-
944
- /**
945
- * The empty turn `isTruncated()` cannot see, and the reason this error survived
946
- * a truncation retry that was already in place: a reasoning model that spends
947
- * the budget on hidden chain-of-thought and then finishes with NO visible text
948
- * still reports `finish_reason: 'stop'` — the provider considers the call
949
- * complete, because to it the model did stop, it just stopped while thinking.
950
- * Measured live on byok/deepseek-v4-flash: `stop` + empty content + non-empty
951
- * `reasoning_content`, which fell straight through both retry gates to
952
- * emptyTurnError. Reasoning tokens and answer tokens share one budget, so the
953
- * recovery is identical to a 'length' cut: buy room and ask once more.
954
- *
955
- * A round with no reasoning TEXT but a non-zero reasoning-token count counts as
956
- * reasoning here: that is a Pro turn whose deliberation was withheld, and
957
- * treating it as genuinely empty is what sent it to the generic nudge instead
958
- * of the ask that names the problem.
959
- */
960
- function reasonedButSilent(res) {
961
- return !assistantText(res) && (reasoningTextOf(res) !== '' || reasoningTokensOf(res) > 0);
962
- }
963
-
964
- /**
965
- * The rung a reasoning-only retry is raised to. Every reasoning retry is paid
966
- * for out of the same budget twice — the chain-of-thought is paid for again
967
- * before a single visible word can be written — so a rung that merely doubled
968
- * (the 8k floor -> 16k) still finished silent: the floor is what an unstated
969
- * budget yields, and it is the rung the live failure had already exhausted.
970
- */
971
- const REASONING_RETRY_FLOOR = 32768;
972
-
973
- /**
974
- * The one budget decision every empty-turn retry makes, in one place: is the
975
- * number we hold ours (a rung we derived, which a retry may raise) or the
976
- * caller's (a deliberate cap the retry may only double)?
977
- *
978
- * It matters exactly here. The floor above is a floor on OUR rung; applying it
979
- * to a stated cap would turn the flow lane's deliberate 1024-token ceiling into
980
- * 32768 because the model happened to think out loud — the same "a guessed
981
- * number goes on the wire as a ceiling" bug statedCapOf() exists to prevent.
982
- */
983
- function retryBudgetFor(opts, reasoningOnly) {
984
- const doubled = doubledBudget(opts.maxTokens);
985
- if (!reasoningOnly) return doubled;
986
- // Which number is this? A budget that is one of EFFORT_TOKEN_BUDGET's own
987
- // rungs (8192/16384/32768) is the rung this call was sized at, so a reasoning
988
- // retry may raise it to the top of the ladder — that is the live failure this
989
- // exists for: 16384 burned on hidden chain-of-thought, finish_reason 'stop',
990
- // empty content. Any OTHER number belongs to someone who chose it (the flow
991
- // lane's deliberate 1024, a caller's own 4096), and doubling is as far as a
992
- // retry may go: promoting it by an order of magnitude would put a ceiling the
993
- // user never asked for on the wire.
994
- return ladderRung(opts.maxTokens) ? Math.max(doubled, REASONING_RETRY_FLOOR) : doubled;
995
- }
996
-
997
- /** Is this budget one of the effort ladder's own rungs (a size WE derived)? */
998
- function ladderRung(maxTokens) {
999
- const n = Number(maxTokens);
1000
- return Number.isFinite(n) && Object.values(EFFORT_TOKEN_BUDGET).includes(n);
1001
- }
1002
-
1003
- /**
1004
- * Double a budget for the one-shot truncation retry. A budget the caller set
1005
- * on purpose (the flow lane's deliberate 1024-token cap, say) is merely
1006
- * doubled — the floor only applies when nothing was set at all, so a retry
1007
- * can never silently override a small cap by an order of magnitude.
1008
- */
1009
- function doubledBudget(maxTokens) {
1010
- const n = Number(maxTokens) || 0;
1011
- return n > 0 ? n * 2 : 8192;
1012
- }
1013
-
1014
- /**
1015
- * The cap the CALLER stated, or `undefined` meaning "none was stated".
1016
- *
1017
- * The two branches resolve one question — whose number is this? — and the
1018
- * first is the fix. An internal re-entry (runSubagent's nested chat()) passes
1019
- * `statedMaxTokens` explicitly, because the `maxTokens` it holds is the rung
1020
- * reasoningBudget() derived from `effort`: a number the server is about to
1021
- * derive for itself. Re-reading that value as the caller's own is what put a
1022
- * guessed 32768 on the wire as a *ceiling over* aegis1's ladder
1023
- * (pass_budgets: total = min(ladder, max_tokens x passes)) — so a
1024
- * high-effort subagent silently ran at 8192 and the ladder the UI advertised
1025
- * was not the budget the call used.
1026
- *
1027
- * A non-numeric or non-positive value means "nothing stated" — never a 0- or
1028
- * NaN-token ceiling.
1029
- */
1030
- function statedCapOf(payload) {
1031
- const asCap = (v) => {
1032
- const n = Number(v);
1033
- return Number.isFinite(n) && n > 0 ? n : undefined;
1034
- };
1035
- if (payload && Object.prototype.hasOwnProperty.call(payload, 'statedMaxTokens')) {
1036
- return asCap(payload.statedMaxTokens);
1037
- }
1038
- return asCap(payload && payload.maxTokens);
1039
- }
1040
-
1041
- /**
1042
- * The follow-up shown to a model that ended its turn with neither text nor a
1043
- * tool call. Sent as a plain user message (never as a tool result — there is
1044
- * no pending tool call to answer) so every provider accepts it verbatim.
1045
- */
1046
- const EMPTY_TURN_NUDGE =
1047
- 'Your previous reply came back empty — it contained no answer and no tool call. ' +
1048
- 'Write your answer now, using only the information already gathered above. ' +
1049
- 'No tools are available in this reply, so do not call any: respond in plain ' +
1050
- 'prose or markdown.';
1051
-
1052
- /**
1053
- * The nudge for an empty round that was NOT really empty: the model spent it
1054
- * thinking. A reasoning model that burns its budget on hidden chain-of-thought
1055
- * and stops without writing a visible word (`finish_reason: 'stop'`, empty
1056
- * content, non-empty `reasoning_content`) is the normal shape of this failure on
1057
- * DeepSeek, and the generic nudge above does not describe it — "write your answer
1058
- * now" invites the same reasoning pass a second time, because nothing told the
1059
- * model that the thinking was the problem.
1060
- *
1061
- * Naming the failure IS the fix, and it is the upstream engine's own last resort
1062
- * (`src/backend.js`, the `thoughtOnly` recovery round). Buying budget is the
1063
- * other lever, already tried below; when that has failed the budget is not what
1064
- * is wrong, so the ask changes instead: answer WITHOUT thinking first.
1065
- */
1066
- const THOUGHT_ONLY_NUDGE =
1067
- 'Your previous round was spent entirely on hidden reasoning and produced no visible reply. ' +
1068
- 'Answer the user directly and briefly now. Do not reason, explain, or think first — write only ' +
1069
- 'the answer, no tools.';
1070
-
1071
- /**
1072
- * The last ask of the recovery ladder, for a turn that stayed silent even after
1073
- * being told not to think first.
1074
- *
1075
- * A model that is going to reason anyway will reason whatever the nudge says, so
1076
- * the final round stops asking it not to: the ask becomes "say anything usable
1077
- * about what you already have", which a model that has demonstrably read the
1078
- * context can always satisfy. Producing a slightly thin write-up is strictly
1079
- * better than the alternative — the transcript keeps the answer, and the user
1080
- * can ask for detail on the one point that was skimped, in a turn where the
1081
- * material is already in context.
1082
- */
1083
- const FINAL_ANSWER_NUDGE =
1084
- 'Write your answer now, in plain prose, using only what is already in this conversation. ' +
1085
- 'If your information is incomplete, say what you have and what is missing — an incomplete ' +
1086
- 'answer is the expected outcome here and is better than none. No tools, no preface.';
1087
-
1088
- /**
1089
- * How many EXTRA calls an empty write-up round is worth before the turn is
1090
- * declared failed.
1091
- *
1092
- * The upstream engine spends additional calls on a silent round rather than
1093
- * telling the reader to go and change a setting (`src/backend.js`'s thoughtOnly
1094
- * recovery), and this is the same trade, made explicit because the trade is the
1095
- * whole point of the number: an extra dispatch costs tokens, a failed turn costs
1096
- * the entire investigation the tool log on screen paid for. Two calls — one
1097
- * after the budget-retry above, one after the ask changes — is where the curve
1098
- * flattens: measured on byok/deepseek-v4-flash, a round that reasons and stays
1099
- * silent either answers on the first changed ask or is not going to answer at
1100
- * all, because the failure is the model's habit and not the wording.
1101
- *
1102
- * Crucially, every one of these rounds runs with `tools: []` on `synthesisOpts`:
1103
- * they re-ask for the write-up out of a context that already holds the findings,
1104
- * so "more calls" can never mean "do the investigation again".
1105
- */
1106
- const RECOVERY_ROUNDS = 2;
1107
-
1108
- /**
1109
- * Last resort for a turn that is still empty after the synthesis pass.
1110
- *
1111
- * Throws rather than returning the blank completion. Returning it is what
1112
- * produces the renderer's undiagnosable "(empty response)" bubble, and
1113
- * synthesising fake assistant text instead would be worse: renderer/app.js
1114
- * persists whatever comes back as the assistant's own message and syncs it
1115
- * to the aegis account, so the notice would re-enter the model's context on
1116
- * the next turn as something it had said. Failing loudly leaves the turn's
1117
- * real tool log on screen, keeps the transcript honest, and names the cause
1118
- * (renderer prints `Error: <message>`).
1119
- */
1120
- function emptyTurnError({ cls, model, finishReason, reasoningChars, reasoningTokens, effort, recoveryRounds }) {
1121
- const calls = Number(recoveryRounds) || 0;
1122
- // A withheld deliberation has no chars to count, so the two signals are
1123
- // reported as the one fact they both are: the round spent its output on
1124
- // thinking. Without this the Pro case printed "No visible text came back from
1125
- // any of those calls", which describes a transport that produced nothing —
1126
- // the opposite of a child that reasoned at length and wrote no answer.
1127
- const tokens = Number(reasoningTokens) || 0;
1128
- const reasoned = !!reasoningChars || tokens > 0;
1129
- const reasonClause = reasoningChars
1130
- ? `, hidden reasoning: ${reasoningChars} chars and no visible text`
1131
- : tokens > 0
1132
- ? `, ~${tokens} thinking tokens billed and no visible text`
1133
- : '';
1134
- const err = new Error(
1135
- `The model returned no answer after ${cls}/${model} was asked to summarise its results` +
1136
- (calls
1137
- ? `, and ${calls} extra recovery call${calls === 1 ? '' : 's'} with a larger budget ` +
1138
- 'and a changed ask came back empty too'
1139
- : '') +
1140
- ` (stop reason: ${finishReason || 'none'}` +
1141
- `${effort ? `, effort: ${effort}` : ''}` +
1142
- `${reasonClause}). ` +
1143
- (reasoned
1144
- ? // Deliberately NOT "raise the Effort rung". The budget was already taken
1145
- // out of the equation before this error could be reached: the recovery
1146
- // calls above ran at the top of the ladder, so pointing at the ceiling
1147
- // would send the reader to change the one setting that is already
1148
- // maxed out. The unchanged thing is the model's habit of answering
1149
- // inside its head, and that is what gets named.
1150
- 'Every one of those calls spent its output on hidden reasoning instead of writing a ' +
1151
- 'word, so this is the model rather than the budget: pick a model that answers without ' +
1152
- 'a thinking pass, or ask for a smaller piece of work.'
1153
- : 'No visible text came back from any of those calls. Send the request again, in smaller ' +
1154
- 'pieces, or from a different model.')
1155
- );
1156
- err.status = 502;
1157
- return err;
1158
- }
1159
-
1160
- function createLocalEngine({
1161
- aegis,
1162
- settings,
1163
- tools,
1164
- promptBuilder,
1165
- // The level's recall breadth, injected by the host that owns the
1166
- // avatar ledger (desktop/main.js builds one from lib/avatar/turn.js). It is a
1167
- // SEAM rather than a call into lib/avatar/* because this engine is shared with
1168
- // the CLI (cli/src/deps.js loads this file): the engine must not grow a
1169
- // dependency on the desktop's avatar directory, and a host with no avatar
1170
- // simply passes nothing and gets the exact pre-Phase-20 turn.
1171
- //
1172
- // `recallProvider({ payload, env, system })` may be sync or async and returns
1173
- // either the final system prompt or `{ system }`. It runs once per turn,
1174
- // before the first dispatch, and its result is the system prompt every round
1175
- // of that turn travels with.
1176
- recallProvider,
1177
- env,
1178
- getConfirmMode,
1179
- // Injectable for tests; defaults to the real transport so every existing
1180
- // caller (desktop/main.js, the CLI's deps.js) wires the local class by
1181
- // simply existing.
1182
- localTransport: localT = localTransport,
1183
- // Injectable for tests (and for a host that fronts the network itself): the
1184
- // fetch used ONLY by `discoverModels`, which asks a vendor's list API. Every
1185
- // other request in this file goes through `localT`, so this is deliberately
1186
- // not the transport — discovery is an outbound call to api.<vendor>, not to
1187
- // the AEGIS relay. Undefined in production, which means the global fetch.
1188
- fetchImpl,
1189
- // Injectable for tests, like `localTransport` above: the git half of the Pro
1190
- // child's sandbox widening (proAddDirs). Production passes nothing and the
1191
- // real `./git-scope.js` is resolved at call time.
1192
- gitScope,
1193
- }) {
1194
- const controllers = new Map(); // sessionId -> AbortController
1195
- const T = tools || toolsModule;
1196
- const buildSystemPrompt = (promptBuilder && promptBuilder.buildSystemPrompt) || promptModule.buildSystemPrompt;
1197
-
1198
- /** "Confirm before running tools" (Settings toggle, persisted by
1199
- * lib/settings.js. Because gatedExecuteTool is called for EVERY tool round
1200
- * it is read per call, not captured once at construction: flipping the
1201
- * switch takes effect on the next tool call, with no restart.
1202
- * An explicit `getConfirmMode` factory arg wins (used by tests); then the
1203
- * settings store's own accessor; then the safe default — ON, i.e. the gate
1204
- * stays up, so a store that predates the toggle can never silently
1205
- * disable it. */
1206
- // Session-scoped round accounting (lib/local/session-rounds.js): the
1207
- // tool-round cap is held against the *session* rather than the single turn,
1208
- // so a turn that reaches its horizon is resumed by the next turn in the same
1209
- // conversation instead of being cut off with the work lost. Module-level
1210
- // state, so it survives `send()` and even a fresh engine instance.
1211
- const sessionRounds = require('./session-rounds.js');
1212
- const confirmModeEnabled = () => {
1213
-
1214
- if (typeof getConfirmMode === 'function') return getConfirmMode() !== false;
1215
- if (settings && typeof settings.getConfirmMode === 'function') {
1216
- const value = settings.getConfirmMode();
1217
- return value === undefined ? true : Boolean(value);
1218
- }
1219
- return true;
1220
- };
1221
-
1222
- // ── Tool-call approval gate (renderer confirms exec/writeFile/editFile
1223
- // before they run) ─────────────────────────────────────────────────────
1224
- //
1225
- // `sessionAllowlists` is keyed by the CONVERSATION's root session id (the
1226
- // one the renderer's `send()` mints once per thread and reuses across
1227
- // turns — see rootSessionId below), never by the per-call sessionId a
1228
- // subagent gets, so "allow for this session" reads the way the user sees
1229
- // it: one decision per open conversation, not per nested tool round.
1230
- // In-memory only, on purpose — never persisted, so a restart (or
1231
- // newChat()'s clearSessionApprovals) always starts from a clean gate.
1232
- const sessionAllowlists = new Map(); // rootSessionId -> Set<toolName>
1233
- // Denials are remembered for the same reason allows are, mirroring it for
1234
- // the other answer. Without this, a "Deny" was forgotten the instant it was
1235
- // given: the model read `… the user denied the request`, re-planned, called
1236
- // the SAME tool again, and the gate raised a SECOND card — so one "no" cost
1237
- // the user a prompt per round for up to maxRounds (24 chat / 40 autonomous)
1238
- // rounds, each round re-sending the whole conversation to the provider. A
1239
- // gate that only remembers "yes" turns a single click into a retry storm;
1240
- // remembering "no" makes the first answer stick.
1241
- const sessionDenials = new Map(); // rootSessionId -> Set<toolName>
1242
- // ── Pro-class conversation continuity ────────────────────────────────────
1243
- //
1244
- // `claude` keeps its own session store, and the Pro child is spawned fresh
1245
- // for every turn. Continuity therefore has to be carried by US: the session
1246
- // id the child reports is remembered here, keyed by the CONVERSATION's root
1247
- // session id, and handed back as `--resume` on the next turn. Without this
1248
- // map every Pro turn is a brand-new conversation — the child is told nothing
1249
- // about the prior turns, because `pro` has no `messages` channel (the child
1250
- // runs its own agent loop), so "Claude has no memory of this conversation"
1251
- // was literally true.
1252
- //
1253
- // Keyed by root, like the allowlists above: one thread, one memory. In-memory
1254
- // only, and cleared by the same newChat()/`/clear` hook that clears the gate,
1255
- // because "clear the conversation" must clear what the child remembers too —
1256
- // a resumed child would otherwise answer from turns the user just erased.
1257
- const proSessions = new Map(); // rootSessionId -> child session UUID
1258
- const pendingApprovals = new Map(); // approvalId -> { resolve }
1259
- const pendingRoundAsks = new Map(); // askId -> { resolve }
1260
-
1261
- function sessionAllows(rootId, name) {
1262
- const set = sessionAllowlists.get(rootId);
1263
- return Boolean(set && set.has(name));
1264
- }
1265
-
1266
- function allowForSession(rootId, name) {
1267
- if (!sessionAllowlists.has(rootId)) sessionAllowlists.set(rootId, new Set());
1268
- sessionAllowlists.get(rootId).add(name);
1269
- }
1270
-
1271
- /** Has this conversation already refused this tool? Checked before the card
1272
- * is raised, so a repeat call is refused outright instead of re-prompting. */
1273
- function sessionDenies(rootId, name) {
1274
- const set = sessionDenials.get(rootId);
1275
- return Boolean(set && set.has(name));
1276
- }
1277
-
1278
- function denyForSession(rootId, name) {
1279
- if (!sessionDenials.has(rootId)) sessionDenials.set(rootId, new Set());
1280
- sessionDenials.get(rootId).add(name);
1281
- }
1282
-
1283
- /**
1284
- * The text a refused tool hands back to the model. The old one-line
1285
- * `"<tool> was not executed — the user denied the request."` read to a
1286
- * capable agent as a transient failure to route around: it would apologise,
1287
- * pick a different command that does the same thing, and call the gate
1288
- * again. This says the durable part out loud (the refusal covers the rest of
1289
- * the conversation, not just that call) and asks for the one response that
1290
- * actually helps — say what you need and stop, so the user can re-enable it.
1291
- */
1292
- function denialText(name) {
1293
- return (
1294
- `${name} was not executed — the user denied this tool for this conversation. ` +
1295
- `Do NOT retry it and do NOT attempt the same effect by another route ` +
1296
- `(another command, a writeFile instead of an edit, a subagent). ` +
1297
- `Stop calling tools and reply in plain text: say what you were trying to do, ` +
1298
- `what you need, and that the user can re-enable ${name} to let it proceed.`
1299
- );
1300
- }
1301
-
1302
- /** newChat() in the renderer calls this so a fresh conversation never
1303
- * inherits a prior thread's blanket allows — or its refusals. A new chat is
1304
- * a new gate in both directions: leaving denials behind would silently
1305
- * refuse a tool in a thread where the user never said no. */
1306
- function clearSessionApprovals(rootSessionId) {
1307
- sessionAllowlists.delete(rootSessionId);
1308
- sessionDenials.delete(rootSessionId);
1309
- // And the Pro child's memory of the conversation, for the same reason: a
1310
- // new chat (or `/clear`) that left the child resumed would let it answer
1311
- // from turns the user just deleted, which looks like the clear failed.
1312
- proSessions.delete(rootSessionId);
1313
- return { ok: true };
1314
- }
1315
-
1316
- /** The renderer's approval card resolves the pending requestApproval()
1317
- * promise below. An unknown/already-answered id is a no-op — the card
1318
- * can only be clicked once (it disables itself), but a duplicate or
1319
- * late message must never throw. */
1320
- function respondApproval(approvalId, decision) {
1321
- const pending = pendingApprovals.get(approvalId);
1322
- if (!pending) return { ok: false };
1323
- pendingApprovals.delete(approvalId);
1324
- pending.resolve(decision === 'session' || decision === 'once' ? decision : 'deny');
1325
- return { ok: true };
1326
- }
1327
-
1328
- /**
1329
- * Ask the renderer to approve one mutating tool call. Resolves 'once',
1330
- * 'session' or 'deny' (an explicit choice by the user) — or 'cancel' when
1331
- * nobody ever answered: no listener able to reply, or the turn was aborted.
1332
- * 'cancel' is kept apart from 'deny' on purpose. Both refuse the call, but
1333
- * only 'deny' is a decision the user made, so only 'deny' may be remembered
1334
- * as "this conversation said no" (see sessionDenials). Folding the two
1335
- * together — which is what the old fail-safe did, resolving 'deny' for an
1336
- * abort — would let a cancelled turn permanently refuse a tool the user
1337
- * never ruled on. Sent over `rootOnDelta` (see chat()) as an `{ approval }`
1338
- * chunk so it rides the exact same streaming channel as tool-activity
1339
- * chunks — no new IPC surface needed on the push side, only on the reply
1340
- * side (respondApproval). Fails safe: an unanswered request refuses the
1341
- * call instead of hanging the tool round forever.
1342
- */
1343
- function requestApproval(rootSessionId, rootOnDelta, signal, info) {
1344
- return new Promise((resolve) => {
1345
- if (signal && signal.aborted) {
1346
- resolve('cancel');
1347
- return;
1348
- }
1349
- const id = randomUUID();
1350
- let settled = false;
1351
- const onAbort = () => finish('cancel');
1352
- const finish = (decision) => {
1353
- if (settled) return;
1354
- settled = true;
1355
- pendingApprovals.delete(id);
1356
- if (signal) signal.removeEventListener('abort', onAbort);
1357
- resolve(decision);
1358
- };
1359
- if (signal) signal.addEventListener('abort', onAbort, { once: true });
1360
- pendingApprovals.set(id, { resolve: finish });
1361
- if (typeof rootOnDelta !== 'function') {
1362
- finish('cancel');
1363
- return;
1364
- }
1365
- rootOnDelta({
1366
- delta: '',
1367
- approval: {
1368
- id,
1369
- sessionId: rootSessionId,
1370
- tool: info.tool,
1371
- args: info.args,
1372
- diff: info.diff || null,
1373
- },
1374
- });
1375
- });
1376
- }
1377
-
1378
- /** The renderer's rounds-dialog answer resolves the pending
1379
- * requestRoundsAsk() promise below. An unknown/already-answered id is a
1380
- * no-op, same contract as respondApproval. */
1381
- function respondRoundsAsk(askId, decision) {
1382
- const pending = pendingRoundAsks.get(askId);
1383
- if (!pending) return { ok: false };
1384
- pendingRoundAsks.delete(askId);
1385
- pending.resolve(decision === true || decision === 'continue');
1386
- return { ok: true };
1387
- }
1388
-
1389
- /**
1390
- * Ask the renderer whether to fund another block of tool rounds, mirroring
1391
- * requestApproval's shape exactly: pushed over `rootOnDelta` as a `{ rounds }`
1392
- * chunk (the one channel a detached renderer has into a running turn) and
1393
- * resolved externally via `respondRoundsAsk`. Resolves `true` (fund one more
1394
- * block) or `false` (stop here) — never throws. Fails safe to `false`: no
1395
- * listener, an aborted turn, or an unanswered ask must not keep the loop
1396
- * waiting forever (or, worse, spend rounds nobody agreed to).
1397
- */
1398
- function requestRoundsAsk(rootSessionId, rootOnDelta, signal, info) {
1399
- return new Promise((resolve) => {
1400
- if (signal && signal.aborted) {
1401
- resolve(false);
1402
- return;
1403
- }
1404
- const id = randomUUID();
1405
- let settled = false;
1406
- const onAbort = () => finish(false);
1407
- const finish = (decision) => {
1408
- if (settled) return;
1409
- settled = true;
1410
- pendingRoundAsks.delete(id);
1411
- if (signal) signal.removeEventListener('abort', onAbort);
1412
- resolve(decision);
1413
- };
1414
- if (signal) signal.addEventListener('abort', onAbort, { once: true });
1415
- pendingRoundAsks.set(id, { resolve: finish });
1416
- if (typeof rootOnDelta !== 'function') {
1417
- finish(false);
1418
- return;
1419
- }
1420
- rootOnDelta({
1421
- delta: '',
1422
- rounds: {
1423
- id,
1424
- sessionId: rootSessionId,
1425
- spent: info.spent,
1426
- extensions: info.extensions,
1427
- max: info.max,
1428
- size: info.size,
1429
- },
1430
- });
1431
- });
1432
- }
1433
-
1434
- /**
1435
- * The gate itself: read-only tools and already-session-allowed mutating
1436
- * tools run exactly like executeTool always did. A first-time mutating
1437
- * call previews writeFile/editFile (a preview failure — e.g. old_string
1438
- * not found — is returned as the ordinary tool error, no approval prompt
1439
- * needed for a call that couldn't succeed anyway), asks the renderer, and
1440
- * on approval either applies with a fresh hash check (writeFile/editFile)
1441
- * or runs normally (exec — nothing to hash-check).
1442
- *
1443
- * Confirm mode off (Settings → "Confirm before running tools") short-circuits
1444
- * ALL of that: no preview, no approval card, no requestApproval() — the call
1445
- * runs straight through exactly like a session-allowed one, so "don't ask"
1446
- * is one switch rather than a per-tool blanket allow in every conversation.
1447
- */
1448
- /**
1449
- * The single place a tool executor is called from the chat loop, so the
1450
- * turn guard cannot be bypassed by reaching a different branch (there are
1451
- * four `return`s in gatedExecuteTool below; all of them come through here).
1452
- *
1453
- * exec is *checked* before running and writeFile/editFile are *recorded*
1454
- * after, and the asymmetry is the point: a refusal has to happen before the
1455
- * command runs, while "this path is mine" is only true once the write
1456
- * actually happened — recording a denied or preview-failed write would hide
1457
- * a genuinely foreign file behind a claim of ownership.
1458
- *
1459
- * A refusal is returned as an ordinary tool error, so the model reads it and
1460
- * adapts (name the paths, or don't do it) with no new IPC or renderer
1461
- * channel — the same reason it works identically in the GUI and the CLI.
1462
- */
1463
- async function guardedExecute(name, args, toolCtx) {
1464
- // Resolve `~/…` and refuse a foreign-OS path BEFORE anything below reads it
1465
- // (tools.js normalizeArgs; idempotent, so executeTool normalising again is a
1466
- // no-op). The covenant assert and recordWrite both inspect `args.file_path`,
1467
- // and a path they rule on must be the path that actually gets written.
1468
- const norm = normalizeToolArgs(T, name, args, toolCtx || {});
1469
- if (!norm.ok) return { ok: false, error: norm.error };
1470
- args = norm.args;
1471
- const guard = toolCtx && toolCtx.guard;
1472
- if (guard && name === 'exec') {
1473
- const verdict = blocksDestructive(guard, args && args.command);
1474
- if (!verdict.ok) return { ok: false, error: verdict.reason };
1475
- }
1476
- // ÆL/1 pre-action assert — Σ1..Σ4 / Λ1,Λ2,Λ4.
1477
- //
1478
- // Placed AFTER the destructive-command guard above (so that guard keeps
1479
- // its own message) and BEFORE every executor call below, which is the
1480
- // only thing that matters: `gatedExecuteTool` has four `return`s into
1481
- // this function, and all of them land above this line, so no branch of
1482
- // the confirmation gate can reach an executor without passing here.
1483
- //
1484
- // §9 amendment invariant: ¬M(Λ1) ∧ ¬M(Λ2) ∧ ¬M(Λ4)
1485
- // This check is deliberately *unconditional* and reads nothing from
1486
- // `toolCtx` — no confirm-mode setting, no remembered per-session "allow",
1487
- // no /permissions rule, no admin path and no IPC payload can skip it or
1488
- // reverse its verdict. An approval that could waive Λ2 would be the exact
1489
- // capture K3 describes. To change what is permitted, the covenant text
1490
- // itself has to be re-sealed — which no runtime input can do.
1491
- //
1492
- // DO NOT MOVE THIS BELOW A SHORT-CIRCUIT. It sits above every `return` of
1493
- // the confirmation gate on purpose (ON8/D8 rule 2): `gatedExecuteTool`
1494
- // short-circuits on `!confirmModeEnabled()`, on a remembered session
1495
- // "allow", and on a `/permissions` skip — and since ON8 the confirm-mode
1496
- // preference is the SHARED store's, i.e. the same value the terminal face
1497
- // reads, and `--dangerously-skip-permissions` can arrive in that store as
1498
- // well. A refactor that hoists this below any of those three would make
1499
- // the covenant waivable by a setting a user can write, which is the one
1500
- // thing D8 rule 2 forbids outright. The frozen classes
1501
- // (`write`/`shell`/`network`/`offDevice`, always `'ask'`; see
1502
- // lib/avatar/level.js `LEVEL_INDEPENDENT_APPROVALS`) have the same floor
1503
- // and are asserted beside this one by one/test/permissions.test.mjs.
1504
- const cv = covenant.preActionAssert({ tool: name, args: args || {} });
1505
- if (!cv.allowed) {
1506
- // Non-silent (never a quiet no-op) and bound for Λ4 accountability.
1507
- const record = covenant.bindRefusal({ tool: name, args: args || {} }, cv);
1508
- return {
1509
- ok: false,
1510
- error: `refused by the ÆGIS covenant — ${cv.clause} (${cv.label}): ${cv.reason}`,
1511
- covenant: record,
1512
- };
1513
- }
1514
- // Awaited, not merely returned: "this path is mine" is only true once the
1515
- // write actually landed, and `executeTool` is async — inspecting `.ok` on
1516
- // an un-awaited promise would read undefined and record every write,
1517
- // including the ones that failed. Ownership is load-bearing in the other
1518
- // direction too: a path wrongly claimed stops being reported as foreign.
1519
- const result = await T.executeTool(name, args, toolCtx);
1520
- if (guard && (name === 'writeFile' || name === 'editFile') && result && result.ok !== false) {
1521
- recordWrite(guard, args && args.file_path);
1522
- }
1523
- return result;
1524
- }
1525
-
1526
- async function gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal }) {
1527
- const { name } = call;
1528
- // Same normalisation as guardedExecute, and for the same reason one layer
1529
- // up: the diff the user approves is rendered from this path, the hash guard
1530
- // re-reads it, and recordWrite claims it. All three must mean one file.
1531
- const normalized = normalizeToolArgs(T, name, call.args, toolCtx || {});
1532
- if (!normalized.ok) return { ok: false, error: normalized.error };
1533
- const args = normalized.args;
1534
- if (!T.MUTATING_TOOLS.has(name)) return guardedExecute(name, args, toolCtx);
1535
- if (!confirmModeEnabled()) return guardedExecute(name, args, toolCtx);
1536
- if (sessionAllows(rootSessionId, name)) return guardedExecute(name, args, toolCtx);
1537
- // Already refused in this conversation: refuse again WITHOUT raising a
1538
- // second card. Before this, the model's retry after a denial re-prompted
1539
- // the user for the same tool — one "no" produced a card per round for up
1540
- // to maxRounds rounds, each one a billed provider call re-sending the
1541
- // whole conversation. Checked after the confirm-mode short-circuit so
1542
- // turning the gate off still overrides an earlier refusal.
1543
- if (sessionDenies(rootSessionId, name)) return { ok: false, error: denialText(name) };
1544
-
1545
- let preview = null;
1546
- if (name === 'writeFile' || name === 'editFile') {
1547
- preview = T.previewMutation(name, args, toolCtx || {});
1548
- if (!preview.ok) return { ok: false, error: preview.error };
1549
- }
1550
-
1551
- const decision = await requestApproval(rootSessionId, rootOnDelta, signal, {
1552
- tool: name,
1553
- args,
1554
- diff: preview && preview.diff,
1555
- });
1556
-
1557
- // Only a click is remembered. 'cancel' (aborted turn / nobody able to
1558
- // answer) refuses this call but must not write a durable "no" the user
1559
- // never gave.
1560
- if (decision === 'deny') {
1561
- denyForSession(rootSessionId, name);
1562
- return { ok: false, error: denialText(name) };
1563
- }
1564
- if (decision !== 'session' && decision !== 'once') {
1565
- return { ok: false, error: `${name} was not executed — the request was cancelled.` };
1566
- }
1567
- if (decision === 'session') allowForSession(rootSessionId, name);
1568
-
1569
- if (preview) {
1570
- const res = T.applyChecked(name, args, preview, toolCtx || {});
1571
- // Recorded on the same condition as guardedExecute's path: only a write
1572
- // that landed is this session's. (The previous form returned here
1573
- // unconditionally, making every line below it unreachable — the
1574
- // approved-write path recorded nothing at all.)
1575
- if (res && res.ok !== false && toolCtx && toolCtx.guard) {
1576
- recordWrite(toolCtx.guard, args && args.file_path);
1577
- }
1578
- return res;
1579
- }
1580
- return guardedExecute(name, args, toolCtx);
1581
- }
1582
-
1583
- async function listClasses() {
1584
- return CLASSES.map((c) => {
1585
- if (c.class === 'aegis') {
1586
- return { ...c, configured: Boolean(aegis.apiKey) };
1587
- }
1588
- if (c.class === 'byok') {
1589
- // Configured means "this host could actually spend a key for at least
1590
- // one provider" — byok holds one row per provider (byokNamespace), so
1591
- // there is no single baseURL+key pair to report. A row whose key lives
1592
- // in `~/.aegiscode/.env` counts: that is the whole point of reading the
1593
- // file, and calling it unconfigured would send the user to a Settings
1594
- // row they do not need. A stored key still short-circuits, so an install
1595
- // with no env file pays one lookup per stored row and nothing else.
1596
- //
1597
- // The authoritative per-provider answer is `listModels`, which has the
1598
- // server's catalog and so can name a provider the user has never opened
1599
- // Settings for. This one can only see providers with a stored row.
1600
- const rows = settings.list() || [];
1601
- const anyConfigured = rows.some((s) => {
1602
- if (!s || typeof s.provider !== 'string' || !s.provider.startsWith('byok:')) return false;
1603
- if (s.configured) return true;
1604
- return Boolean(providerKeyFromEnv(s.provider.slice(BYOK_NAMESPACE_PREFIX.length)));
1605
- });
1606
- return { ...c, configured: anyConfigured };
1607
- }
1608
- if (c.class === 'local') {
1609
- // Always "configured": this class needs no credential at all, which is
1610
- // the entire reason it is free. Whether a daemon is actually listening
1611
- // is a different question, asked where the answer belongs — in
1612
- // listModels, next to the model list the user is looking at, so the
1613
- // state reads "start the daemon" instead of "go and configure
1614
- // something", which is what an unconfigured row would say.
1615
- return { ...c, configured: true };
1616
- }
1617
- if (c.class === 'pro') {
1618
- // Configured means "there is a Claude Code subscription to spend": a
1619
- // credential file with a token in it. Deliberately NOT gated on the
1620
- // `claude` binary being on PATH as well — that is a separate state with
1621
- // its own remedy, and folding the two together would answer "sign in"
1622
- // to someone who is signed in and merely missing the CLI.
1623
- const status = claudePro.claudeProStatus({ env: process.env });
1624
- const seam = claudePro.seamAvailable();
1625
- return { ...c, configured: status.loggedIn, status, seam };
1626
- }
1627
- // Unreachable while CLASSES lists only aegis + byok + local + pro; kept so
1628
- // a future class added without a status rule reads as unconfigured rather
1629
- // than silently appearing ready (the "no saved key" fallback shape).
1630
- return { ...c, configured: false };
1631
- });
1632
- }
1633
-
1634
- async function listModels(cls) {
1635
- if (cls === 'aegis') {
1636
- // The catalog is behind the account's key: GET /api/v1/models answers
1637
- // `401 {"error":{"message":"No API key"}}` without one (verified against
1638
- // aegiscloud.org). Aegis Cloud is the *default* class, so firing the call
1639
- // anyway painted a raw "listModels failed: … 401" over the default model
1640
- // picker for every user who had just installed the app and not yet
1641
- // pasted a key — the one state where the UI must say what unblocks it and
1642
- // not what went wrong. Report the missing key as a state (`needsKey`) and
1643
- // let the renderer invite the user to connect; nothing else about the
1644
- // class changes, and the model dropdown keeps its "server default (auto)"
1645
- // entry so the class is usable the moment a key lands.
1646
- if (!aegis.apiKey) return { class: cls, models: [], needsKey: true };
1647
- const data = await aegis.listModels();
1648
- // The whole catalog, aliases folded — see the rule above. What the list
1649
- // contains does not touch `needsKey` or the renderer's per-class hint.
1650
- return {
1651
- class: cls,
1652
- // One call, because the folding has to see the payload's own `alias_of`
1653
- // bookkeeping: a pre-collapsed row IS the selection, so a renderer must
1654
- // not filter it back out as a hidden alias, and folding what has already
1655
- // been folded would leave a renamed tier (`nexus-brain-v2`, an alias OF
1656
- // the brain under a spelling this release has never seen) on screen.
1657
- models: offerableCatalog(normalizeCatalog(data && data.models)),
1658
- };
1659
- }
1660
- if (cls === 'byok') {
1661
- // The server's catalog names every provider it accepts a key for, the
1662
- // models each unlocks, and whether an AEGIS account key is even needed
1663
- // to ask (it is not — the catalog answers an anonymous request).
1664
- // Deliberately NOT gated on aegis.apiKey the way the pooled class above
1665
- // is: BYOK's whole point is a caller who brings their own credential, and
1666
- // hiding the catalog would hide the answer to "which key do I go and get"
1667
- // from exactly the person deciding whether to bother. Nothing here
1668
- // enforces billing either: the desktop is one client of a route that is
1669
- // unauthenticated by design, so refusing in this process would stop
1670
- // exactly one host out of many. The relay owns that decision, and reports
1671
- // it via `fee.require_balance` below.
1672
- let providers = [];
1673
- let fee = null;
1674
- try {
1675
- const data = await aegis.byokProviders();
1676
- // The server's catalog, plus the ids it does not name but the vendor
1677
- // serves and the relay will forward (`client/byok-catalog.js`, shared
1678
- // with the CLI so both hosts offer the same rows). Applied HERE, at the
1679
- // single point where the payload enters this engine, so every consumer
1680
- // of `providers` — the model list built just below, the renderer's
1681
- // per-provider Settings rows, and the CLI's own `/byok` listing when it
1682
- // runs on this engine — sees one list instead of three opinions.
1683
- providers = withUserModels(withByokAdditions((data && data.providers) || []));
1684
- // The handling fee AEGIS adds on top of the caller's vendor bill. It is
1685
- // the server's own published rate (services/pricing.price_byok_call) and
1686
- // is passed through untouched — never re-derived here, because a client
1687
- // that hardcodes a fee is a client that can disagree with the ledger.
1688
- // Absent until the server publishes one, and the UI must then say
1689
- // nothing rather than show a guess.
1690
- fee = (data && data.fee) || null;
1691
- } catch {
1692
- providers = [];
1693
- }
1694
- const models = [];
1695
- for (const p of providers) {
1696
- if (!p || !p.id) continue;
1697
- const rowCfg = settings.get(byokNamespace(p.id)) || {};
1698
- // A key from `~/.aegiscode/.env` makes the provider usable, so it must
1699
- // read as configured here — this is the flag `needsProviderKey` is built
1700
- // on, and the one the renderer's per-provider rows mirror. Reporting it
1701
- // unconfigured while `chat()` happily spends the env key is exactly the
1702
- // "no saved key" contradiction this file removes.
1703
- const envRec = providerKeyRecord(p.id);
1704
- const fromEnv = envRec.key || '';
1705
- const rawModels = Array.isArray(p.models) ? p.models : [];
1706
- for (const m of rawModels) {
1707
- const modelId = typeof m === 'string' ? m : m && m.id;
1708
- if (!modelId) continue;
1709
- models.push({
1710
- id: `${p.id}:${modelId}`,
1711
- label: `${p.label || p.id} — ${modelId}`,
1712
- provider: p.id,
1713
- configured: Boolean(rowCfg.configured || fromEnv),
1714
- // Why a row with no usable key is keyless, when the env file refused
1715
- // the value it was given rather than never being given one. Carried
1716
- // on the row because the renderer's per-provider line is the only
1717
- // place the user can see it before they send a turn. Null when there
1718
- // is nothing to explain (a saved key, or no env value at all).
1719
- keyRejected: envRec.rejected || null,
1720
- });
1721
- }
1722
- }
1723
- return {
1724
- class: cls, models, providers,
1725
- needsProviderKey: models.length > 0 && !models.some((m) => m.configured),
1726
- needsAegisKey: !aegis.apiKey,
1727
- fee,
1728
- };
1729
- }
1730
- if (cls === 'local') {
1731
- // No credential to check, so the only question is whether anything is
1732
- // listening. The probe never throws (local.js), so a machine with no
1733
- // daemon reports a STATE and the renderer invites the user to start one —
1734
- // the same shape as the pooled class's `needsKey` above, and for the same
1735
- // reason: an install in its default state must be told what unblocks it,
1736
- // not shown a transport error.
1737
- const cfg = settings.get('local') || {};
1738
- const baseURL = cfg.baseURL || localT.DEFAULT_BASE;
1739
- const status = await localT.probe(baseURL);
1740
- if (!status.running) {
1741
- return { class: cls, models: [], baseURL: status.baseURL, needsDaemon: true };
1742
- }
1743
- // The daemon is up. Its tag list is Ollama's native endpoint, so a
1744
- // non-Ollama server on the same box (llama.cpp, LM Studio, vLLM) answers
1745
- // 404 here — recoverable, and it must not cost the class its usability:
1746
- // the renderer falls back to letting the user type a model name, and the
1747
- // transport itself never needs this call.
1748
- let tags = [];
1749
- let listed = true;
1750
- try {
1751
- tags = await localT.listTags(baseURL);
1752
- } catch {
1753
- listed = false;
1754
- }
1755
- return { class: cls, models: tags, baseURL: status.baseURL, listed };
1756
- }
1757
- if (cls === 'pro') {
1758
- // The model list is the CLI's OWN aliases. The subscription does not
1759
- // expose an id list this process may query, and inventing full model
1760
- // names here would be exactly the "client names a model the transport
1761
- // cannot address" defect — `claude --model` takes these aliases, so these
1762
- // are the rows (claude-pro.js PRO_MODELS).
1763
- const status = claudePro.claudeProStatus({ env: process.env });
1764
- const models = claudePro.PRO_MODELS.map((m) => ({
1765
- id: m.id,
1766
- label: m.label,
1767
- note: m.note,
1768
- configured: status.loggedIn,
1769
- }));
1770
- return {
1771
- class: cls,
1772
- models,
1773
- // Nothing to key: the subscription IS the credential, and there is no
1774
- // AEGIS spend on this class for the relay's balance gate to consider.
1775
- needsProviderKey: false,
1776
- needsAegisKey: false,
1777
- subscription: status.subscription,
1778
- loggedIn: status.loggedIn,
1779
- credentialFile: status.file,
1780
- // A shell `ANTHROPIC_API_KEY` too short to be a credential makes the CLI
1781
- // prefer that name over the subscription, so a signed-in machine ran
1782
- // turns as "API key: he". The child is fixed either way (claude-pro.js
1783
- // childEnvPlan); reported here so the picker can name the var instead of
1784
- // leaving it to be discovered from `claude auth status` by hand.
1785
- shadowed: status.shadowed || null,
1786
- seam: claudePro.seamAvailable(),
1787
- };
1788
- }
1789
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
1790
- // and 'pro', all returned above. Thrown rather than falling through to an
1791
- // empty list, because "no models" is a state the renderer renders as a
1792
- // normal empty picker — an unknown class would look like a
1793
- // configured-but-empty account instead of the bug it is. Same shape as
1794
- // dispatch's tail.
1795
- throw new Error(
1796
- `listModels: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
1797
- );
1798
- }
1799
-
1800
- /**
1801
- * The environment facts the model needs to stop asking which OS it is on.
1802
- * Everything is best-effort: a missing field is simply omitted.
1803
- */
1804
- function envFor(payload) {
1805
- return hostEnv(env || {}, (payload && payload.env) || {}, payload);
1806
- }
1807
-
1808
- /**
1809
- * The directories the Claude Pro child is additionally allowed to work in,
1810
- * for a turn running in `cwd` — the Pro path's half of "the model is not
1811
- * walled into one subdirectory".
1812
- *
1813
- * Two candidates, and only two:
1814
- *
1815
- * · the repository root, from `git-scope.js` — the module the turn guard and
1816
- * the queue already share, so "where does this work happen" is answered in
1817
- * one place rather than re-derived here;
1818
- * · the project data directory (`$AEGISCODE_HOME`, else `~/.aegiscode`),
1819
- * because a turn asked to look at its own session/queue/memory files is
1820
- * otherwise asked to read a path outside its sandbox — the second real
1821
- * report of this wall.
1822
- *
1823
- * Resolved at CALL time, not at load: `git-scope.js` is staged beside this
1824
- * file in both layouts (one/scripts/predist.mjs), and a checkout that has not
1825
- * been staged must still load the engine. A missing module therefore degrades
1826
- * to "no widening", which is the pre-existing behaviour — never to a second,
1827
- * local implementation of git root discovery.
1828
- *
1829
- * Deduplicated against `cwd` itself: telling the child that its own working
1830
- * directory is also an extra directory is noise in the argv, in the record and
1831
- * in the run-log line, and noise is where a real widening hides.
1832
- */
1833
- function proAddDirs(cwd) {
1834
- const out = [];
1835
- // Separator-normalised comparison only — this file deliberately does not
1836
- // grow a `node:path` dependency at module scope for two string checks, and
1837
- // both candidates arrive absolute from modules that already resolved them.
1838
- const norm = (p) => String(p || '').replace(/[\\/]+$/, '');
1839
- const here = norm(cwd);
1840
- const add = (dir) => {
1841
- const abs = norm(dir);
1842
- if (!abs || abs === here || out.includes(abs)) return;
1843
- out.push(abs);
1844
- };
1845
- let scope = gitScope;
1846
- if (scope === undefined) {
1847
- try {
1848
- scope = require('./git-scope.js');
1849
- } catch {
1850
- scope = null;
1851
- }
1852
- }
1853
- try {
1854
- if (scope && typeof scope.gitRoot === 'function') add(scope.gitRoot(cwd));
1855
- } catch {
1856
- /* not a repo, or git is absent: no wider tree to grant */
1857
- }
1858
- try {
1859
- if (credentialsLib && typeof credentialsLib.aegisHome === 'function') add(credentialsLib.aegisHome());
1860
- } catch {
1861
- /* no data directory resolved: nothing to add */
1862
- }
1863
- return out;
1864
- }
1865
-
1866
- /** One transport round for the chosen class. */
1867
- async function dispatch(cls, opts) {
1868
- if (cls === 'aegis') {
1869
- // `undefined` = "leave the model id's own default alone" (a real user
1870
- // turn on the pooled class: the selected Nexus id is what decides, so
1871
- // today's behaviour is unchanged). `false` = an explicit single provider
1872
- // call, for a pass that is a continuation rather than a new
1873
- // investigation. `true` = the autonomous fan-out.
1874
- const brainFlag = opts.singlePass ? false : opts.autonomous ? true : undefined;
1875
- return aegis.chatCompletion({
1876
- prompt: opts.prompt,
1877
- system: opts.system,
1878
- messages: opts.messages,
1879
- model: opts.model,
1880
- mode: opts.mode,
1881
- // Only a cap the caller STATED travels; an effort-derived one does not.
1882
- // The server derives its own budget from `effort` (aegis1 pass_budgets
1883
- // splits its ladder across workers + synthesis), so forwarding the
1884
- // derived number states one decision twice — and the copies had already
1885
- // drifted: 974adc5 doubled aegis1's ladder while this side stood still,
1886
- // leaving the client capping below the budget it displayed. The cap was
1887
- // never the one the renderer showed either (the Max tokens dropdown
1888
- // that used to claim a figure for the pooled class is gone — see
1889
- // desktop/renderer/budget.js). Omitting the field is
1890
- // what tells aegis1 "no cap stated — let effort decide", the same
1891
- // contract the upstream engine sends.
1892
- //
1893
- // A cap the caller DID state is a different thing, and dropping it was
1894
- // a bug: aegis1 reads a body max_tokens as a ceiling over its ladder,
1895
- // so omitting it does not bound the call — it grants the full top rung
1896
- // instead. A deliberate 4096 would have run at 32768, which is the same
1897
- // "only ever raise the caller's ceiling" failure the old
1898
- // Math.max(Number(maxTokens) || 0, EFFORT_TOKEN_BUDGET[eff]) had.
1899
- maxTokens: opts.statedMaxTokens,
1900
- stream: opts.stream !== false,
1901
- // The pooled (Nexus) brain is streamed, and an OpenAI-compatible SSE
1902
- // stream reports no token usage unless asked. Without this the Aegis
1903
- // Cloud class — the desktop's default — was the one class that answered
1904
- // with text but never a token count, so a pooled turn's spend was
1905
- // invisible here while the same model through the MCP path reported it.
1906
- includeUsage: true,
1907
- onStream: opts.onDelta,
1908
- // Extended-reasoning trace (the fan-out's worker findings). Its own
1909
- // channel so it never counts as answer text — see vendor/aegis.js.
1910
- onReasoning: opts.onReasoning,
1911
- // A brain fan-out is silent between passes; give it room (see
1912
- // AUTONOMOUS_IDLE_TIMEOUT_MS). Undefined elsewhere -> 60s default.
1913
- idleTimeoutMs: opts.idleTimeoutMs,
1914
- signal: opts.signal,
1915
- // aegis_recall — the read half of aegis_memory, and the only half a
1916
- // client on this engine should send.
1917
- //
1918
- // aegis_memory is both halves: it injects the account's synced memory
1919
- // into context AND persists this turn back into it, charging sync
1920
- // quota for the write. That pairing is right for aegis-online, whose
1921
- // chat has nowhere else to live. It is wrong here, because this engine
1922
- // is shared by the GUI and the CLI (cli/src/deps.js loads this file):
1923
- // either would be billed for every "hey" and would fill the user's
1924
- // memory with greetings. Verified against aegis1 app.py: every
1925
- // write-back site (the note/upsert calls) is gated on aegis_memory,
1926
- // and aegis_memory implies aegis_recall there — so dropping the write
1927
- // half leaves /online unchanged and costs nothing on the read side.
1928
- //
1929
- // Writing is still available, explicitly: the aegis_memory_save tool
1930
- // (mcp/tools.js; the CLI exposes it as /memory). Recall on every turn,
1931
- // store only what the user asks for — which is what the upstream engine's
1932
- // own cross-session memory does, and what this comment claimed to
1933
- // match while sending both halves.
1934
- //
1935
- // Recall was previously unreachable for a client that would not pay
1936
- // for it: services/tiered_recall.py only ran behind a flag that also
1937
- // bought a write, so the tiered path existed with no caller able to
1938
- // afford it. The split is what makes it reachable. The DEEP tier of the
1939
- // same read is a third flag with its own price — see `opts.recallDeep`
1940
- // below, which is off unless the session opted in.
1941
- extra: {
1942
- aegis_recall: true,
1943
- // The DEEP tier of that read — brain corrections plus the semantic
1944
- // answer cache — is not the same price, so it does not ride along.
1945
- // aegis1 app.py:8367 reads `aegis_recall_deep` (or the
1946
- // X-AEGIS-Recall-Deep header) and services/brain_memory.py
1947
- // find_cached_answer embeds the query: one provider embedding per
1948
- // turn, metered. The server deliberately implies it from
1949
- // `aegis_memory` and NOT from `aegis_recall`, so that a terminal
1950
- // client can buy the cheap read without the embedding.
1951
- //
1952
- // This client is that terminal client (the CLI loads this file via
1953
- // cli/src/deps.js), so it must not opt itself in: the flag is sent
1954
- // only when the SESSION asked for it — CLI `/memory-deep on`, a
1955
- // desktop payload with `recallDeep: true` — and it defaults false
1956
- // everywhere. It also travels only on the user's own turn
1957
- // (`opts.recallDeep` is cleared for every other dispatch below): a
1958
- // tool round, the doubled-budget retry and the write-up re-dispatch
1959
- // all re-send a context whose embedding the first round already
1960
- // bought, which would turn one embedding per turn into one per round.
1961
- ...(opts.recallDeep ? { aegis_recall_deep: true } : {}),
1962
- session: opts.sessionId,
1963
- // The fan-out is opt-in per dispatch. `brain` is sent EXPLICITLY
1964
- // whenever this dispatch is not the autonomous one, because the
1965
- // model id this class sends (``nexus-brain``) enables the pooled
1966
- // brain on its own: without the flag a continuation pass — the
1967
- // doubled-budget retry, or the "write up what you already found"
1968
- // re-dispatch — silently re-ran the whole workers+1 fan-out for a
1969
- // pass whose documented cost is a single request. aegis1
1970
- // services/pool_brain.py parse_brain_request honours the opt-out.
1971
- ...(brainFlag === undefined ? {} : { brain: brainFlag }),
1972
- // An opted-out pass is also told WHICH band to run on. A single call
1973
- // on a brain model id infers its band from the id and lands on
1974
- // "fast" (the cheapest id in the pool); "brain" is the band the
1975
- // workers themselves run on (cheapest model that can think). Same
1976
- // model as the fan-out, one sample instead of four — otherwise
1977
- // dropping the fan-out would have quietly changed the model too.
1978
- ...(brainFlag === false ? { mode: 'brain' } : {}),
1979
- // `effort` is the budget rung, and it is sent whenever the caller has
1980
- // one — not only alongside a fan-out. The fan-out is triggered by the
1981
- // model id (this class sends ``nexus-brain``), so a caller that never
1982
- // ticked "work autonomously" still ran a pooled call and had no way to
1983
- // say how big it should be: the server fell through to its own default
1984
- // rung. That is how a one-word prompt came to reserve the top of the
1985
- // ladder. A single-pass pass carries it too — inert on that path, but
1986
- // it keeps the request honest about what it asked for.
1987
- ...(opts.effort ? { effort: opts.effort } : {}),
1988
- // Only meaningful with a running fan-out — aegis1 services/pool_brain.py
1989
- // parse_brain_request reads `workers` straight off the body and clamps
1990
- // it itself (MAX_WORKERS), so no client-side validation here.
1991
- ...(brainFlag === true && opts.workers ? { workers: opts.workers } : {}),
1992
- // The pool forwards `tools` to the provider and returns tool_calls
1993
- // (aegis1 app.py:7765 → provider, pool_brain synthesis keeps them).
1994
- ...(opts.tools.length ? { tools: opts.tools } : {}),
1995
- ...(opts.toolChoice ? { tool_choice: opts.toolChoice } : {}),
1996
- },
1997
- // aegis1's agent-key gate (services/agent_gate.py) 403s a pooled turn
1998
- // whose `tools` names a code-capable verb (writeFile/editFile/exec —
1999
- // this engine's builtin set — normalise to the server's CODE_TOOLS
2000
- // entries) unless X-AEGIS-Agent-Key is attached. `AEGIS_API_KEY` says
2001
- // who pays; this says who may change code, and is deliberately a
2002
- // separate credential (see agent_gate.py's module docstring). Read
2003
- // from `~/.aegiscode/.env` via the same loadEnvFile() both hosts
2004
- // already run at startup — no new key store. Absent by default: an
2005
- // account with no agent key simply gets the same 403 as before,
2006
- // scoped to turns that actually carry tools.
2007
- agentKey: opts.tools.length ? (process.env.AEGIS_AGENT_KEY || '').trim() || undefined : undefined,
2008
- });
2009
- }
2010
-
2011
- if (cls === 'byok') {
2012
- // opts.model is still the compound "provider:model" id here — the
2013
- // relay wants them split (a `provider` field plus a bare `model`).
2014
- // opts.apiKey is the PROVIDER key resolved by chat() above (from the
2015
- // byokNamespace(provider) settings row), never the account's own AEGIS
2016
- // key — that one is baked into the `aegis` client already and attached
2017
- // automatically by byokChatCompletion() as X-AEGIS-Key so the account
2018
- // gets billed the handling fee; see client/aegis.js.
2019
- const { provider, model: bareModel } = splitByokModel(opts.model);
2020
- // Translate the rung for THIS vendor once, and carry the verdict rather
2021
- // than a bare level: the relay validates strictly upstream and the field
2022
- // name is not portable (DeepSeek's `/anthropic` transport takes `effort`,
2023
- // OpenAI-shaped vendors take `reasoning_effort`). Undefined for a family
2024
- // with no dialect, which the transport then omits entirely.
2025
- const effort = nativeEffort(provider, bareModel, opts.effort);
2026
- try {
2027
- return await aegis.byokChatCompletion({
2028
- provider,
2029
- model: bareModel,
2030
- providerKey: opts.apiKey,
2031
- // Only meaningful for provider "custom" (aegis1 reads it ONLY on
2032
- // that id) — forwarded unconditionally anyway, same as the other
2033
- // fields above, rather than special-cased per provider here.
2034
- // `cfg` is this provider's settings row (byokNamespace(provider)),
2035
- // the same row /byok-key and /model-add write.
2036
- baseURL: opts.cfg && opts.cfg.baseURL,
2037
- prompt: opts.prompt,
2038
- system: opts.system,
2039
- messages: opts.messages,
2040
- maxTokens: opts.maxTokens,
2041
- // aegis1's byok_chat_completions has read and forwarded `tools`/
2042
- // `tool_choice` since 926069b (2026-09-10) — this call simply never
2043
- // sent them, so every BYOK turn (DeepSeek, Anthropic, OpenAI alike)
2044
- // ran with no write/exec/editFile schema at all. A model told in its
2045
- // system prompt that it "writes and edits files" but never given the
2046
- // JSON shape to do so improvises a DeepSeek-native DSML call from
2047
- // prose alone when it's confident, and falls back to prose ADVICE
2048
- // (a shell script to run by hand) when it isn't — which is exactly
2049
- // the bug this line closes.
2050
- tools: opts.tools,
2051
- toolChoice: opts.toolChoice,
2052
- // Native effort knob, field and level both from the dialect table.
2053
- // `bareModel` is already provider-less, so it matches the dialect
2054
- // regexes without further stripping. Both wire channels are live, and
2055
- // which one is used is the dialect's decision, not this call site's:
2056
- // DeepSeek's `/anthropic` transport takes `effort` (aegis1 gates it on
2057
- // provider_id == "deepseek" and the adapter nests it as
2058
- // `output_config.effort`), while the OpenAI-shaped vendors take
2059
- // `reasoning_effort`. Routing on the field name is what keeps a
2060
- // dialect from being silently dropped here — the previous form
2061
- // forwarded only `reasoning_effort`, so turning DeepSeek's dialect
2062
- // over to `effort` would have died at this line.
2063
- effort: effort && effort.field === 'effort' ? effort.level : undefined,
2064
- reasoningEffort: effort && effort.field === 'reasoning_effort' ? effort.level : undefined,
2065
- stream: true,
2066
- onStream: opts.onDelta,
2067
- signal: opts.signal,
2068
- });
2069
- } catch (e) {
2070
- // The relay's own balance gate (aegis1 `AEGIS_BYOK_REQUIRE_BALANCE`,
2071
- // app.py `byok_chat_completions`) answers 402 with a body aimed at an
2072
- // API consumer — "Insufficient balance. Top up to continue using
2073
- // BYOK." Shown raw in a chat transcript that reads as a crash rather
2074
- // than a bill, so the one thing the user has to DO is said here, in the
2075
- // hosts' own voice. The status is preserved so every existing caller
2076
- // (the CLI's error painter, the desktop turn guard) still sees a 402.
2077
- //
2078
- // The provider key is untouched by this: it is the caller's own and it
2079
- // is still valid. What ran out is the AEGIS balance the handling fee
2080
- // is billed against, which is the whole reason this lane has a fee.
2081
- if (e && e.status === 402) {
2082
- const err = new Error(
2083
- 'byok: this account has no AEGIS balance left, and the BYOK handling fee is ' +
2084
- 'billed there — your provider key is still valid, this is not a key problem. ' +
2085
- 'Top up the account, then try again (or /class aegis to use the pooled lane).'
2086
- );
2087
- err.status = 402;
2088
- throw err;
2089
- }
2090
- throw e;
2091
- }
2092
- }
2093
-
2094
- if (cls === 'local') {
2095
- // The one class whose turn leaves this machine for hardware the user
2096
- // owns. `baseURL` comes from the 'local' settings row and is re-checked
2097
- // by the transport on every call (local.js `remoteRefusal`), so a row
2098
- // hand-edited to a public address after it was saved still cannot be
2099
- // dialed — the engine is not the only gate, it is the first one.
2100
- const baseURL = (opts.cfg && opts.cfg.baseURL) || localT.DEFAULT_BASE;
2101
- const call = (useTools) =>
2102
- localT.chat({
2103
- baseURL,
2104
- model: opts.model,
2105
- prompt: opts.prompt,
2106
- system: opts.system,
2107
- messages: opts.messages,
2108
- maxTokens: opts.maxTokens,
2109
- signal: opts.signal,
2110
- onDelta: opts.onDelta,
2111
- ...(useTools && opts.tools.length ? { tools: opts.tools, toolChoice: opts.toolChoice } : {}),
2112
- });
2113
- try {
2114
- return await call(true);
2115
- } catch (e) {
2116
- // An older daemon 400s on `tools` it does not understand. Sending none
2117
- // gets the turn answered — without tool access, which is worse than the
2118
- // full loop and far better than a 400 the user cannot act on. Retried
2119
- // once, and only for that one status: a 400 about the model name or the
2120
- // message shape is not fixed by dropping schemas, and retrying it would
2121
- // send the same broken turn twice.
2122
- if (opts.tools.length && e && e.status === 400) return call(false);
2123
- throw e;
2124
- }
2125
- }
2126
-
2127
- if (cls === 'pro') {
2128
- // The user's own Claude subscription. This transport is unlike the other
2129
- // three in a way that decides its whole shape: the `claude` child runs
2130
- // its OWN agent loop, with its own tools, so there is no `tools` argument
2131
- // to send and none is invented — passing this engine's schemas would ask
2132
- // a process that already has a tool loop to re-run our tools inside it.
2133
- // `opts.messages`/`opts.tools` are deliberately unused here for that
2134
- // reason, and the dispatch returns the child's own final answer.
2135
- //
2136
- // ── … and the consequence of that, which used to be a bug ─────────────
2137
- //
2138
- // Because the transcript is NOT replayed into the child, the child's own
2139
- // session store was the only thing that could carry context between
2140
- // turns — and nothing ever told it to resume one. Every turn was a
2141
- // brand-new conversation: "Claude has no memory of this conversation"
2142
- // was literally true, and no amount of `messages` upstream could fix it,
2143
- // because they were dropped on purpose one paragraph above.
2144
- //
2145
- // So the child's reported session id is remembered per CONVERSATION and
2146
- // handed back as `--resume`. Keyed by the conversation (rootSessionId),
2147
- // never by `sessionId`: the CLI mints a fresh uuid per turn for
2148
- // cancellation, so keying by it would resume nothing, every turn.
2149
- //
2150
- // We deliberately do NOT pass `sessionId` (`--session-id`) to name the
2151
- // conversation upfront: the CLI's own `/new` mints `aegis-xxxxxxxx`,
2152
- // which is not a UUID the child accepts, and the child's self-minted id
2153
- // is authoritative anyway. It is read back off the `result` line instead.
2154
- const convKey = opts.sessionKey || opts.rootSessionId || opts.sessionId;
2155
- const remembered = convKey ? proSessions.get(convKey) : null;
2156
- // ── the sandbox the child is actually given ───────────────────────────
2157
- //
2158
- // A headless `claude` child resolves every relative path and every tool's
2159
- // root against the directory it was spawned in, so a turn started in a
2160
- // SUBDIRECTORY of the repo cannot read or run anything above it. Reported
2161
- // from this product for real: a session launched in `cli/` that needed
2162
- // `test/` came back with "I can't run outside the sandboxed directory
2163
- // `cli/`" — the model, not a bug in the tools, describing this boundary.
2164
- //
2165
- // The repo root is the right width: it is the tree the user opened, it is
2166
- // one directory (never a glob, never the home dir), and it is derived
2167
- // rather than guessed — `git-scope.js` is the module the turn guard and
2168
- // the queue already ask for "where is this work happening". Best-effort:
2169
- // outside a repo there is no wider directory to grant and the child keeps
2170
- // exactly the posture it had.
2171
- // The turn's own working directory rides on `opts.cwd` (threaded in by
2172
- // `chat()` as `turnCwd`), never on the enclosing scope's local — that
2173
- // reference is the exact `ReferenceError: turnCwd is not defined` this
2174
- // file already carries a regression case for.
2175
- const addDir = proAddDirs(opts.cwd);
2176
- //
2177
- // The permission half of the argv is NOT built here. It comes from
2178
- // resolvePosture() inside runClaudePro, through the one argv builder
2179
- // (one/src/child.js), so this host and AEGISONE's faces cannot disagree
2180
- // about what the child was allowed to do.
2181
- const proRes = await claudePro.runClaudePro({
2182
- // The re-ask round's instruction, when this round has none of its own.
2183
- // See proTurnPrompt(): without it every recovery round spawned the
2184
- // child with an empty prompt and the turn could never be recovered.
2185
- prompt: proTurnPrompt(opts),
2186
- model: opts.model && opts.model !== 'default' ? opts.model : undefined,
2187
- system: opts.system,
2188
- cwd: opts.cwd,
2189
- // The widened sandbox, threaded through to the ONE argv builder. A
2190
- // directory the engine could not derive (or that adds nothing, e.g. the
2191
- // turn already runs at the repo root) is simply absent from this list,
2192
- // and absent means "exactly the posture the child had before".
2193
- addDir,
2194
- // Carry the conversation, if we have one to carry.
2195
- resumeSessionId: remembered || undefined,
2196
- // The stored posture this host already reads for its own gate, handed
2197
- // to the resolver rather than re-read there — one answer per turn.
2198
- gate: typeof getConfirmMode === 'function' ? !getConfirmMode() : undefined,
2199
- signal: opts.signal,
2200
- onDelta: opts.onDelta,
2201
- onSpawn: (child, record) => {
2202
- // Rule 4's "recorded, never inferred": the child's real flags are
2203
- // reported on the same channel tool activity uses, so a Pro turn's
2204
- // transcript shows what it was allowed to do.
2205
- if (opts.onDelta && record) {
2206
- opts.onDelta({ delta: '', note: claudePro.childLine(record) });
2207
- }
2208
- void child;
2209
- },
2210
- });
2211
- // Remember the id the child reported, so the NEXT turn in this thread
2212
- // resumes this conversation. Recorded only on a turn that actually
2213
- // produced one: a failed turn must not overwrite a good id with
2214
- // `undefined` and silently turn the next turn into a new conversation.
2215
- if (convKey && proRes && proRes.sessionId && !proRes.error) {
2216
- proSessions.set(convKey, proRes.sessionId);
2217
- }
2218
- return proRes;
2219
- }
2220
-
2221
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
2222
- // and 'pro', all returned above. Thrown rather than falling through to a
2223
- // default transport, because a class that silently borrows another's wire
2224
- // format is this file's recurring failure mode.
2225
- throw new Error(
2226
- `dispatch: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
2227
- );
2228
- }
2229
-
2230
- async function chat(payload, onDelta) {
2231
- const cls = payload && payload.class;
2232
- const model = payload && payload.model;
2233
- // byok's model id is "provider:model" (see splitByokModel) — strip the
2234
- // provider prefix before pattern-matching, or a DeepSeek reasoning model
2235
- // selected under byok ("byok" model "deepseek:deepseek-v4-flash") never
2236
- // matches DEEPSEEK_REASONING_MODEL_RE's anchored pattern and silently
2237
- // gets no stated budget, which is exactly the "hidden CoT ate the whole
2238
- // default and returned nothing" failure this budget exists to prevent.
2239
- const reasoningModelId = cls === 'byok' ? splitByokModel(model).model : model;
2240
- const maxTokens = reasoningBudget(reasoningModelId, payload && payload.maxTokens, payload && payload.effort);
2241
- // The caller's OWN number, kept apart from `maxTokens` above. That one
2242
- // collapses two different facts into a single value — "the caller stated
2243
- // 4096" and "effort implies 32768" — and the pooled path must treat them
2244
- // differently. A stated cap is a liability ceiling the server honours
2245
- // downward (aegis1 pass_budgets: total = min(ladder, max_tokens x passes));
2246
- // an effort-derived one is the server's own arithmetic stated twice, and
2247
- // sending it is how the two copies came to disagree. So the pooled call
2248
- // forwards only what the caller actually asked for.
2249
- // ...and it is read through statedCapOf(), so a nested chat() that states
2250
- // the key overrides its own derived `maxTokens` instead of being mistaken
2251
- // for a caller who asked for that number (see statedCapOf).
2252
- const statedMaxTokens = statedCapOf(payload);
2253
- // "Work autonomously" — routes this call through aegis1's pool_brain
2254
- // worker fan-out (services/pool_brain.py: N reasoning workers + a
2255
- // synthesis pass) instead of a single provider call. UI-gated to the
2256
- // 'aegis' class only (see AUTONOMOUS_CLASS in app.js).
2257
- const autonomous = cls === 'aegis' && Boolean(payload && payload.autonomous);
2258
- // Opt-in only: the round-horizon dialog (requestRoundsAsk below) needs a
2259
- // live renderer on the other end of `rootOnDelta` able to answer it. The
2260
- // interactive CLI session sets this; the queue worker and `-p` one-shot
2261
- // runs never do (nobody is there to click), so they keep the old
2262
- // stop-and-record-session behaviour (sessionRounds below) untouched.
2263
- const roundsAsk = Boolean(payload && payload.roundsAsk);
2264
- const sessionId = (payload && payload.sessionId) || randomUUID();
2265
- // Recursion depth for the task tool: 0 for a real user turn, N+1 for a
2266
- // subagent spawned by depth N. Never set by an IPC caller — only by
2267
- // runSubagent's own recursive chat() call below.
2268
- const depth = Number.isInteger(payload && payload.depth) ? payload.depth : 0;
2269
- // The approval gate's identity for this whole conversation, regardless of
2270
- // depth: a real user turn defines it (defaults to its own sessionId); a
2271
- // subagent's nested chat() call always receives it explicitly from
2272
- // runSubagent below, so "allow for this session" means the same thing
2273
- // whether the call came from the top-level turn or three subagents deep.
2274
- const rootSessionId = (payload && payload.rootSessionId) || sessionId;
2275
- // Likewise, approval requests must always reach the ORIGINAL caller's
2276
- // stream — a subagent's own chat() call is invoked with a no-op onDelta
2277
- // (its tool activity/text is not streamed to the renderer), so without
2278
- // this a nested approval request would call that no-op and hang forever
2279
- // waiting for a response nobody can ever send.
2280
- const rootOnDelta = (payload && payload.rootOnDelta) || onDelta;
2281
-
2282
- // A pooled brain call streams each worker's finding as extended reasoning
2283
- // before the synthesis pass writes the visible answer. Forward it on its
2284
- // own channel so the renderer can show the fan-out working instead of an
2285
- // apparently idle bubble for the whole worker phase. Uses `onDelta` (not
2286
- // rootOnDelta) on purpose: a subagent's reasoning should be suppressed
2287
- // exactly as its text already is.
2288
- const onReasoning =
2289
- typeof onDelta === 'function' ? (text) => text && onDelta({ reasoning: text }) : undefined;
2290
-
2291
- const controller = new AbortController();
2292
- controllers.set(sessionId, controller);
2293
- const signal = controller.signal;
2294
-
2295
- // A caller can opt out of the agent loop entirely (`tools: false`) and get
2296
- // the old single-shot turn back. byok used to be forced into that same
2297
- // single-shot shape unconditionally: aegis1's byok relay had no
2298
- // tools/tool_choice parameter at all, so sending schemas would build a
2299
- // prompt promising tool access the transport silently dropped — the model
2300
- // would reason about exec/readFile and never see a result. That stopped
2301
- // being true at aegis1 926069b (2026-09-10, byok_chat_completions reads
2302
- // and forwards both), but this carve-out was never revisited, so every
2303
- // BYOK turn since kept running with no tool schema at all regardless —
2304
- // the model told in its own system prompt that it writes and edits files,
2305
- // and never given the JSON shape to do so. Reported live: asked to save a
2306
- // file to the Desktop, DeepSeek had no write tool to call and answered
2307
- // with a PowerShell script for the user to run by hand instead.
2308
- const toolsEnabled = !(payload && payload.tools === false);
2309
- const toolSchemas = toolsEnabled ? T.toolsFor({ includeSubagent: depth < MAX_SUBAGENT_DEPTH }) : [];
2310
- const toolChoice = (payload && payload.toolChoice) || null;
2311
-
2312
- const system = (payload && payload.system) || buildSystemPrompt(envFor(payload));
2313
- const history = Array.isArray(payload && payload.messages) ? payload.messages.filter(Boolean).slice() : [];
2314
- // Index into `history` of everything THIS turn added as opposed to what the
2315
- // caller brought with it. Reset after the resume rehydration below, so a
2316
- // restored transcript is never re-recorded as if this turn had produced it
2317
- // (which would double it on every interruption in a chain).
2318
- let historyStart = history.length;
2319
- let prompt = (payload && payload.prompt) || '';
2320
-
2321
- // Lazily start ONE shell session for this turn; the exec tool shares it so
2322
- // cd/env/state persist across calls. Only spawned if exec actually runs,
2323
- // and always disposed when the turn ends.
2324
- let shell = null;
2325
- const getShell = () => shell || (shell = new ShellSession({ cwd: envFor(payload).cwd }));
2326
- // The turn's working directory. It rides on every tool frame because a
2327
- // tool row's args are the command or the path — never the directory the
2328
- // command runs in — which left "where is it working in" unanswerable from
2329
- // the transcript. It also has to ride on `toolCtx`, which is what
2330
- // normalizeArgs (tools.js) actually resolves a RELATIVE readFile/writeFile/
2331
- // editFile/listDir/glob/grep path against — omitting `cwd` here meant that
2332
- // resolution fell back to the HOST PROCESS's own cwd (the Electron install
2333
- // dir off Linux, per baseDir()'s comment in tools.js, which fixed this for
2334
- // the no-path default but never for a path the model actually supplied).
2335
- // `desktopdir` rides the same way so resolvePath can correct a model's
2336
- // literal "Desktop" guess to the real one (platform.js's own alias fix).
2337
- const turnEnv = envFor(payload);
2338
- const turnCwd = turnEnv.cwd;
2339
- const toolCtx = { getShell, signal, cwd: turnCwd, desktopdir: turnEnv.desktopdir };
2340
-
2341
- try {
2342
- // byok's settings row lives under the provider named IN THE MODEL id
2343
- // ("anthropic:claude-sonnet-5" -> byokNamespace('anthropic')), never
2344
- // under the literal class name — one flat 'byok' row could not hold
2345
- // more than one provider's key at a time.
2346
- const byokParts = cls === 'byok' ? splitByokModel(model) : null;
2347
- // aegis carries its own credential on the `aegis` client; byok is the
2348
- // only class whose key comes out of the settings store, and it comes from
2349
- // the provider named in the model id.
2350
- const cfg =
2351
- cls === 'byok' ? settings.get(byokNamespace(byokParts.provider)) || {}
2352
- : cls === 'local' ? settings.get('local') || {}
2353
- : {};
2354
- // Where a byok key comes from, in order: the encrypted store (a key saved
2355
- // through the app), then the shared `~/.aegiscode/.env` (client/env-file.js,
2356
- // read into process.env at start-up). The store wins when it holds one, so
2357
- // removing a key there still means removed — the file is the convenience,
2358
- // not a second authority.
2359
- const storedKey = cls === 'byok' ? settings.rawKey(byokNamespace(byokParts.provider)) : null;
2360
- const apiKey = cls !== 'byok'
2361
- ? null
2362
- : (storedKey || providerKeyFromEnv(byokParts.provider));
2363
-
2364
- if (cls === 'byok' && (!byokParts.provider || !byokParts.model)) {
2365
- const err = new Error(
2366
- "byok: model must be \"<provider>:<model>\" (pick one from /models) — got " +
2367
- JSON.stringify(model || '')
2368
- );
2369
- err.status = 400;
2370
- throw err;
2371
- }
2372
- if (cls === 'byok' && !apiKey) {
2373
- // Anthropic is the one provider with a SECOND, non-API route, and it is
2374
- // the one a user with a Claude subscription actually owns. Pinning
2375
- // `anthropic:claude-sonnet-5` is a promise that this machine has a
2376
- // console API key for api.anthropic.com; a Pro/Max subscription is NOT
2377
- // one and is deliberately not usable as one (claude-pro.js's own
2378
- // header). So when the machine holds a subscription and no usable
2379
- // anthropic key, the honest instruction is the Pro class — it spends
2380
- // the subscription they already pay for instead of a key they do not
2381
- // have. Checked through claudeProStatus() rather than by looking for a
2382
- // token here, so this message and the picker cannot disagree about
2383
- // whether a subscription is present.
2384
- const pro = byokParts.provider === 'anthropic' ? claudePro.claudeProStatus({ env: process.env }) : null;
2385
- // A key the env file REFUSED outranks both of the messages below. The
2386
- // generic "no key yet" tells a user to go paste one, which is the wrong
2387
- // instruction when the file already holds a value that cannot be a
2388
- // credential: they will paste the same broken thing again, or conclude
2389
- // their account is broken. This is the exact state that produced an
2390
- // upstream `{"type":"authentication_error","message":"Invalid bearer
2391
- // token"}` and read to the user as "Anthropic auth failed".
2392
- const refused = providerKeyRecord(byokParts.provider).rejected;
2393
- const err = new Error(
2394
- refused
2395
- ? `${refused}. That is why this turn has no ${byokParts.provider} key: an env value ` +
2396
- `that short is a paste that lost its payload, not a credential. Fix ${refused.split(' ')[0]} ` +
2397
- `in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: ` +
2398
- `/byok-key ${byokParts.provider} <key> to set one here.`
2399
- : pro && pro.loggedIn
2400
- ? `No Anthropic API key on this machine — an "anthropic:…" id is served by your own ` +
2401
- `console key, which a Claude subscription is not. Use the subscription instead: ` +
2402
- `/class pro (it spends your Claude Code ${pro.subscription || 'Pro'} plan through the ` +
2403
- `claude CLI) — or add a real console key: /byok-key anthropic <key>.`
2404
- : `No key for "${byokParts.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, ` +
2405
- `no setup) — or add this provider's own key: /byok-key ${byokParts.provider} <key>.`
2406
- );
2407
- err.status = 400;
2408
- throw err;
2409
- }
2410
- // …and the AEGIS account key is what makes the turn BILLABLE at all. The
2411
- // relay authenticates on the provider key and resolves the payer
2412
- // separately, from X-AEGIS-Key (app.py `_byok_identify_user`): with no
2413
- // account key the server can attribute the handling fee to no one, so it
2414
- // is logged against user 0 as uncollected — an anonymous free ride the
2415
- // fee exists to close. Require the account key here so EVERY BYOK turn is
2416
- // attributed and every caller pays the handling fee: a funded balance is
2417
- // debited immediately, an unfunded one records the fee as owed
2418
- // (token_bank.charge_byok clamps to zero and never refuses), and nobody
2419
- // is served free. Balance is the server's own concern, not this gate's —
2420
- // with a balance or without one, the account still pays. `listModels`
2421
- // still answers anonymously (the catalog is how a user finds out which
2422
- // key to get), so this refuses only the send, and only until a key lands.
2423
- if (cls === 'byok' && !aegis.apiKey) {
2424
- const err = new Error(
2425
- 'No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — ' +
2426
- 'or add your AEGIS key with /login, then try again.'
2427
- );
2428
- err.status = 401;
2429
- throw err;
2430
- }
2431
-
2432
- // The direct-dial gate, restored for the one class that legitimately
2433
- // dials. It policed a lane that could reach ANY user-supplied URL, which
2434
- // billed nobody — no pooled margin, no BYOK handling fee, no account key
2435
- // attached — so a remote URL there was an unpaid turn to refuse rather
2436
- // than meter. That open-ended lane is gone for good. `local` is the case
2437
- // its own reasoning carved out: a model on a machine the user owns, where
2438
- // there is no vendor to pay in the first place, so there is nothing to
2439
- // bill and nobody being cheated. Checked here before any byte goes out,
2440
- // and again inside the transport, because a settings row can be edited on
2441
- // disk after it was written. Anything not local is refused, not metered —
2442
- // remote models belong on `aegis` or `byok`, both of which bill.
2443
- if (cls === 'local') {
2444
- const refusal = localT.remoteRefusal(cfg.baseURL || localT.DEFAULT_BASE);
2445
- if (refusal) throw refusal;
2446
- }
2447
- const base = {
2448
- cls, model, mode: payload && payload.mode, maxTokens, statedMaxTokens, autonomous, sessionId, signal, onDelta, cfg, apiKey, toolChoice,
2449
- // The turn's working directory, computed above as `turnCwd` — `dispatch`
2450
- // is its own function, not a closure over `chat`'s locals, so the 'pro'
2451
- // branch (the only one that spawns a child in a directory) needs it
2452
- // threaded through here rather than reaching for the enclosing scope's
2453
- // variable, which does not exist from inside `dispatch`.
2454
- cwd: turnCwd,
2455
- // The CONVERSATION's identity, distinct from `sessionId` (which both
2456
- // hosts mint fresh per TURN — the CLI in ask(), for cancellation).
2457
- // Continuity that must outlive one turn is keyed by these, never by
2458
- // `sessionId`: the Pro child's remembered session is one per open
2459
- // thread, so keying it by a per-turn id would start a new child
2460
- // conversation every single turn and look exactly like no memory.
2461
- rootSessionId,
2462
- sessionKey: (payload && payload.sessionKey) || undefined,
2463
- effort: payload && payload.effort,
2464
- workers: payload && payload.workers,
2465
- // Deep recall (`aegis_recall_deep`) is an explicit per-session opt-in
2466
- // and never a default: it costs one provider embedding per turn
2467
- // server-side (aegis1 services/brain_memory.py find_cached_answer), so
2468
- // a client that pays per turn must not turn it on for itself. Only a
2469
- // literal `true` from the caller counts — an absent or `undefined`
2470
- // field is off, which is what keeps every existing caller (the
2471
- // renderer's IPC payloads included) on the cheap read.
2472
- recallDeep: payload && payload.recallDeep === true,
2473
- // The fan-out opt-out, and it must be an explicit `true` for the same
2474
- // reason `recallDeep` is. `undefined` is NOT an opt-out: the wire flag
2475
- // below is `singlePass ? false : autonomous ? true : undefined`, and an
2476
- // absent `brain` flag lets the *model id* turn the fan-out on by itself
2477
- // (aegis1 pool_brain.parse_brain_request: `is_brain_model(spec)` alone
2478
- // enables it). So a clamped task on a brain model fanned out anyway
2479
- // while the log claimed a single pass — the caller's intent never
2480
- // reached the wire. Forwarding it here is what lets the refusal be real
2481
- // rather than a local boolean nobody downstream could see.
2482
- singlePass: payload && payload.singlePass === true,
2483
- onReasoning,
2484
- idleTimeoutMs: autonomous ? AUTONOMOUS_IDLE_TIMEOUT_MS : undefined,
2485
- // A caller with no live streaming surface (a `--no-stream` CLI flag, a
2486
- // one-shot script) can ask for the buffered non-stream wire form
2487
- // instead. Undefined/anything but `false` keeps every existing caller
2488
- // (the desktop renderer never sets this) on the streamed path.
2489
- stream: payload && payload.stream === false ? false : true,
2490
- };
2491
-
2492
- // No round cap: a model that keeps calling tools keeps going for as
2493
- // long as it wants to. The old fixed cap (12 rounds) cut off genuinely
2494
- // long research/exploration turns mid-investigation. A turn ends when
2495
- // the model answers with text, or the user cancels.
2496
- //
2497
- // Both of those exit paths need a guard, because a provider's
2498
- // "I'm finished" signal can arrive with no answer attached — which is
2499
- // exactly how the renderer came to paint "(empty response)" over a turn
2500
- // that had actually done real work:
2501
- // - truncated (finish_reason 'length'): the budget was consumed
2502
- // before any visible text (DeepSeek's hidden reasoning bills
2503
- // against max_tokens), or mid tool-call JSON. One doubled retry.
2504
- // - empty (no tool call AND no text): re-dispatch once with no tools
2505
- // and a nudge, so the model has to write up what it already found.
2506
- // Each guard fires at most once per turn, so a provider that is simply
2507
- // broken still terminates instead of looping.
2508
- let truncationRetried = false;
2509
- let synthesisDone = false;
2510
-
2511
- // Round cap — a bound the upstream engine has had all along and this engine
2512
- // did not. Removing the old fixed cap (12) was right in spirit and wrong
2513
- // in effect: it left the turn with NO horizon, and on 2026-09-15 the
2514
- // question "can you check the plan" ran ~70 rounds, grew the context
2515
- // from 2,260 to 116,011 tokens, cost about EUR 2, and spent those rounds
2516
- // writing 400 lines of unrequested code into the source tree. Each round
2517
- // re-sends the whole conversation, so an unbounded loop gets more
2518
- // expensive the longer it runs.
2519
- //
2520
- // The numbers match the upstream engine's (src/autonomous.js) so both clients
2521
- // behave the same: 24 rounds for a chat turn, 40 for an autonomous one.
2522
- // Env-overridable for a deliberately long job.
2523
- // A stated horizon (env) still wins outright — an explicit number is the
2524
- // user overriding the engine, not something the ledger may pad.
2525
- const roundEnvName = autonomous ? 'AEGIS_AUTONOMOUS_MAX_ROUNDS' : 'AEGIS_CHAT_MAX_ROUNDS';
2526
- const statedRounds = (() => {
2527
- const raw = Number.parseInt(process.env[roundEnvName] || '', 10);
2528
- return Number.isFinite(raw) && raw > 0 ? raw : 0;
2529
- })();
2530
- const baseRounds = statedRounds || (autonomous ? 40 : 24);
2531
-
2532
- // Did the previous turn in this session die at its horizon? If so, this
2533
- // turn is a continuation of it: same job, unfinished, and the model has
2534
- // to be told — a cold restart is what made the old cap lose work.
2535
- let roundSessionKey = sessionRounds.keyFor(payload, history);
2536
- let resumed = sessionRounds.take(roundSessionKey);
2537
- if (!resumed) {
2538
- // The caller minted a fresh key this turn (no stated session id and a
2539
- // rebuilt history array). Adopt the held work rather than dropping it,
2540
- // but only within the ledger's recency window.
2541
- const adopted = sessionRounds.adopt();
2542
- if (adopted) {
2543
- resumed = adopted.entry;
2544
- roundSessionKey = adopted.key;
2545
- }
2546
- }
2547
- if (resumed) {
2548
- const preamble = sessionRounds.resumePreamble(resumed);
2549
- // Restore the interrupted turn's transcript, because the preamble alone
2550
- // says HOW MUCH was done, not WHAT. The two callers need different
2551
- // halves of it, so `session-rounds` files both (see `record`):
2552
- //
2553
- // · a caller who brings no conversation of its own — the queue
2554
- // worker's fresh dispatch; autonomous.js never sends `messages` —
2555
- // has nothing, so it gets the FULL transcript;
2556
- // · an interactive chat already carries the prior turns (and the
2557
- // "stopped at N rounds" note), so it gets only what THIS turn added
2558
- // that the caller never saw: the tool calls and their results. Full
2559
- // restore here would duplicate the caller's own text.
2560
- //
2561
- // The old `history.length === 0` guard did the first and not the second,
2562
- // so the resume it was written for a queue task never reached the
2563
- // interactive sessions this feature is actually used from.
2564
- if (history.length === 0) {
2565
- if (Array.isArray(resumed.messages) && resumed.messages.length) history.push(...resumed.messages);
2566
- } else if (Array.isArray(resumed.added) && resumed.added.length) {
2567
- history.push(...resumed.added);
2568
- }
2569
- // Round 1's ask travels as `prompt`; a follow-up dispatch (and every
2570
- // turn that skips the shorthand) has to receive it through history.
2571
- if (prompt) prompt = `${preamble}\n\n${prompt}`;
2572
- else history.push({ role: 'user', content: preamble });
2573
- if (rootOnDelta) {
2574
- rootOnDelta({
2575
- delta:
2576
- `\n\n[resuming work this session left unfinished at ${resumed.rounds} tool rounds` +
2577
- `${resumed.interruptions > 1 ? ` (cut off ${resumed.interruptions}×)` : ''}…]\n`,
2578
- });
2579
- }
2580
- }
2581
- // A resumed turn gets a small bonus on top of the base horizon so
2582
- // re-orientation does not consume the new budget before any work lands.
2583
- let maxRounds = statedRounds || baseRounds + (resumed ? sessionRounds.bonus(baseRounds) : 0);
2584
- let round = 0;
2585
- // Rounds bought by one confirmed extension, and a hard cap on how many
2586
- // extensions a single turn may spend — matching the upstream engine's
2587
- // numbers (src/autonomous.js ROUND_EXTENSION_SIZE/MAX_ROUND_EXTENSIONS)
2588
- // so a turn behaves the same whether it runs there or here. The cap
2589
- // exists even though the renderer is the one asking: a dialog that
2590
- // always says yes must still terminate (8 x baseRounds extra rounds).
2591
- const ROUND_EXTENSION_SIZE = baseRounds;
2592
- const MAX_ROUND_EXTENSIONS = 8;
2593
- let extensions = 0;
2594
-
2595
- // Token accounting for the whole TURN, not just its last round. An
2596
- // agentic turn makes one provider call per tool round, and returning only
2597
- // the final round's `usage` (what this did) reported a fraction of what
2598
- // was actually spent — the tool phase's tokens simply disappeared. Every
2599
- // dispatch is summed, including the truncation retry and the synthesis
2600
- // re-dispatch: both are real, separately billed provider calls.
2601
- const turnUsage = { calls: 0 };
2602
- // The cache fields MUST be listed here, not just summed at the top level.
2603
- // DeepSeek reports its hit count as `prompt_cache_hit_tokens` and its
2604
- // miss count as `prompt_cache_miss_tokens`, and neither name was in this
2605
- // list — so every tool-using turn dropped them on the way out and handed
2606
- // its caller a usage object with no cache information at all. The CLI's
2607
- // `--json` republishes exactly this accumulator, `usageBuckets` then had
2608
- // nothing to read, and the published cost of an agentic run was priced
2609
- // entirely at the miss rate. Measured on the 3-task sweep: `cache_read: 0`
2610
- // on all three trials (tokens_in 210,904) while the row's own baseline
2611
- // showed 72,448 cached tokens. The same defect the CLI's per-turn readout
2612
- // was fixed for, here one layer below it.
2613
- const USAGE_FIELDS = [
2614
- 'input_tokens', 'output_tokens', 'prompt_tokens', 'completion_tokens', 'total_tokens',
2615
- // Anthropic spelling (disjoint from its input count).
2616
- 'cache_read_input_tokens', 'cache_creation_input_tokens',
2617
- // DeepSeek/OpenAI spelling (both SUBSETs of the prompt count, which is
2618
- // what `usageBuckets` detects and subtracts rather than double-billing).
2619
- 'prompt_cache_hit_tokens', 'prompt_cache_miss_tokens',
2620
- // Hidden deliberation, which every provider here bills as OUTPUT but
2621
- // none of them split out for free. These were absent from the list
2622
- // while `reasoningTokensOf` (below) already knew how to read them, so
2623
- // the one place that could have separated "wrote more code" from
2624
- // "thought longer" threw the split away at the accumulator and handed
2625
- // its caller a single `output_tokens` with CoT folded in. A benchmark
2626
- // row could therefore see that a turn cost 1.9x another's output and
2627
- // still have no way to say which half moved.
2628
- 'reasoning_tokens', 'thinking_tokens',
2629
- ];
2630
- const addUsage = (res) => {
2631
- const u = res && res.usage;
2632
- if (!u || typeof u !== 'object') return;
2633
- turnUsage.calls += 1;
2634
- for (const key of USAGE_FIELDS) {
2635
- if (typeof u[key] === 'number' && Number.isFinite(u[key])) {
2636
- turnUsage[key] = (turnUsage[key] || 0) + u[key];
2637
- }
2638
- }
2639
- // A provider that reports only the split (Anthropic-compatible) has no
2640
- // total to sum, so derive one or the renderer has nothing to print.
2641
- if (typeof u.total_tokens !== 'number') {
2642
- const derived =
2643
- (u.prompt_tokens ?? u.input_tokens ?? 0) + (u.completion_tokens ?? u.output_tokens ?? 0);
2644
- if (derived) turnUsage.total_tokens = (turnUsage.total_tokens || 0) + derived;
2645
- }
2646
- };
2647
- // The turn's totals win over any single round's, so the attached usage is
2648
- // never the last round wearing the whole turn's label.
2649
- const withTurnUsage = (res) => {
2650
- if (!res || typeof res !== 'object' || !turnUsage.calls) return res;
2651
- // Built from the accumulator alone: every field already present in a
2652
- // round's usage was summed into it, so merging the last round back in
2653
- // could only reintroduce a partial number under a whole-turn label.
2654
- return { ...res, usage: { ...turnUsage } };
2655
- };
2656
-
2657
- // Round 1's shorthand prompt was sent as `prompt`, not as a message, so
2658
- // any follow-up dispatch in this turn must fold it into the history
2659
- // first or the model would be shown a nudge with no question above it.
2660
- const foldPromptIntoHistory = () => {
2661
- if (prompt === '') return;
2662
- const last = history[history.length - 1];
2663
- if (!(last && last.role === 'user' && last.content === prompt)) {
2664
- history.push({ role: 'user', content: prompt });
2665
- }
2666
- prompt = '';
2667
- };
2668
-
2669
- // From here on, everything pushed into `history` is this turn's own work:
2670
- // the restored transcript above (if any) belongs to the turn it came from,
2671
- // and re-recording it would double the ledger on every interruption.
2672
- historyStart = history.length;
2673
-
2674
- for (;;) {
2675
- // Stop and SAY so. A turn that reaches its horizon has usually done
2676
- // real work; ending silently would paint an empty answer over it,
2677
- // which is the same "(empty response)" failure the guards below exist
2678
- // to prevent.
2679
- if (round >= maxRounds) {
2680
- // Before conceding, give an interactive caller the chance to fund
2681
- // another block of rounds instead of ending the turn outright — the
2682
- // upstream engine's "asks" contract (src/backend.js requestExtension).
2683
- // Only reachable with `roundsAsk` AND a live signal: a caller with no
2684
- // renderer on the other end (queue, `-p`) falls straight through to
2685
- // the session-hold stop below, unchanged.
2686
- if (roundsAsk && extensions < MAX_ROUND_EXTENSIONS && !signal.aborted) {
2687
- const granted = await requestRoundsAsk(rootSessionId, rootOnDelta, signal, {
2688
- spent: maxRounds,
2689
- extensions: extensions + 1,
2690
- max: MAX_ROUND_EXTENSIONS,
2691
- size: ROUND_EXTENSION_SIZE,
2692
- });
2693
- if (granted) {
2694
- extensions += 1;
2695
- const spent = maxRounds;
2696
- maxRounds += ROUND_EXTENSION_SIZE;
2697
- history.push({
2698
- role: 'user',
2699
- content: `You have used all ${spent} tool rounds allowed for this turn; ` +
2700
- `${ROUND_EXTENSION_SIZE} more have been granted (do not restart). Continue the task ` +
2701
- 'from exactly where you stopped — do not re-plan, do not repeat work already done, ' +
2702
- 'and finish with an answer.',
2703
- });
2704
- continue;
2705
- }
2706
- // Declined (or the extension cap is spent): fall through to the
2707
- // same session-hold stop a non-interactive caller gets, so a "no"
2708
- // here is bit-for-bit the old hard stop rather than a dead end.
2709
- }
2710
- // The knob is only advice where nobody could have been asked about
2711
- // it. An interactive caller was already offered another block of
2712
- // rounds (requestRoundsAsk above) and declined or spent the cap, so
2713
- // pointing it at an env var it cannot set from inside the app — and
2714
- // would have to restart to apply — is obsolete text: drop it. The
2715
- // queue worker and `-p` one-shots have no dialog, so for them the
2716
- // variable remains the only lever and is still named.
2717
- const knob = roundsAsk ? '' : `, or raise ${roundEnvName} for a longer single turn`;
2718
- const note =
2719
- `[stopped at ${maxRounds} tool rounds` +
2720
- `${turnUsage.total_tokens ? `, ${turnUsage.total_tokens.toLocaleString()} tokens` : ''}` +
2721
- `. This session holds the work: your next message here resumes it automatically` +
2722
- ` (with a continuation preamble)${knob}.]`;
2723
- // File the interruption before returning, so the horizon is a pause
2724
- // in the session rather than the end of the job. `chain` carries the
2725
- // count forward across resumes.
2726
- const held = sessionRounds.record(roundSessionKey, {
2727
- rounds: round,
2728
- tokens: turnUsage.total_tokens || 0,
2729
- note,
2730
- chain: resumed ? resumed.interruptions : 0,
2731
- // The actual tool-call/tool-result transcript built up this turn —
2732
- // everything folded/pushed into `history` by completed rounds — so
2733
- // a resume can restore real memory of the work, not just a count
2734
- // of it (see the `resumed.messages` rehydration above).
2735
- messages: history,
2736
- // …and only what this turn itself added, for the caller that
2737
- // already has the rest of `history` in its own conversation.
2738
- added: history.slice(historyStart),
2739
- });
2740
- if (rootOnDelta) rootOnDelta({ delta: `\n\n${note}` });
2741
- return withTurnUsage({
2742
- model: base.model,
2743
- choices: [{ message: { content: note }, finish_reason: 'length' }],
2744
- stoppedOnRounds: true,
2745
- heldForSession: true,
2746
- heldRounds: held.rounds,
2747
- sessionInterruptions: held.interruptions,
2748
- resumedFrom: roundSessionKey,
2749
- });
2750
- }
2751
- round += 1;
2752
- // `round === 1` is the user's own ask, and the ONLY dispatch allowed to
2753
- // carry the deep-recall opt-in: the deep tier embeds the query once per
2754
- // dispatch, so leaving it on for an agentic turn would charge one
2755
- // embedding per tool round instead of one per turn (the retries below
2756
- // clear it explicitly, being re-dispatches inside round 1).
2757
- const opts = { ...base, system, messages: history, prompt, tools: toolSchemas, recallDeep: base.recallDeep && round === 1 };
2758
- let res;
2759
- res = await dispatch(cls, opts);
2760
- addUsage(res);
2761
-
2762
- // A cancelled turn is over. Both recoveries below exist for "the model
2763
- // said nothing", and an aborted request resolves with exactly that —
2764
- // no text — so without this guard a user pressing Esc to stop a slow
2765
- // turn immediately issued ANOTHER billed provider call (and, because
2766
- // every transport concatenates the deltas it forwards, streamed the
2767
- // partial answer a second time onto the same bubble). Measured before
2768
- // the guard: one interrupted turn == two dispatches.
2769
- if (signal.aborted) return withTurnUsage(res);
2770
-
2771
- // Budget exhausted before the answer was written. Doubling it costs
2772
- // one request and converts a dead turn into a real one; a second
2773
- // 'length' result is accepted as-is so a hard-capped model can't
2774
- // spin here forever.
2775
- //
2776
- // Gated on empty text on purpose. Every transport builds `content`
2777
- // by concatenating the deltas it already forwarded to onDelta, so
2778
- // empty content means nothing was streamed and re-dispatching cannot
2779
- // double up in the renderer's live view. When text *has* arrived the
2780
- // turn is not empty — the answer is merely truncated — and a retry
2781
- // would stream it a second time onto the same bubble.
2782
- if (!truncationRetried && !assistantText(res) && (isTruncated(res) || reasonedButSilent(res))) {
2783
- truncationRetried = true;
2784
- const reasoningOnly = reasonedButSilent(res);
2785
- // singlePass: this retry buys *budget*, not a second investigation.
2786
- // The fan-out's workers would re-run the whole task from scratch for
2787
- // it — 3 extra reasoning passes + a synthesis — which is the opposite
2788
- // of what "one doubled request" means (and what the note above
2789
- // promises). The pass itself is unchanged apart from that.
2790
- res = await dispatch(cls, {
2791
- ...opts,
2792
- singlePass: true,
2793
- // A re-dispatch, not a new ask: the deep tier's embedding was
2794
- // bought by round 1, and buying it again here would charge a
2795
- // second one for the same context.
2796
- recallDeep: false,
2797
- // A reasoning-only completion gets the high rung AND high effort:
2798
- // the model is about to re-pay for the same chain-of-thought, and
2799
- // on DeepSeek that pair is what actually moves the ceiling.
2800
- effort: reasoningOnly ? 'high' : opts.effort,
2801
- maxTokens: retryBudgetFor(opts, reasoningOnly),
2802
- // Doubling applies to the pooled path only when the caller stated a
2803
- // number. With none stated, the server's effort ladder IS the
2804
- // budget, and sending doubledBudget's 8192 floor would *lower* it
2805
- // (aegis1 reads max_tokens as a ceiling over the ladder) — a
2806
- // "double the budget" retry that halves it at high effort.
2807
- statedMaxTokens: opts.statedMaxTokens ? doubledBudget(opts.statedMaxTokens) : undefined,
2808
- });
2809
- addUsage(res);
2810
- // Same guard as line ~1499, for the same reason: an abort landing
2811
- // during THIS dispatch also resolves as empty text, and without
2812
- // this check that "no answer" would fall straight into the
2813
- // empty-turn nudge below instead of ending the turn — a cancelled
2814
- // request quietly buying a THIRD billed call.
2815
- if (signal.aborted) return withTurnUsage(res);
2816
- }
2817
-
2818
- const calls = toolSchemas.length ? extractToolCalls(res) : [];
2819
- if (!calls.length) {
2820
- if (assistantText(res) || synthesisDone || !toolsEnabled) return withTurnUsage(res);
2821
- // The model stopped without calling a tool and without saying
2822
- // anything. Force the summary out of the context it already holds
2823
- // instead of handing the renderer a blank completion. Skipped when
2824
- // the caller opted out of the agent loop (`tools: false`): there is
2825
- // no gathered context to rescue, so a bare completion is just that.
2826
- synthesisDone = true;
2827
- foldPromptIntoHistory();
2828
- // The nudge is chosen by what the empty round actually WAS, not by the
2829
- // fact that it was empty. A round that spent its budget on hidden
2830
- // reasoning and stopped without writing a word needs to be told not to
2831
- // think; the generic wording invites the same silent pass a second
2832
- // time, which is precisely how a recoverable turn became
2833
- // `emptyTurnError` on byok/deepseek-v4-flash (2026-10-11).
2834
- history.push({ role: 'user', content: reasonedButSilent(res) ? THOUGHT_ONLY_NUDGE : EMPTY_TURN_NUDGE });
2835
- // singlePass: same reasoning as the truncation retry above, and it is
2836
- // the same comment's literal promise ("force the summary out of the
2837
- // context it already holds"). Escalating a write-up back into the
2838
- // worker fan-out asked three fresh workers to redo an investigation
2839
- // whose findings are already in `history`, at 4x the cost, to produce
2840
- // a paragraph the model had all the material for.
2841
- const synthesisOpts = {
2842
- ...opts,
2843
- singlePass: true,
2844
- // Same as the truncation retry above: this pass writes up findings
2845
- // already in `history`, and a fresh embedding buys it nothing.
2846
- recallDeep: false,
2847
- messages: history,
2848
- prompt: '',
2849
- tools: [],
2850
- };
2851
- res = await dispatch(cls, synthesisOpts);
2852
- // The ceiling and the rung of the last dispatch that came back empty,
2853
- // so the failure below reports the call that actually failed instead of
2854
- // the original one it was retried away from.
2855
- let lastBudget = synthesisOpts.maxTokens;
2856
- let lastEffort = synthesisOpts.effort;
2857
- addUsage(res);
2858
- // Same guard again: a cancel landing during the synthesis pass
2859
- // resolves empty too, and without this check it fell through to
2860
- // emptyTurnError — a real exception, so the renderer painted a red
2861
- // "no answer" failure over what was actually just the user hitting
2862
- // Cancel.
2863
- if (signal.aborted) return withTurnUsage(res);
2864
- // The SAME truncation retry the main round gets, one level down: the
2865
- // write-up pass is itself a fresh dispatch billed against `opts.maxTokens`,
2866
- // and a reasoning model can burn that whole budget on hidden
2867
- // chain-of-thought a SECOND time while composing the summary — history
2868
- // is bigger than round 1's, so if anything this pass is more likely to
2869
- // need the room. Without this, "the synthesis pass also got
2870
- // truncated" and "the model is simply done" were indistinguishable —
2871
- // both threw the same emptyTurnError — even though the first is
2872
- // recoverable with the exact one-line fix already proven above.
2873
- if (!assistantText(res) && (isTruncated(res) || reasonedButSilent(res))) {
2874
- const reasoningOnly = reasonedButSilent(res);
2875
- lastBudget = retryBudgetFor(synthesisOpts, reasoningOnly);
2876
- lastEffort = reasoningOnly ? 'high' : synthesisOpts.effort;
2877
- res = await dispatch(cls, {
2878
- ...synthesisOpts,
2879
- effort: lastEffort,
2880
- maxTokens: lastBudget,
2881
- statedMaxTokens: synthesisOpts.statedMaxTokens
2882
- ? doubledBudget(synthesisOpts.statedMaxTokens)
2883
- : undefined,
2884
- });
2885
- addUsage(res);
2886
- if (signal.aborted) return withTurnUsage(res);
2887
- }
2888
- // ── The recovery ladder: extra calls, not a verdict ────────────────
2889
- // Everything above bought a bigger ceiling; this changes the ASK —
2890
- // and repeats it — because a round that reasoned and then stayed
2891
- // silent has already been handed more room and still did not write a
2892
- // word.
2893
- //
2894
- // This is the upstream engine's own trade (`src/backend.js`, the
2895
- // `thoughtOnly` recovery round): spend another call rather than hand
2896
- // the reader a red "backend error: … raise the Effort rung" over work
2897
- // that is finished and already sitting in `history`. Telling someone
2898
- // to go and raise a setting is not a recovery, and the ceiling it
2899
- // points at was raised by the retry above — so the ladder spends
2900
- // calls, with a variant of the ask each time, and only reports
2901
- // failure when every one of them comes back empty as well.
2902
- //
2903
- // Bounded by construction: `RECOVERY_ROUNDS` caps the calls,
2904
- // `synthesisDone` is already true, and each nudge JOINS `history`
2905
- // rather than replacing it — every round here runs with `tools: []`,
2906
- // so a round is a re-ask out of context the model already holds and
2907
- // can never become a fresh investigation.
2908
- //
2909
- // The ceiling lift below is computed ONCE, not per round. A ladder
2910
- // that doubled the budget each time would turn "two more calls" into
2911
- // "two more calls at double the price" for a model whose problem is
2912
- // demonstrably not the price, and Math.max keeps it monotone: for a
2913
- // rung this is the top of the ladder, and a number a previous retry
2914
- // already raised past it (a caller's doubled cap) is never lowered.
2915
- const ladderBudget = (() => {
2916
- const owned = Number(lastBudget) || 0;
2917
- // No number in hand — the caller stated none and the model is not a
2918
- // reasoning model, so `reasoningBudget()` sends no `max_tokens` at
2919
- // all and the provider's own limit governs. Inventing one here
2920
- // (retryBudgetFor's 8192 floor) would put a ceiling on the wire that
2921
- // nobody asked for, which is the very defect this file's budget
2922
- // comments were written about. The ladder's extra call is then the
2923
- // same price as the call it repeats, and only the ask changes.
2924
- if (!owned) return lastBudget;
2925
- const ask = { maxTokens: lastBudget };
2926
- if (synthesisOpts.statedMaxTokens) ask.statedMaxTokens = synthesisOpts.statedMaxTokens;
2927
- return Math.max(owned, retryBudgetFor(ask, true));
2928
- })();
2929
- let recoveryRounds = 0;
2930
- while (!assistantText(res) && recoveryRounds < RECOVERY_ROUNDS && !signal.aborted) {
2931
- const reasoningOnly = reasonedButSilent(res);
2932
- recoveryRounds += 1;
2933
- history.push({
2934
- role: 'user',
2935
- content: reasoningOnly
2936
- ? recoveryRounds === 1
2937
- ? THOUGHT_ONLY_NUDGE
2938
- : FINAL_ANSWER_NUDGE
2939
- : EMPTY_TURN_NUDGE,
2940
- });
2941
- if (reasoningOnly) lastEffort = 'high';
2942
- lastBudget = ladderBudget;
2943
- res = await dispatch(cls, {
2944
- ...synthesisOpts,
2945
- messages: history,
2946
- effort: lastEffort,
2947
- maxTokens: lastBudget,
2948
- statedMaxTokens: synthesisOpts.statedMaxTokens
2949
- ? doubledBudget(synthesisOpts.statedMaxTokens)
2950
- : undefined,
2951
- });
2952
- addUsage(res);
2953
- if (signal.aborted) return withTurnUsage(res);
2954
- }
2955
- if (!assistantText(res)) {
2956
- throw emptyTurnError({
2957
- cls,
2958
- model,
2959
- // What the LAST call looked like, and how many extra calls the
2960
- // ladder already spent: the report describes the call that failed
2961
- // rather than the first one it was retried away from.
2962
- effort: lastEffort,
2963
- recoveryRounds,
2964
- finishReason: finishReasonOf(res),
2965
- reasoningChars: reasoningTextOf(res).length,
2966
- // The withheld-deliberation case (a Pro turn with extended
2967
- // thinking on): no chars to count, but the provider billed the
2968
- // thinking. Without this the report claims nothing came back.
2969
- reasoningTokens: reasoningTokensOf(res),
2970
- });
2971
- }
2972
- return withTurnUsage(res);
2973
- }
2974
-
2975
- foldPromptIntoHistory();
2976
-
2977
- // Thread the assistant turn (its tool_calls) and each result back in
2978
- // the OpenAI shape the relay accepts.
2979
- history.push({
2980
- role: 'assistant',
2981
- content: assistantText(res),
2982
- tool_calls: calls.map((c) => ({
2983
- id: c.id,
2984
- type: 'function',
2985
- function: { name: c.name, arguments: JSON.stringify(c.args) },
2986
- })),
2987
- });
2988
-
2989
- for (const call of calls) {
2990
- // Open the live row BEFORE the tool runs. The CLI paints
2991
- // `Running N … · 3s` off a `phase: 'run'` frame and ticks it while
2992
- // the tool is still going; reporting the tool only once, after it
2993
- // finished, left the transcript showing a spinner verb and nothing
2994
- // else for the whole exec timeout (120s, up to 600s) — which reads
2995
- // as a wedged turn rather than a working one.
2996
- if (onDelta) {
2997
- onDelta({
2998
- delta: '',
2999
- tool: { name: call.name, args: call.args, id: call.id, cwd: turnCwd, phase: 'run' },
3000
- });
3001
- }
3002
- const result = call.name === T.SUBAGENT_TOOL
3003
- ? await runSubagent(call.args, {
3004
- cls, model, statedMaxTokens, effort: payload && payload.effort,
3005
- mode: payload && payload.mode, parentSignal: signal, depth, rootSessionId, rootOnDelta,
3006
- })
3007
- : await gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal });
3008
- // A subagent's spend rides back on its tool result (see runSubagent).
3009
- if (result && result.usage) addUsage({ usage: result.usage });
3010
- // The id is carried on both frames: the CLI pairs them by id first,
3011
- // precisely so parallel same-name calls don't collapse into one row
3012
- // with the wrong plural.
3013
- if (onDelta) {
3014
- onDelta({
3015
- delta: '',
3016
- tool: { name: call.name, args: call.args, ok: result.ok, id: call.id, cwd: turnCwd, phase: 'done' },
3017
- });
3018
- }
3019
- history.push({
3020
- role: 'tool',
3021
- tool_call_id: call.id,
3022
- name: call.name,
3023
- content: T.toolResultText(result),
3024
- });
3025
- }
3026
- }
3027
- } finally {
3028
- if (shell) shell.dispose();
3029
- controllers.delete(sessionId);
3030
- }
3031
- }
3032
-
3033
- /**
3034
- * Run a `task` tool call as a subagent: a nested chat() turn on the same
3035
- * class/model, primed with the chosen specialist's system prompt (agents.js)
3036
- * and its own tool access (including task, until MAX_SUBAGENT_DEPTH cuts
3037
- * it off), returning the subagent's final text as the tool result. Never
3038
- * throws — resolves { ok, output } or { ok:false, error }, matching
3039
- * tools.js's executor contract so the caller treats it identically.
3040
- */
3041
- async function runSubagent(
3042
- { description, subagent_type, prompt: subPrompt } = {},
3043
- { cls, model, statedMaxTokens, effort, mode, parentSignal, depth, rootSessionId, rootOnDelta } = {}
3044
- ) {
3045
- const task = String(subPrompt || description || '').trim();
3046
- if (!task) return { ok: false, error: 'task requires a prompt' };
3047
- const label = subagent_type && subagent_type !== 'general' ? agentRoleLabel(subagent_type) : 'general';
3048
- const system = agentSystemPrompt(subagent_type);
3049
- const subSessionId = randomUUID();
3050
-
3051
- // Aborting the parent turn must also stop a running subagent instead of
3052
- // leaving it to finish on its own (or sit out the whole turn timeout).
3053
- let onParentAbort;
3054
- if (parentSignal) {
3055
- if (parentSignal.aborted) return { ok: false, error: 'aborted' };
3056
- onParentAbort = () => cancel(subSessionId);
3057
- parentSignal.addEventListener('abort', onParentAbort, { once: true });
3058
- }
3059
-
3060
- try {
3061
- // rootSessionId/rootOnDelta ride along explicitly (see chat()) so the
3062
- // subagent's own mutating tool calls still gate through the SAME
3063
- // approval card the user sees for the top-level turn, instead of
3064
- // silently hanging behind this call's no-op onDelta below.
3065
- const res = await chat(
3066
- {
3067
- class: cls, model, mode, system, prompt: task, sessionId: subSessionId, depth: (depth || 0) + 1,
3068
- rootSessionId, rootOnDelta,
3069
- // The parent's budget AUTHORITY is forwarded, not the number it
3070
- // implies. `maxTokens` is deliberately absent: it is the rung this
3071
- // turn derived from `effort`, and a re-entry that hands it back gets
3072
- // read as the caller's own cap (statedCapOf). The rung itself rides
3073
- // along as `effort`, which is what aegis1 sizes the fan-out and its
3074
- // ladder from — so a subagent now runs at the effort the user chose
3075
- // instead of at a number that only meant anything for this model id.
3076
- statedMaxTokens,
3077
- effort,
3078
- },
3079
- () => {}
3080
- );
3081
- const text = assistantText(res);
3082
- // The subagent's tokens were billed to the same account as the parent
3083
- // turn, so its usage travels back on the tool result and is summed into
3084
- // the parent's total. Attached even on the no-output branch: a subagent
3085
- // that burned a full context and said nothing is precisely the spend the
3086
- // user most needs to see.
3087
- const spent = res && res.usage ? { usage: res.usage } : {};
3088
- return text
3089
- ? { ok: true, output: text, ...spent }
3090
- : { ok: false, error: `subagent (${label}) produced no output`, ...spent };
3091
- } catch (e) {
3092
- return { ok: false, error: `subagent (${label}) failed: ${e && e.message ? e.message : e}` };
3093
- } finally {
3094
- if (parentSignal && onParentAbort) parentSignal.removeEventListener('abort', onParentAbort);
3095
- }
3096
- }
3097
-
3098
- function cancel(sessionId) {
3099
- const controller = controllers.get(sessionId);
3100
- if (controller) controller.abort();
3101
- return { ok: Boolean(controller) };
3102
- }
3103
-
3104
- /**
3105
- * Unload every local model this engine warmed, across every daemon it
3106
- * talked to (local.js `unloadAll`). The desktop host calls this on its quit
3107
- * path so closing the app also closes the model — the local lane bills
3108
- * nothing precisely because it is YOUR hardware, and hardware left running
3109
- * a model nobody is using anymore after the app exits is the one cost that
3110
- * lane was supposed to never have.
3111
- */
3112
- function unloadLocalModels() {
3113
- return localT.unloadAll();
3114
- }
3115
-
3116
- /**
3117
- * The vendor key for a provider, resolved in the order the NEXT TURN will
3118
- * resolve it: the saved `byok:<provider>` row first, then `~/.aegiscode/.env`
3119
- * (loaded into the environment at host start-up by `client/env-file.js`) and
3120
- * the shell. Discovery must ask with the key the call will run on — a list
3121
- * fetched with a different one describes a catalog this machine cannot reach.
3122
- *
3123
- * Read-only by construction: it never writes a key, never hands the value to
3124
- * a renderer and never logs it.
3125
- */
3126
- function byokKeyForProviderLookup(providerId) {
3127
- const id = String(providerId == null ? '' : providerId).trim().toLowerCase();
3128
- if (!id) return '';
3129
- try {
3130
- if (settings && typeof settings.rawKey === 'function') {
3131
- const stored = settings.rawKey(byokNamespace(id));
3132
- if (typeof stored === 'string' && stored.trim()) return stored.trim();
3133
- }
3134
- } catch { /* a store that throws has no key, and that is a reportable state */ }
3135
- return providerKeyFromEnv(id);
3136
- }
3137
-
3138
- return {
3139
- CLASSES,
3140
- listClasses,
3141
- listModels,
3142
- chat,
3143
- cancel,
3144
- respondApproval,
3145
- respondRoundsAsk,
3146
- clearSessionApprovals,
3147
- settings,
3148
- unloadLocalModels,
3149
- // The user's own model declarations (`$AEGISCODE_HOME/models.json`), read,
3150
- // added and removed through ONE implementation because THREE faces write
3151
- // them: the desktop's Settings row (via main.js's model dispatch), the
3152
- // CLI's `/model-add`, and the user's own editor. `userModels()` returns
3153
- // `{ dir, file, map, invalid }` so a host can SHOW where the file is and
3154
- // name the rows it refused (`invalid`), instead of a declaration vanishing
3155
- // into a picker that looks like the feature did nothing.
3156
- //
3157
- // Add/remove THROW on a malformed provider or model id (that is the point —
3158
- // an id the relay would forward to a vendor 404s on the user's first turn,
3159
- // where a rejected input 404s never), so every caller surfaces the message
3160
- // rather than storing it.
3161
- userModels: () => loadUserModels(),
3162
- addUserModel: (provider, model) => addUserModel(provider, model),
3163
- removeUserModel: (provider, model) => removeUserModel(provider, model),
3164
- // ── asking the vendor, so the user does not have to remember ids ───────
3165
- //
3166
- // `discoverModels(provider)` resolves and returns the ids the provider's own
3167
- // list API serves RIGHT NOW, which is the fix for the chore that produced
3168
- // `client/byok-catalog.js`'s hand-copied Anthropic table. It never throws:
3169
- // the shape is the discovery module's own
3170
- // `{ ok, provider, ids, others, count }` / `{ ok:false, error }`, and the
3171
- // renderer prints `error` verbatim. A window that guessed at an id and
3172
- // silently pinned a 404 is the outcome this exists to prevent.
3173
- //
3174
- // The key comes from the SAME chain the next turn will use (the saved
3175
- // `byok:<provider>` row, then `~/.aegiscode/.env`, then the shell), because
3176
- // a list fetched with a different key than the call runs on would describe
3177
- // somebody else's catalog.
3178
- discoverModels: async (provider) => {
3179
- const id = String(provider == null ? '' : provider).trim().toLowerCase();
3180
- const key = byokKeyForProviderLookup(id);
3181
- const res = await discoverVendorModels(id, { key, fetchImpl });
3182
- // Say what the caller needs to offer the next step: which of these the
3183
- // relay itself already lists, and which this machine has declared, so the
3184
- // UI can mark a row instead of the user diffing two lists by eye.
3185
- if (!res || !res.ok) return res;
3186
- const declared = [];
3187
- try {
3188
- const map = loadUserModels().map;
3189
- for (const m of Array.isArray(map[id]) ? map[id] : []) declared.push(m);
3190
- } catch { /* a store that cannot be read marks nothing */ }
3191
- return { ...res, declared, endpoint: (vendorEndpointFor(id) || {}).url || '' };
3192
- },
3193
- // The bulk write (`/model-add <provider> '*'` and the desktop's "Add all"
3194
- // button): declare every id in one pass, skipping what is already there and
3195
- // NAMING what was refused rather than aborting the whole batch on one bad
3196
- // row. Returns counts, never a bare boolean, so both faces can report
3197
- // "3 added, 2 already declared" instead of claiming work they did not do.
3198
- addUserModels: (provider, ids) => {
3199
- const list = Array.isArray(ids) ? ids : [];
3200
- const out = { provider, added: 0, already: [], failed: [], capped: 0, file: '' };
3201
- for (const raw of list) {
3202
- try {
3203
- const res = addUserModel(provider, raw);
3204
- out.file = res.file || out.file;
3205
- if (res.added) out.added += 1;
3206
- else out.already.push(res.model);
3207
- } catch (err) {
3208
- const message = (err && err.message) || String(err);
3209
- // The store's per-provider ceiling ends the batch as a CEILING. A
3210
- // vendor serves a hundred ids and the store holds 32, so reporting
3211
- // that as sixty-eight refused models would describe one deliberate
3212
- // limit as sixty-eight broken ids.
3213
- if (/the cap/.test(message)) {
3214
- out.capped = list.length - out.added - out.already.length - out.failed.length;
3215
- break;
3216
- }
3217
- out.failed.push({ id: String(raw), reason: message });
3218
- }
3219
- }
3220
- return out;
3221
- },
3222
- // What the Settings row uses to decide whether to OFFER a list at all: a
3223
- // provider this client cannot ask (or has no key for) falls back to the
3224
- // free-form input, which is the path that always works.
3225
- canDiscoverModels: (provider) => canDiscoverVendorModels(provider),
3226
- discoverableProviders: () => discoverableProviders(),
3227
- };
3228
- }
3229
-
3230
- 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};