aegiscode 7.0.26 → 7.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4089
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +1 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
@@ -1,1030 +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
- * claude-pro.js — the Claude Code Pro class: the user's own Claude
10
- * subscription, driven through the `claude` CLI.
11
- *
12
- * ── why this is a CLASS and not a provider row ──────────────────────────────
13
- *
14
- * The other three classes reach a model over an HTTP API: `aegis` and `byok`
15
- * post to the AEGIS relay, `local` posts to a daemon on loopback. This one
16
- * reaches no API at all. A Pro/Max subscription is not an API key and is
17
- * deliberately not usable as one — Claude Code's OAuth session is bound to the
18
- * `claude` binary, and the only supported way for another program to spend that
19
- * subscription is to spawn that binary. `~/aegiscodex-dev` proved the shape
20
- * (src/backend.js runClaude): `claude -p <prompt> --output-format stream-json
21
- * --include-partial-messages --verbose`, reading the stream off stdout.
22
- *
23
- * So the class has no baseURL, no key row, and no relay. It has an ARGV.
24
- *
25
- * ── the two rules this file exists to keep ──────────────────────────────────
26
- *
27
- * 1. **The argv is DERIVED, never hand-typed.** `one/src/child.js` already owns
28
- * that decision (AEGISONE decision D8 rule 4) and states why: a spawn site
29
- * that writes its own flags is a second policy, and the child's permission
30
- * system is the one nobody on this side can answer. The only argv builder is
31
- * `claudeArgv(descriptor)`, fed a posture record from
32
- * `one/src/permissions.js resolvePosture()`. This module therefore does NOT
33
- * build flags; it asks for a posture record and hands over a descriptor.
34
- *
35
- * 2. **Auth is the CLI's, not ours.** ~/.claude/.credentials.json is read to
36
- * ANSWER "is there a subscription here", and never written. That is the same
37
- * read-only contract the rest of the repo states (client/credentials.js's
38
- * "another product's file"), and it is why `claudeProStatus()` is an
39
- * inspector rather than a login.
40
- *
41
- * Resolution of both sibling modules is by EXISTENCE in the two layouts the
42
- * repo already uses (a checkout, and the staged vendor tree), and a missing
43
- * child.js is a thrown error rather than a local re-implementation — a second
44
- * argv builder is exactly the drift rule 4 forbids.
45
- */
46
-
47
- const fs = require('node:fs');
48
- const os = require('node:os');
49
- const path = require('node:path');
50
-
51
- // client/env-file.js, resolved the same two ways engine.js already resolves
52
- // it (a checkout, and a packaged desktop build's flat vendor dir) — the CLI's
53
- // mirrored tree preserves this file's own relative position, so the same
54
- // checkout path also resolves there.
55
- let envFileLib = null;
56
- try {
57
- envFileLib = require('../../../client/env-file.js');
58
- } catch {
59
- try {
60
- envFileLib = require('../../vendor/env-file.js');
61
- } catch {
62
- envFileLib = null;
63
- }
64
- }
65
-
66
- /** Claude Code's own config dir; `$CLAUDE_CONFIG_DIR` wins, as the CLI's does. */
67
- function claudeConfigDir(env) {
68
- const e = env || process.env;
69
- const override = e && e.CLAUDE_CONFIG_DIR;
70
- if (override && String(override).trim()) return String(override).trim();
71
- return path.join(os.homedir(), '.claude');
72
- }
73
-
74
- /**
75
- * The user's Claude Code OAuth token, read the way the `claude` binary itself
76
- * wants it handed to it: into the CHILD's environment only, never exported
77
- * into this process's own `process.env`.
78
- *
79
- * `CLAUDE_CODE_OAUTH_TOKEN` is on client/env-file.js's FOREIGN_SECRET_NAMES —
80
- * a credential for a different CLI, deliberately left OUT of the ambient
81
- * `~/.aegiscode/.env` load every host does at start-up, because until this
82
- * class existed no host in this repo read it. This class is now that one
83
- * reader, and it reads it the way the split was designed for — explicitly,
84
- * for the one process that needs it, never ambient to every other process on
85
- * the machine.
86
- *
87
- * Checked in the order that keeps a real shell export authoritative:
88
- * 1. the caller's own env bag (an explicit `CLAUDE_CODE_OAUTH_TOKEN=…`
89
- * export always wins — the same rule `loadEnvFile`'s rule 1 states).
90
- * 2. `~/.aegiscode/secrets.env` — the file the split moves this name to.
91
- * 3. `~/.aegiscode/.env`, parsed directly and never applied to any env
92
- * object — covers a token that has not been migrated to secrets.env yet
93
- * (`tools/split-env-secrets.mjs` is the migration), without this class
94
- * having to make the value ambient to get there.
95
- *
96
- * @param {object} [env] defaults to process.env
97
- * @returns {string} '' when no source has it
98
- */
99
- function claudeOAuthToken(env) {
100
- // client/env-file.js owns the deny list AND the secrets-file resolution, so
101
- // it is the one place that answers "does a foreign secret exist anywhere" —
102
- // the CLI's model picker (cli/src/models.js) reads the SAME function to
103
- // decide whether `/model` still needs to collect this token, and a second
104
- // implementation here is exactly the drift that would let the two disagree.
105
- if (!envFileLib) return '';
106
- return envFileLib.resolveForeignSecret('CLAUDE_CODE_OAUTH_TOKEN', { env });
107
- }
108
-
109
- /**
110
- * The env names that SHADOW the subscription when the `claude` CLI starts.
111
- *
112
- * Claude Code authenticates with `ANTHROPIC_API_KEY` (or `ANTHROPIC_AUTH_TOKEN`)
113
- * when either is set, and that choice wins over the `claudeAiOauth` entry the
114
- * subscription lives in. So a value that is not a credential at all does not
115
- * merely fail on its own — it takes the plan down with it.
116
- */
117
- const SHADOWING_ENV_VARS = Object.freeze(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']);
118
-
119
- /**
120
- * Whether `value` is shaped like an Anthropic console API key.
121
- *
122
- * Deliberately a SHAPE test, not a validity test. This process cannot know
123
- * whether a key is live without spending it, so it does not try: it answers
124
- * only "could this possibly be the console credential that is allowed to
125
- * outrank a subscription". Anthropic console keys are `sk-ant-`-prefixed. The
126
- * check is case-sensitive and anchored, because that is the literal the vendor
127
- * uses — a case-insensitive match would accept `SK-ANT-` junk.
128
- *
129
- * @param {string} value
130
- * @returns {boolean}
131
- */
132
- function isAnthropicConsoleKey(value) {
133
- return typeof value === 'string' && /^sk-ant-[A-Za-z0-9_-]{8,}$/.test(value.trim());
134
- }
135
-
136
- /**
137
- * The env for one `claude` child, with a shadowing value that cannot be a
138
- * credential removed.
139
- *
140
- * ── why this exists (measured, 2026-10-14) ──────────────────────────────────
141
- *
142
- * `claude auth status` in the shell that launched this host:
143
- *
144
- * { "loggedIn": true, "authMethod": "claude.ai", "apiProvider": "firstParty",
145
- * "apiKeySource": "ANTHROPIC_API_KEY", "email": null, "orgId": null,
146
- * "subscriptionType": null } ← the two-character state
147
- *
148
- * and the identical command with the one variable unset (`env -u
149
- * ANTHROPIC_API_KEY claude auth status`):
150
- *
151
- * { … "email": "…", "orgId": "9d5e56e1-…", "orgName": "…",
152
- * "subscriptionType": "pro" } ← the plan this user pays for
153
- *
154
- * The session was signed in the whole time; `~/.claude/.credentials.json` holds
155
- * a valid `claudeAiOauth` entry naming `pro` (verified read-only). What was
156
- * missing was only that the shell exported `ANTHROPIC_API_KEY=he` — two
157
- * characters, the residue of a paste that lost its payload — so every `claude`
158
- * child this host spawned authenticated as "API key: he" instead of as the
159
- * subscription, and Claude Pro was unavailable in exactly the state a user is
160
- * most likely to be in: the shell where they once pasted a key.
161
- *
162
- * ── what it does NOT do ─────────────────────────────────────────────────────
163
- *
164
- * It does not strip a real key. The floor is `client/env-file.js`'s
165
- * `credentialLooksUsable` — the one place this repo decides "too short to be a
166
- * credential" — so a genuine `ANTHROPIC_API_KEY` keeps its precedence, because
167
- * a user who set one deliberately is asking for the pay-per-token path. Only a
168
- * value that provably cannot be a key is dropped, and the drop is REPORTED
169
- * rather than silent (see `envDroppedLine`).
170
- *
171
- * ── the second rule: a length floor is not a shape (measured, 2026-10-21) ───
172
- *
173
- * The floor above answers "is this too short to be anything?" and nothing more.
174
- * A 35-character value that is NOT an Anthropic console key clears it, still
175
- * wins the CLI's precedence, and still takes the plan down — so the floor alone
176
- * reproduced the original bug one paste later. Measured state that produced it:
177
- *
178
- * ~/.aegiscode/.env held ANTHROPIC_API_KEY=<35 chars, not sk-ant-*>
179
- * ~/.claude/.credentials.json held a valid `claudeAiOauth` for plan `pro`
180
- * `aegiscode -p "say hi" --json`
181
- * → {"text":"Invalid API key · Fix external API key","model":"sonnet",
182
- * "tokens":0,"balance_eur":1.54} exit 0, in 2.3 s
183
- *
184
- * and the child was spawned with the stale value present (`ANTHROPIC_LEN=35`,
185
- * observed by a fake `claude` on PATH). Unsetting the variable in the SHELL did
186
- * not help either: this host loads `~/.aegiscode/.env` into `process.env`
187
- * itself, so the file is an input no caller can undo.
188
- *
189
- * So when a subscription IS present, only a value shaped like an Anthropic
190
- * console key may shadow it. That is the narrowest rule that keeps the promise
191
- * the old comment made — "a user who set one deliberately is asking for the
192
- * pay-per-token path" — while refusing a value that provably is not one. With
193
- * no subscription there is nothing to shadow and no opinion is taken: any value
194
- * clearing the floor passes, exactly as before.
195
- *
196
- * @param {object} [baseEnv] the caller's env bag
197
- * @param {string} [token] a `CLAUDE_CODE_OAUTH_TOKEN` to hand the child
198
- * @param {{hasSubscription?: boolean}} [opts] whether a subscription is present
199
- * (see the second rule above); absent means "assume not", which keeps every
200
- * pre-existing caller and test on the old behaviour.
201
- * @returns {{env: object, dropped: Array<{name: string, length: number, reason: string}>}}
202
- */
203
- function childEnvPlan(baseEnv, token, opts) {
204
- const env = { ...(baseEnv || {}) };
205
- const dropped = [];
206
- const usable = envFileLib && typeof envFileLib.credentialLooksUsable === 'function'
207
- ? envFileLib.credentialLooksUsable
208
- : null;
209
- // Only a present subscription can be shadowed, so it is the only case that
210
- // earns the stricter shape rule (see the docstring's second section).
211
- const hasSubscription = !!(opts && opts.hasSubscription);
212
- // A host whose env module predates the floor keeps today's behaviour (the
213
- // variable passes through): a second copy of the floor here is the drift
214
- // client/env-file.js exists to prevent.
215
- if (usable) {
216
- for (const name of SHADOWING_ENV_VARS) {
217
- const value = env[name];
218
- if (typeof value !== 'string') continue;
219
- // Two independent reasons to refuse, and they are reported apart because
220
- // they mean different things to the user: too short is junk, while a
221
- // well-formed value that is not a console key is a key for something
222
- // else that would silently outrank the plan they are paying for.
223
- let reason = null;
224
- if (!usable(value)) reason = 'too-short';
225
- else if (hasSubscription && name === 'ANTHROPIC_API_KEY' && !isAnthropicConsoleKey(value)) {
226
- reason = 'not-a-console-key';
227
- }
228
- if (!reason) continue;
229
- delete env[name];
230
- // A variable set to '' shadows nothing worth reporting — it is removed
231
- // (harmless) but the user is not told about a value they never gave.
232
- const length = value.trim().length;
233
- if (length > 0) dropped.push({ name, length, reason });
234
- }
235
- }
236
- if (token) env.CLAUDE_CODE_OAUTH_TOKEN = token;
237
- return { env, dropped };
238
- }
239
-
240
- /** The one-line report for a child that started without a shadowing value. */
241
- function envDroppedLine(dropped) {
242
- const list = Array.isArray(dropped) ? dropped : [];
243
- if (!list.length) return null;
244
- const shaped = list.filter((d) => d && d.reason === 'not-a-console-key');
245
- const short = list.filter((d) => !d || d.reason !== 'not-a-console-key');
246
- const parts = [];
247
- if (short.length) {
248
- const names = short.map((d) => `${d.name} (${d.length} character${d.length === 1 ? '' : 's'})`).join(', ');
249
- parts.push(`${names}: too short to be a credential, and the CLI would have spent it instead of your subscription`);
250
- }
251
- if (shaped.length) {
252
- const names = shaped.map((d) => `${d.name} (${d.length} characters)`).join(', ');
253
- parts.push(
254
- `${names}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`
255
- );
256
- }
257
- return `aegis: not passed to the claude child — ${parts.join('; ')}`;
258
- }
259
-
260
- /**
261
- * The shadowing value in `env` that cannot be spent as the credential the CLI
262
- * would take it for, if any (see the two rules in `childEnvPlan`).
263
- *
264
- * This must agree with `childEnvPlan` exactly: a status surface that says "no
265
- * shadowing value" while the child is in fact being handed one is worse than no
266
- * report at all. Both reasons are therefore reported, and each carries the same
267
- * `reason` tag the drop report uses so the two lines cannot drift apart.
268
- *
269
- * @param {object} env
270
- * @param {{hasSubscription?: boolean}} [opts]
271
- * @returns {{name: string, length: number, reason: string}|null}
272
- */
273
- function shadowingValue(env, opts) {
274
- const bag = env || {};
275
- const usable = envFileLib && typeof envFileLib.credentialLooksUsable === 'function'
276
- ? envFileLib.credentialLooksUsable
277
- : null;
278
- if (!usable) return null;
279
- const hasSubscription = !!(opts && opts.hasSubscription);
280
- for (const name of SHADOWING_ENV_VARS) {
281
- const value = bag[name];
282
- if (typeof value !== 'string') continue;
283
- let reason = null;
284
- if (!usable(value)) reason = 'too-short';
285
- else if (hasSubscription && name === 'ANTHROPIC_API_KEY' && !isAnthropicConsoleKey(value)) {
286
- reason = 'not-a-console-key';
287
- }
288
- if (reason) return { name, length: value.trim().length, reason };
289
- }
290
- return null;
291
- }
292
-
293
- /**
294
- * Read Claude Code's credential file, without ever writing it.
295
- *
296
- * `kind` is 'oauth' (a `claudeAiOauth` entry — the Pro/Max subscription),
297
- * 'apikey', or 'env-token' (see below). `subscription` is the plan the file
298
- * itself names ('pro', 'max'), so the picker can say which subscription is
299
- * being spent instead of guessing from the token's shape.
300
- *
301
- * `loggedIn` is deliberately NOT `!expired`: access tokens are short-lived and
302
- * refreshed by the CLI on its next run, so a file holding a refresh token is a
303
- * working subscription even when the access token has lapsed. Only a file with
304
- * NO token at all is "not signed in" — anything stricter would tell a signed-in
305
- * user to sign in again.
306
- *
307
- * A file that genuinely has no usable token (never logged in, or a refresh
308
- * token that outright expired — the CLI's own `claude auth status` agrees in
309
- * that case, there is no stricter-than-the-CLI check being applied here) falls
310
- * back to `claudeOAuthToken()`: a `CLAUDE_CODE_OAUTH_TOKEN` the user has set
311
- * aside (shell export, `secrets.env`, or an unmigrated `.env` line) is handed
312
- * to the `claude` child directly by `runClaudePro`, and the CLI authenticates
313
- * with it regardless of what is on disk. Reporting "not logged in" while that
314
- * token would actually work is the gap this closes — the file is read-only
315
- * state, the token is a second, equally real way to be signed in.
316
- */
317
- function claudeProStatus(opts) {
318
- const o = opts || {};
319
- const env = o.env || process.env;
320
- const file = path.join(o.dir || claudeConfigDir(env), '.credentials.json');
321
- const out = {
322
- claude: o.claudeVersion || null,
323
- file,
324
- exists: false,
325
- kind: null,
326
- subscription: null,
327
- expiresAt: 0,
328
- loggedIn: false,
329
- };
330
- let data;
331
- try {
332
- data = JSON.parse(fs.readFileSync(file, 'utf8'));
333
- out.exists = true;
334
- } catch {
335
- data = null;
336
- }
337
- const oauth = data && data.claudeAiOauth;
338
- if (oauth && (oauth.accessToken || oauth.refreshToken)) {
339
- out.kind = 'oauth';
340
- out.subscription = oauth.subscriptionType || null;
341
- out.expiresAt = Number(oauth.refreshTokenExpiresAt) || 0;
342
- out.loggedIn = true;
343
- } else if (data && typeof data.token === 'string' && data.token) {
344
- out.kind = 'apikey';
345
- out.loggedIn = true;
346
- } else if (claudeOAuthToken(env)) {
347
- out.kind = 'env-token';
348
- out.loggedIn = true;
349
- }
350
- // A shadowing env var that cannot be a credential does NOT change `loggedIn`
351
- // — the subscription is there — but it is the one state where "signed in" and
352
- // "actually spends the plan" differ, because the CLI prefers that name. The
353
- // child is fixed regardless (childEnvPlan); this reports it so a status
354
- // surface can say why, rather than leaving `apiKeySource: ANTHROPIC_API_KEY`
355
- // to be discovered from `claude auth status` by hand.
356
- // A SUBSCRIPTION — the thing a stray `ANTHROPIC_API_KEY` would outrank — is an
357
- // `oauth` plan or a `CLAUDE_CODE_OAUTH_TOKEN` handed to the child. A
358
- // `credentials.json` holding a plain API key is not: there is no plan there to
359
- // shadow, so the strict shape rule must not fire and drop the user's own key.
360
- // This is computed once and published, so the report and the child env read
361
- // ONE answer instead of each deciding for itself.
362
- out.subscriptionPresent = out.loggedIn && out.kind !== 'apikey';
363
- // The stricter rule only applies when a subscription is present, so the
364
- // subscription this function just resolved is the same input the child env
365
- // gets. Passing it here is what keeps `shadowed` and the drop report agreeing.
366
- out.shadowed = shadowingValue(env, { hasSubscription: out.subscriptionPresent });
367
- // "Can this host serve a `pro` turn at all?" is NOT the same question as
368
- // "is there a subscription to shadow?" (above). A pin is phantom only when
369
- // nothing usable survives to the child, and a bare API key in
370
- // `credentials.json` (`kind: 'apikey'`) is a route with no plan behind it —
371
- // so `subscriptionPresent` excludes it deliberately, while callability must
372
- // count it. Answered by running the SAME planner the child env comes from, so
373
- // this cannot disagree with what `claude` is actually handed: a variable the
374
- // planner drops is not a credential, whatever it looks like in `env`.
375
- const plan = childEnvPlan(env, null, { hasSubscription: out.subscriptionPresent });
376
- out.credentialPresent = out.loggedIn
377
- || typeof plan.env.ANTHROPIC_API_KEY === 'string'
378
- || typeof plan.env.ANTHROPIC_AUTH_TOKEN === 'string'
379
- || typeof plan.env.CLAUDE_CODE_OAUTH_TOKEN === 'string';
380
- return out;
381
- }
382
-
383
- /**
384
- * Everything `claude --model` accepts on the installed CLI: its own aliases
385
- * PLUS the full model names, which `--model` resolves just as well ("Provide an
386
- * alias for the latest model … or a model's full name", `claude --help`).
387
- *
388
- * The list used to be the four aliases alone, so `pro` could not address the
389
- * rest of the Anthropic catalogue at all — a user on the subscription, holding
390
- * no console key, had no way to reach Sonnet 5.5 or Opus 4.6 from the picker.
391
- * Each row below was probed against the shipped binary (2.1.228) with the
392
- * ambient `ANTHROPIC_API_KEY` unset, and "accepted" means the id reached the
393
- * subscription (a credit/session-limit answer) rather than "is not a model this
394
- * version of Claude Code recognizes".
395
- *
396
- * Deliberately ABSENT, each for a measured reason — a row here is a promise the
397
- * transport can keep, so an id the child rejects must not be listed:
398
- *
399
- * - claude-sonnet-5, claude-opus-4-8, claude-fable-5, claude-haiku-4-5-*
400
- * are what `sonnet` / `opus` / `fable` / `haiku` already resolve to, so
401
- * listing them twice would put the same model on two rows.
402
- * - claude-opus-5-5 and claude-fable-5-1 ARE recognized, but this CLI
403
- * refuses them with "version 2.1.280 (resp. 2.1.251) or newer is required".
404
- * They start working on upgrade, not before, so they stay out until then.
405
- * - claude-haiku-5-5 / claude-fable-5-5 are unknown to this version — it
406
- * falls back to the bogus-model path, so they are not callable at all.
407
- * - claude-opus-4-1-20250805 is auto-remapped to Opus 5 by the CLI itself,
408
- * which makes it a second spelling of a row already here.
409
- */
410
- const PRO_MODELS = Object.freeze([
411
- { id: 'default', label: 'Default (recommended)', note: 'the CLI picks for the subscription' },
412
- { id: 'sonnet', label: 'Sonnet', note: 'alias the CLI resolves · latest Sonnet' },
413
- { id: 'opus', label: 'Opus', note: 'alias the CLI resolves · latest Opus' },
414
- { id: 'opusplan', label: 'Opus Plan', note: 'alias the CLI resolves · plan with Opus, act on Sonnet' },
415
- { id: 'haiku', label: 'Haiku', note: 'alias the CLI resolves · latest Haiku' },
416
- { id: 'fable', label: 'Fable', note: 'alias the CLI resolves · needs usage credits' },
417
- { id: 'claude-sonnet-5-5', label: 'Claude Sonnet 5.5', note: 'full name · Anthropic' },
418
- { id: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', note: 'full name · Anthropic' },
419
- { id: 'claude-sonnet-4-5-20250929', label: 'Claude Sonnet 4.5', note: 'full name · Anthropic · dated snapshot' },
420
- { id: 'claude-opus-5', label: 'Claude Opus 5', note: 'full name · Anthropic' },
421
- { id: 'claude-opus-4-7', label: 'Claude Opus 4.7', note: 'full name · Anthropic' },
422
- { id: 'claude-opus-4-6', label: 'Claude Opus 4.6', note: 'full name · Anthropic' },
423
- { id: 'claude-opus-4-5-20251101', label: 'Claude Opus 4.5', note: 'full name · Anthropic · dated snapshot' },
424
- ]);
425
-
426
- /**
427
- * The extra argv this class owns (what the child is told about the turn),
428
- * separate from the argv `one/src/child.js` owns (what the child is allowed to
429
- * do). Keeping the two apart is the point of rule 4: the permission half is
430
- * derived from the posture record, and this half is derived from the payload.
431
- *
432
- * NOTE: the session flags are NOT here even though they are "about the turn".
433
- * `--resume`/`--session-id` decide whether this turn is the same conversation
434
- * as the previous one — that is a policy about continuity, and it lives with
435
- * the other flags in the one argv builder, so a second spawn site cannot grow
436
- * its own opinion about it. `runClaudePro` passes `resumeSessionId`/
437
- * `sessionId` through the descriptor instead.
438
- */
439
- function turnArgs(payload) {
440
- const args = [];
441
- const p = payload || {};
442
- if (p.system && String(p.system).trim()) {
443
- args.push('--append-system-prompt', String(p.system));
444
- }
445
- return args;
446
- }
447
-
448
- // ---------------------------------------------------------------------------
449
- // The stream-json reader
450
- // ---------------------------------------------------------------------------
451
-
452
- /**
453
- * Line-oriented parser for `claude --output-format stream-json`. Pure: it feeds
454
- * callbacks and keeps only the tool bookkeeping between lines, so a test can
455
- * replay a captured transcript without spawning anything.
456
- *
457
- * Ported from ~/aegiscodex-dev src/backend.js createStreamParser(), which is
458
- * the reference implementation on this machine and carries the field names the
459
- * protocol actually uses. Two details there are load-bearing and are kept
460
- * verbatim:
461
- *
462
- * - `input_json_delta` fragments arrive routed BY BLOCK INDEX. Parallel
463
- * same-name tool calls interleave their argument JSON, and matching on
464
- * "the first collecting block" pairs a fragment with the wrong call.
465
- * - one `user` line can carry a tool_result for EVERY call in a parallel
466
- * round, so all of them are resolved, not just the first.
467
- *
468
- * `thinking_delta` is the third delta type and is NOT folded into `text`: an
469
- * extended-thinking block is deliberation, not the answer, so it goes out on
470
- * its own callback and its own accumulator. Dropping it entirely (which is what
471
- * this parser did) left BOTH channels empty for the whole thinking phase, which
472
- * is the longest stretch of a Pro turn — so the renderers' live meters, whose
473
- * only literal `0` is the "nothing received yet" branch, read `↓0 tokens` for
474
- * the entire time the turn was visibly working. Claude Code Pro runs extended
475
- * thinking by default, so this was the normal case, not an edge.
476
- */
477
- function createStreamParser(handlers) {
478
- const h = handlers || {};
479
- const tools = new Map(); // id -> {id, index, name, args, startedAt, phase}
480
- let text = '';
481
- let thinking = '';
482
- // Thinking progress the provider MEASURED, in tokens. On a real Pro turn
483
- // `thinking_delta.thinking` is the empty string and this is the only figure
484
- // the frame carries — see the `thinking_delta` branch below.
485
- let thinkingTokens = 0;
486
- let resultLine = null;
487
-
488
- const emitRun = (block) => {
489
- let args = block.args;
490
- try {
491
- args = block.args ? JSON.parse(block.args) : {};
492
- } catch {
493
- args = {};
494
- }
495
- tools.set(block.id, { ...block, args, phase: 'run' });
496
- if (h.onTool) h.onTool({ id: block.id, name: block.name, args, phase: 'run' });
497
- };
498
-
499
- const collecting = (index) =>
500
- [...tools.values()].find((t) => t.phase === 'collecting' && t.index === index) ||
501
- [...tools.values()].find((t) => t.phase === 'collecting');
502
-
503
- return {
504
- line(raw) {
505
- let j;
506
- try {
507
- j = JSON.parse(raw);
508
- } catch {
509
- return;
510
- }
511
-
512
- if (j.type === 'stream_event' && j.event) {
513
- const e = j.event;
514
- if (e.type === 'content_block_start' && e.content_block) {
515
- if (e.content_block.type === 'tool_use') {
516
- tools.set(e.content_block.id, {
517
- id: e.content_block.id,
518
- index: e.index == null ? 0 : e.index,
519
- name: e.content_block.name,
520
- args: '',
521
- startedAt: Date.now(),
522
- phase: 'collecting',
523
- });
524
- }
525
- } else if (e.type === 'content_block_delta' && e.delta) {
526
- if (e.delta.type === 'text_delta') {
527
- const t = (e.delta.text || '').replace(/\x00/g, '');
528
- text += t;
529
- if (h.onText && t) h.onText(t);
530
- } else if (e.delta.type === 'thinking_delta') {
531
- // Same `\x00` scrub as the visible text, for the same reason: a
532
- // NUL in the frame would otherwise be handed to a terminal.
533
- const t = (e.delta.thinking || '').replace(/\x00/g, '');
534
- thinking += t;
535
- if (h.onThinking && t) h.onThinking(t);
536
- // The figure that ACTUALLY moves on a subscription turn. Measured
537
- // against Claude Code 2.1.228: every real `thinking_delta` carries
538
- // `thinking: ""` with the deliberation withheld (the finished
539
- // block ships a 5.4 KB `signature` and no text), while
540
- // `estimated_tokens` advances in increments that sum to just under
541
- // the billed `usage.output_tokens_details.thinking_tokens`
542
- // (measured: 1900 vs 1943, 1800 vs 1832, 250 vs 339). So the text
543
- // channel is empty for the WHOLE thinking phase on a Pro turn and
544
- // the earlier `onThinking`-only fix never fired — the live meter
545
- // still read `↓0 tokens` while 4114 thinking tokens were billed
546
- // across three captured turns. Incremental, not cumulative: the
547
- // increments sum to the billed figure, so they are added as they
548
- // arrive rather than treated as a running total.
549
- const est = e.delta.estimated_tokens;
550
- if (typeof est === 'number' && est > 0 && Number.isFinite(est)) {
551
- thinkingTokens += est;
552
- if (h.onThinkingProgress) h.onThinkingProgress(est);
553
- }
554
- } else if (e.delta.type === 'input_json_delta') {
555
- const t = collecting(e.index == null ? 0 : e.index);
556
- if (t) t.args += e.delta.partial_json || '';
557
- }
558
- } else if (e.type === 'content_block_stop') {
559
- const t = collecting(e.index == null ? 0 : e.index);
560
- if (t) emitRun(t);
561
- }
562
- } else if (j.type === 'user' && j.message) {
563
- const content = Array.isArray(j.message.content) ? j.message.content : [];
564
- for (const tr of content) {
565
- if (!tr || tr.type !== 'tool_result' || !tr.tool_use_id) continue;
566
- const t = tools.get(tr.tool_use_id);
567
- if (!t) continue;
568
- const elapsed = Math.max(0, Date.now() - (t.startedAt || Date.now()));
569
- if (h.onTool) {
570
- h.onTool({ id: t.id, name: t.name, phase: 'done', elapsed, error: !!tr.is_error });
571
- }
572
- tools.delete(tr.tool_use_id);
573
- }
574
- } else if (j.type === 'result') {
575
- resultLine = j;
576
- if (h.onDone) {
577
- h.onDone({
578
- text: text || j.result || '',
579
- error: j.is_error ? j.result || 'api error' : undefined,
580
- usage: j.usage || null,
581
- costUsd: typeof j.total_cost_usd === 'number' ? j.total_cost_usd : undefined,
582
- durationMs: j.duration_ms,
583
- sessionId: j.session_id,
584
- // The deliberation this round DID produce, handed up so the engine
585
- // can tell a thinking-only round apart from a genuinely empty one.
586
- // On a real Pro turn the text is normally withheld and only the
587
- // billed token count is available, so `thinking` is often empty
588
- // even when the child thought — hence both fields, and the count.
589
- thinking: thinking || '',
590
- thinkingTokens,
591
- });
592
- }
593
- }
594
- // system / assistant / rate_limit_event lines carry no UI data.
595
- },
596
- get text() {
597
- return text;
598
- },
599
- get thinking() {
600
- return thinking;
601
- },
602
- // Thinking tokens the PROVIDER measured, not inferred from text — the only
603
- // honest way to meter a Pro turn, whose thinking text is withheld.
604
- get thinkingTokens() {
605
- return thinkingTokens;
606
- },
607
- get resultLine() {
608
- return resultLine;
609
- },
610
- };
611
- }
612
-
613
- /**
614
- * Resolve `one/src/child.js` and `one/src/permissions.js` in the two layouts the
615
- * repo uses, or throw naming the file. No fallback implementation: rule 4's
616
- * whole guarantee is that there is exactly ONE argv builder, so a local copy
617
- * here would be the drift the decision forbids.
618
- */
619
- function loadSeam(dir) {
620
- const here = dir || __dirname;
621
- const candidates = [
622
- // A checkout: desktop/lib/local → <repo>/one/src
623
- path.join(here, '..', '..', '..', 'one', 'src'),
624
- // A packaged desktop app: desktop/lib/local → desktop/vendor/one/src
625
- path.join(here, '..', '..', 'vendor', 'one', 'src'),
626
- // The published CLI's mirrored tree: cli/vendor/desktop/lib/local →
627
- // cli/vendor/one/src (the manifest stages one/src there under 'mirror').
628
- path.join(here, '..', '..', '..', '..', 'one', 'src'),
629
- ];
630
- for (const base of candidates) {
631
- try {
632
- const child = require(path.join(base, 'child.js'));
633
- const permissions = require(path.join(base, 'permissions.js'));
634
- if (typeof child.claudeArgv === 'function' && typeof permissions.resolvePosture === 'function') {
635
- return { child, permissions };
636
- }
637
- } catch {
638
- /* try the next layout */
639
- }
640
- }
641
- throw new Error(
642
- 'aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing ' +
643
- 'from this install — refusing to build a second argv, because a second argv is a second policy.'
644
- );
645
- }
646
-
647
- /** Whether the argv seam resolves here, without throwing. For status panels. */
648
- function seamAvailable(dir) {
649
- try {
650
- loadSeam(dir);
651
- return { ok: true, error: null };
652
- } catch (e) {
653
- return { ok: false, error: (e && e.message) || String(e) };
654
- }
655
- }
656
-
657
- /**
658
- * The `choices[0].message` a Pro turn reports.
659
- *
660
- * `content` is the child's own final answer, as before. The addition is the
661
- * deliberation, carried on the shape the engine already reads: `reasoning_content`
662
- * is what `engine.js` `reasoningTextOf()` looks for first, so a Pro round that
663
- * spent its output thinking is now visible as exactly that.
664
- *
665
- * This matters because of how a Pro turn fails. When extended thinking is on —
666
- * which is Claude Code's default — the child can finish a round having produced
667
- * deliberation and no answer, and the engine's recovery ladder decides what to
668
- * do next by asking `reasonedButSilent(res)`, i.e. "was this round empty, or did
669
- * it think and stay silent?". Before this field existed, a Pro result never
670
- * carried reasoning at all, so that question always answered "genuinely empty"
671
- * and the ladder burned its rounds on the generic nudge — the ask that invites
672
- * the same silent thinking pass a second time. Worse, `emptyTurnError` reported
673
- * it as "No visible text came back from any of those calls", which is the wrong
674
- * diagnosis: the model was not silent, it was thinking.
675
- *
676
- * `thinking_tokens` rides alongside as the provider's own billed count. On a
677
- * real Pro turn the deliberation TEXT is withheld — measured across three turns,
678
- * every `thinking_delta` carried `thinking: ""` while thousands of tokens were
679
- * billed — so a text-only signal would still miss the case this exists for. The
680
- * count is the honest figure, and it is the only one that arrives.
681
- */
682
- function proMessage(text, thinking, thinkingTokens) {
683
- const msg = { content: text || '' };
684
- const deliberation = typeof thinking === 'string' ? thinking : '';
685
- if (deliberation) msg.reasoning_content = deliberation;
686
- if (typeof thinkingTokens === 'number' && thinkingTokens > 0 && Number.isFinite(thinkingTokens)) {
687
- msg.thinking_tokens = thinkingTokens;
688
- }
689
- return msg;
690
- }
691
-
692
- /**
693
- * Run one turn on the user's Claude Code subscription.
694
- *
695
- * Returns the SAME shape the other three transports return, because the engine
696
- * loop reads one shape (`choices[0].message.content`, `usage`, `stop_reason`) —
697
- * `extractToolCalls`, `assistantText`, `finishReasonOf` and `addUsage` all read
698
- * it. Returns NO tool_calls, and that is the design rather than an omission:
699
- * the `claude` child runs its own agent loop with its own tools, so the work is
700
- * already done by the time this resolves. Emitting tool_calls as well would
701
- * hand a second, parallel loop the same task and run every tool twice.
702
- *
703
- * @param {object} opts
704
- * @param {string} opts.prompt
705
- * @param {string} [opts.model] a `claude --model` alias (PRO_MODELS)
706
- * @param {string} [opts.system] appended to the child's own prompt
707
- * @param {string} [opts.cwd] the directory the child works in
708
- * @param {string[]} [opts.addDir] extra directories the child may work in.
709
- * The child resolves every relative path
710
- * and every tool's root against `cwd`
711
- * alone, so a turn started in a
712
- * subdirectory cannot see the tree above
713
- * it; this is what widens that. Spelled
714
- * by the ONE argv builder (one/src/child.js
715
- * addDirArgs), never typed here.
716
- * @param {object} [opts.rules] CLI permission rules (cli/src/config.js)
717
- * @param {boolean} [opts.gate] the stored /confirm posture, if known
718
- * @param {string} [opts.permissionMode] explicit passthrough, validated in child.js
719
- * @param {string} [opts.resumeSessionId] reattach to the session a prior turn
720
- * reported → the turn keeps its context
721
- * @param {string} [opts.sessionId] name a NEW session (UUID) for a first turn
722
- * @param {AbortSignal} [opts.signal]
723
- * @param {Function} [opts.onSpawn] receives the child the moment it exists
724
- * @param {number} [opts.idleTimeoutMs] silence budget (default 10 min)
725
- * @returns {Promise<object>} an engine-shaped completion
726
- */
727
- function runClaudePro(opts, deps) {
728
- const o = opts || {};
729
- const d = deps || {};
730
- const seam = d.seam || loadSeam(d.dir);
731
- const spawnFn = d.spawn || require('node:child_process').spawn;
732
-
733
- // One posture per turn, from the single resolver — never re-derived here.
734
- const posture = seam.permissions.resolvePosture({
735
- rules: o.rules,
736
- gate: o.gate,
737
- interactive: false,
738
- childKind: seam.permissions.CHILD_KINDS.HEADLESS,
739
- env: o.env || process.env,
740
- });
741
-
742
- const built = seam.child.claudeArgv({
743
- posture,
744
- prompt: o.prompt,
745
- model: o.model || undefined,
746
- permissionMode: o.permissionMode,
747
- // Continuity, handed to the ONE argv builder rather than typed as `extra`.
748
- // Without these the child starts a brand-new conversation every turn: the
749
- // engine does not replay the transcript into it (`pro` runs its own agent
750
- // loop), so the CLI's own session store is the ONLY thing that can carry
751
- // context across turns. `resumeSessionId` reattaches to the session a
752
- // previous turn reported; `sessionId` names a new one for a later resume.
753
- resumeSessionId: o.resumeSessionId,
754
- sessionId: o.sessionId,
755
- // The widened sandbox for this turn, if the caller asked for one. It rides
756
- // the descriptor rather than `extra` because `--add-dir` is variadic and its
757
- // correct spelling is a decision (child.js addDirArgs), not a flag a caller
758
- // may type.
759
- addDir: o.addDir,
760
- // `--include-partial-messages` is what makes `stream_event` lines arrive at
761
- // all, and `--verbose` is required by the CLI alongside stream-json in print
762
- // mode. Both belong to the transport (this file), not to the posture.
763
- extra: [...turnArgs(o), '--include-partial-messages', '--verbose'],
764
- });
765
-
766
- return new Promise((resolve) => {
767
- if (o.signal && o.signal.aborted) {
768
- resolve({ choices: [{ message: { content: '' }, finish_reason: 'stop' }], stopped: true });
769
- return;
770
- }
771
-
772
- // `CLAUDE_CODE_OAUTH_TOKEN` is merged into the CHILD's env only — never
773
- // written back to `o.env`/`process.env` — so a token the on-disk
774
- // credential file lacks (or has let expire) still reaches the one process
775
- // that can spend it, without making the value ambient to this host or any
776
- // other child it spawns. See claudeOAuthToken() for where it comes from.
777
- //
778
- // `childEnvPlan` additionally refuses to hand over a shadowing var that
779
- // cannot be a credential. Without it a signed-in machine runs the child as
780
- // "API key: he" and the subscription is unreachable — see childEnvPlan.
781
- const baseEnv = o.env || process.env;
782
- const token = claudeOAuthToken(baseEnv);
783
- // Whether a subscription is present decides whether a non-console
784
- // `ANTHROPIC_API_KEY` may shadow it (childEnvPlan's second rule). It is read
785
- // from the same credential file `claudeProStatus` reports on, and a failure
786
- // to read it must NOT weaken the child's env: an unreadable file means "no
787
- // subscription proven", which is the old behaviour, not a crash mid-turn.
788
- let hasSubscription = false;
789
- try {
790
- hasSubscription = !!claudeProStatus({ env: baseEnv }).subscriptionPresent;
791
- } catch {
792
- /* unprovable subscription → the floor-only rule, exactly as before */
793
- }
794
- const plan = childEnvPlan(baseEnv, token, { hasSubscription });
795
- const childEnv = plan.env;
796
- const droppedLine = envDroppedLine(plan.dropped);
797
- if (droppedLine && o.onDelta) {
798
- // Same channel the transcript already paints notes on, and emitted BEFORE
799
- // the spawn so the line lands above the child's own tool rows.
800
- try {
801
- o.onDelta({ delta: '', note: droppedLine });
802
- } catch {
803
- /* a throwing renderer must not take the turn down */
804
- }
805
- }
806
-
807
- let child;
808
- try {
809
- child = spawnFn(d.executable || 'claude', built.argv, {
810
- cwd: o.cwd || process.cwd(),
811
- stdio: ['ignore', 'pipe', 'pipe'],
812
- env: childEnv,
813
- });
814
- } catch (e) {
815
- resolve({
816
- choices: [{ message: { content: '' }, finish_reason: 'error' }],
817
- error: `claude: could not start the child (${(e && e.message) || e})`,
818
- ...(plan.dropped.length ? { envDropped: plan.dropped } : {}),
819
- });
820
- return;
821
- }
822
-
823
- if (o.onSpawn) {
824
- try {
825
- o.onSpawn(child, built.record);
826
- } catch {
827
- /* a throwing hook must not take the turn down */
828
- }
829
- }
830
-
831
- let finished = false;
832
- let stderr = '';
833
- let buffer = '';
834
- let idle = null;
835
- const idleMs = Number(o.idleTimeoutMs) || 10 * 60 * 1000;
836
-
837
- const settle = (result) => {
838
- if (finished) return;
839
- finished = true;
840
- if (idle) clearTimeout(idle);
841
- if (o.signal) o.signal.removeEventListener('abort', kill);
842
- // Recorded on every settle path, the same way `childRecord` is: what the
843
- // child was NOT given is part of what this turn did, and a caller logging
844
- // only the argv would show a turn that "should" have failed as a mystery.
845
- resolve(plan.dropped.length ? { ...result, envDropped: plan.dropped } : result);
846
- };
847
-
848
- const kill = () => {
849
- try {
850
- child.kill('SIGTERM');
851
- } catch {
852
- /* already gone */
853
- }
854
- setTimeout(() => {
855
- try {
856
- child.kill('SIGKILL');
857
- } catch {
858
- /* already gone */
859
- }
860
- }, 1500);
861
- };
862
- if (o.signal) o.signal.addEventListener('abort', kill, { once: true });
863
-
864
- // Idle watchdog, not a flat turn cap: it resets on every byte, so it fires
865
- // only on true silence — which is what a lapsed OAuth session looks like
866
- // when the child opens a re-auth prompt nobody on this side can answer.
867
- const armIdle = () => {
868
- if (idle) clearTimeout(idle);
869
- idle = setTimeout(() => {
870
- kill();
871
- settle({
872
- choices: [{ message: { content: '' }, finish_reason: 'stop' }],
873
- error: `claude: the child went silent for ${Math.round(idleMs / 1000)}s and was stopped`,
874
- });
875
- }, idleMs);
876
- };
877
- armIdle();
878
-
879
- const parser = createStreamParser({
880
- onText: (t) => {
881
- armIdle();
882
- if (o.onDelta) o.onDelta({ delta: t });
883
- },
884
- // Extended thinking, forwarded on the SAME channel the engine's pooled
885
- // brain path already uses for a worker's deliberation (`onReasoning`,
886
- // engine.js — `onDelta({ reasoning })`). Both renderers already consume
887
- // that field, so the live token meter counts the thinking phase on a Pro
888
- // turn exactly as it does everywhere else, with no consumer-side edit.
889
- // `engine.js` hands `runClaudePro` the RAW `opts.onDelta` (not the wrapped
890
- // `onReasoning`), so this transport is the one that must emit the field.
891
- onThinking: (t) => {
892
- armIdle();
893
- if (o.onDelta) o.onDelta({ reasoning: t });
894
- },
895
- // The channel that actually fires on a Pro turn. `onThinking` above is
896
- // kept for any provider that does stream deliberation text, but Claude
897
- // Code withholds it: measured across three real turns, every
898
- // `thinking_delta` carried `thinking: ""`, so `onThinking` never fired
899
- // once while 4114 thinking tokens were billed. This carries the
900
- // provider's own MEASURED count, on a numeric channel of its own rather
901
- // than the text one — the consumers turn `reasoning` text into tokens at
902
- // 4 chars:1 token, so a token count sent down that path would be divided
903
- // by four and read as a quarter of the truth.
904
- onThinkingProgress: (est) => {
905
- armIdle();
906
- if (o.onDelta) o.onDelta({ thinkingTokens: est });
907
- },
908
- onTool: (info) => {
909
- armIdle();
910
- if (!o.onDelta) return;
911
- // Same tool frame the engine's own loop emits, so the renderers paint a
912
- // subscription turn's tool rows with no second code path.
913
- o.onDelta({
914
- delta: '',
915
- tool: {
916
- name: info.name,
917
- args: info.args,
918
- ok: info.phase === 'done' ? !info.error : undefined,
919
- id: info.id,
920
- cwd: o.cwd,
921
- phase: info.phase,
922
- },
923
- });
924
- },
925
- onDone: (r) => {
926
- if (r.error) {
927
- settle({
928
- choices: [{ message: { content: r.text || '' }, finish_reason: 'error' }],
929
- usage: r.usage || undefined,
930
- error: r.error,
931
- });
932
- return;
933
- }
934
- settle({
935
- choices: [{ message: proMessage(r.text || '', r.thinking, r.thinkingTokens), finish_reason: 'stop' }],
936
- usage: r.usage || undefined,
937
- costUsd: r.costUsd,
938
- durationMs: r.durationMs,
939
- sessionId: r.sessionId,
940
- // Carried so a caller can log WHICH flags the child actually got —
941
- // rule 4's "recorded, never inferred".
942
- childRecord: built.record,
943
- });
944
- },
945
- });
946
-
947
- child.stdout.on('data', (chunk) => {
948
- armIdle();
949
- buffer += chunk.toString('utf8');
950
- const lines = buffer.split('\n');
951
- buffer = lines.pop() || '';
952
- for (const line of lines) {
953
- const t = line.trim();
954
- if (t) parser.line(t);
955
- }
956
- });
957
- child.stderr.on('data', (chunk) => {
958
- armIdle();
959
- if (stderr.length < 8192) stderr += chunk.toString('utf8');
960
- });
961
-
962
- child.on('error', (e) => {
963
- settle({
964
- choices: [{ message: { content: '' }, finish_reason: 'error' }],
965
- error:
966
- `claude: could not run the child (${(e && e.message) || e}). ` +
967
- 'Install it with `npm i -g @anthropic-ai/claude-code`, then sign in with `claude auth login`.',
968
- });
969
- });
970
-
971
- child.on('close', (code) => {
972
- if (buffer.trim()) parser.line(buffer.trim());
973
- // Only reached when no `result` line arrived — a clean exit always emits
974
- // one. Anything else is a real failure and is reported as one rather than
975
- // as an empty successful answer.
976
- settle({
977
- choices: [
978
- {
979
- message: proMessage(parser.text, parser.thinking, parser.thinkingTokens),
980
- finish_reason: 'stop',
981
- },
982
- ],
983
- usage: (parser.resultLine && parser.resultLine.usage) || undefined,
984
- childRecord: built.record,
985
- error:
986
- parser.text || code === 0
987
- ? undefined
988
- : `claude: the child exited with status ${code}${
989
- stderr.trim() ? ` — ${stderr.trim().split('\n').slice(-3).join(' ')}` : ''
990
- }`,
991
- });
992
- });
993
- });
994
- }
995
-
996
- /**
997
- * The run-log line for a child argv, from the seam that owns the wording. A
998
- * missing seam degrades to a short local summary rather than throwing — this is
999
- * a reporting path, and a turn that already ran must not fail to describe
1000
- * itself.
1001
- */
1002
- function childLine(record, dir) {
1003
- if (!record) return '';
1004
- try {
1005
- return loadSeam(dir).child.childRecordLine(record);
1006
- } catch {
1007
- const flag = record.skipFlag || 'no permission flag';
1008
- return `aegis: claude child [${record.kind}] ${flag}`;
1009
- }
1010
- }
1011
-
1012
- module.exports = {
1013
- claudeConfigDir,
1014
- claudeOAuthToken,
1015
- claudeProStatus,
1016
- // The child-env half of "the subscription actually gets spent": the plan for
1017
- // what the `claude` child is given (and what a shadowing value cost), the
1018
- // one-line report of it, and the inspector `claudeProStatus` reports.
1019
- childEnvPlan,
1020
- envDroppedLine,
1021
- shadowingValue,
1022
- SHADOWING_ENV_VARS,
1023
- PRO_MODELS,
1024
- turnArgs,
1025
- createStreamParser,
1026
- loadSeam,
1027
- seamAvailable,
1028
- childLine,
1029
- runClaudePro,
1030
- };
3
+ const e=require("node:fs"),n=require("node:os"),t=require("node:path");let o=null;try{o=require("../../../client/env-file.js")}catch{try{o=require("../../vendor/env-file.js")}catch{o=null}}function s(e){const o=e||process.env,s=o&&o.CLAUDE_CONFIG_DIR;return s&&String(s).trim()?String(s).trim():t.join(n.homedir(),".claude")}function i(e){return o?o.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const r=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function l(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function a(e,n,t){const s={...e||{}},i=[],a=o&&"function"==typeof o.credentialLooksUsable?o.credentialLooksUsable:null,c=!(!t||!t.hasSubscription);if(a)for(const e of r){const n=s[e];if("string"!=typeof n)continue;let t=null;if(a(n)?c&&"ANTHROPIC_API_KEY"===e&&!l(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const o=n.trim().length;o>0&&i.push({name:e,length:o,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:i}}function c(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),o=n.filter((e=>!e||"not-a-console-key"!==e.reason)),s=[];if(o.length){const e=o.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");s.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");s.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${s.join("; ")}`}function d(e,n){const t=e||{},s=o&&"function"==typeof o.credentialLooksUsable?o.credentialLooksUsable:null;if(!s)return null;const i=!(!n||!n.hasSubscription);for(const e of r){const n=t[e];if("string"!=typeof n)continue;let o=null;if(s(n)?i&&"ANTHROPIC_API_KEY"===e&&!l(n)&&(o="not-a-console-key"):o="too-short",o)return{name:e,length:n.trim().length,reason:o}}return null}function u(n){const o=n||{},r=o.env||process.env,l=t.join(o.dir||s(r),".credentials.json"),c={claude:o.claudeVersion||null,file:l,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let u;try{u=JSON.parse(e.readFileSync(l,"utf8")),c.exists=!0}catch{u=null}const p=u&&u.claudeAiOauth;p&&(p.accessToken||p.refreshToken)?(c.kind="oauth",c.subscription=p.subscriptionType||null,c.expiresAt=Number(p.refreshTokenExpiresAt)||0,c.loggedIn=!0):u&&"string"==typeof u.token&&u.token?(c.kind="apikey",c.loggedIn=!0):i(r)&&(c.kind="env-token",c.loggedIn=!0),c.subscriptionPresent=c.loggedIn&&"apikey"!==c.kind,c.shadowed=d(r,{hasSubscription:c.subscriptionPresent});const h=a(r,null,{hasSubscription:c.subscriptionPresent});return c.credentialPresent=c.loggedIn||"string"==typeof h.env.ANTHROPIC_API_KEY||"string"==typeof h.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof h.env.CLAUDE_CODE_OAUTH_TOKEN,c}const p=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function h(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function g(e){const n=e||{},t=new Map;let o="",s="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");o+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");s+=t,n.onThinking&&t&&n.onThinking(t);const o=e.delta.estimated_tokens;"number"==typeof o&&o>0&&Number.isFinite(o)&&(i+=o,n.onThinkingProgress&&n.onThinkingProgress(o))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const o=a(null==e.index?0:e.index);o&&(e=>{let o=e.args;try{o=e.args?JSON.parse(e.args):{}}catch{o={}}t.set(e.id,{...e,args:o,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:o,phase:"run"})})(o)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const o of e){if(!o||"tool_result"!==o.type||!o.tool_use_id)continue;const e=t.get(o.tool_use_id);if(!e)continue;const s=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:s,error:!!o.is_error}),t.delete(o.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:o||l.result||"",error:l.is_error?l.result||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:s||"",thinkingTokens:i}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return i},get resultLine(){return r}}}function f(e){const n=e||__dirname,o=[t.join(n,"..","..","..","one","src"),t.join(n,"..","..","vendor","one","src"),t.join(n,"..","..","..","..","one","src")];for(const e of o)try{const n=require(t.join(e,"child.js")),o=require(t.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof o.resolvePosture)return{child:n,permissions:o}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function m(e,n,t){const o={content:e||""},s="string"==typeof n?n:"";return s&&(o.reasoning_content=s),"number"==typeof t&&t>0&&Number.isFinite(t)&&(o.thinking_tokens=t),o}module.exports={claudeConfigDir:s,claudeOAuthToken:i,claudeProStatus:u,childEnvPlan:a,envDroppedLine:c,shadowingValue:d,SHADOWING_ENV_VARS:r,PRO_MODELS:p,turnArgs:h,createStreamParser:g,loadSeam:f,seamAvailable:function(e){try{return f(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}},childLine:function(e,n){if(!e)return"";try{return f(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}},runClaudePro:function(e,n){const t=e||{},o=n||{},s=o.seam||f(o.dir),r=o.spawn||require("node:child_process").spawn,l=s.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:s.permissions.CHILD_KINDS.HEADLESS,env:t.env||process.env}),d=s.child.claudeArgv({posture:l,prompt:t.prompt,model:t.model||void 0,permissionMode:t.permissionMode,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,extra:[...h(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,s=i(n);let l=!1;try{l=!!u({env:n}).subscriptionPresent}catch{}const p=a(n,s,{hasSubscription:l}),h=p.env,f=c(p.dropped);if(f&&t.onDelta)try{t.onDelta({delta:"",note:f})}catch{}let _;try{_=r(o.executable||"claude",d.argv,{cwd:t.cwd||process.cwd(),stdio:["ignore","pipe","pipe"],env:h})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...p.dropped.length?{envDropped:p.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(_,d.record)}catch{}let k=!1,v="",b="",y=null;const A=Number(t.idleTimeoutMs)||6e5,T=n=>{k||(k=!0,y&&clearTimeout(y),t.signal&&t.signal.removeEventListener("abort",I),e(p.dropped.length?{...n,envDropped:p.dropped}:n))},I=()=>{try{_.kill("SIGTERM")}catch{}setTimeout((()=>{try{_.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",I,{once:!0});const S=()=>{y&&clearTimeout(y),y=setTimeout((()=>{I(),T({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(A/1e3)}s and was stopped`})}),A)};S();const D=g({onText:e=>{S(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{S(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{S(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{S(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onDone:e=>{e.error?T({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error}):T({choices:[{message:m(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:d.record})}});_.stdout.on("data",(e=>{S(),b+=e.toString("utf8");const n=b.split("\n");b=n.pop()||"";for(const e of n){const n=e.trim();n&&D.line(n)}})),_.stderr.on("data",(e=>{S(),v.length<8192&&(v+=e.toString("utf8"))})),_.on("error",(e=>{T({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),_.on("close",(e=>{b.trim()&&D.line(b.trim()),T({choices:[{message:m(D.text,D.thinking,D.thinkingTokens),finish_reason:"stop"}],usage:D.resultLine&&D.resultLine.usage||void 0,childRecord:d.record,error:D.text||0===e?void 0:`claude: the child exited with status ${e}${v.trim()?` — ${v.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}};