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,995 +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
- /** The model aliases the `claude` CLI itself accepts (`claude --model <alias>`). */
384
- const PRO_MODELS = Object.freeze([
385
- { id: 'default', label: 'Default (recommended)', note: 'the CLI picks for the subscription' },
386
- { id: 'sonnet', label: 'Sonnet', note: 'alias the CLI resolves' },
387
- { id: 'opus', label: 'Opus', note: 'alias the CLI resolves' },
388
- { id: 'haiku', label: 'Haiku', note: 'alias the CLI resolves' },
389
- ]);
390
-
391
- /**
392
- * The extra argv this class owns (what the child is told about the turn),
393
- * separate from the argv `one/src/child.js` owns (what the child is allowed to
394
- * do). Keeping the two apart is the point of rule 4: the permission half is
395
- * derived from the posture record, and this half is derived from the payload.
396
- *
397
- * NOTE: the session flags are NOT here even though they are "about the turn".
398
- * `--resume`/`--session-id` decide whether this turn is the same conversation
399
- * as the previous one — that is a policy about continuity, and it lives with
400
- * the other flags in the one argv builder, so a second spawn site cannot grow
401
- * its own opinion about it. `runClaudePro` passes `resumeSessionId`/
402
- * `sessionId` through the descriptor instead.
403
- */
404
- function turnArgs(payload) {
405
- const args = [];
406
- const p = payload || {};
407
- if (p.system && String(p.system).trim()) {
408
- args.push('--append-system-prompt', String(p.system));
409
- }
410
- return args;
411
- }
412
-
413
- // ---------------------------------------------------------------------------
414
- // The stream-json reader
415
- // ---------------------------------------------------------------------------
416
-
417
- /**
418
- * Line-oriented parser for `claude --output-format stream-json`. Pure: it feeds
419
- * callbacks and keeps only the tool bookkeeping between lines, so a test can
420
- * replay a captured transcript without spawning anything.
421
- *
422
- * Ported from ~/aegiscodex-dev src/backend.js createStreamParser(), which is
423
- * the reference implementation on this machine and carries the field names the
424
- * protocol actually uses. Two details there are load-bearing and are kept
425
- * verbatim:
426
- *
427
- * - `input_json_delta` fragments arrive routed BY BLOCK INDEX. Parallel
428
- * same-name tool calls interleave their argument JSON, and matching on
429
- * "the first collecting block" pairs a fragment with the wrong call.
430
- * - one `user` line can carry a tool_result for EVERY call in a parallel
431
- * round, so all of them are resolved, not just the first.
432
- *
433
- * `thinking_delta` is the third delta type and is NOT folded into `text`: an
434
- * extended-thinking block is deliberation, not the answer, so it goes out on
435
- * its own callback and its own accumulator. Dropping it entirely (which is what
436
- * this parser did) left BOTH channels empty for the whole thinking phase, which
437
- * is the longest stretch of a Pro turn — so the renderers' live meters, whose
438
- * only literal `0` is the "nothing received yet" branch, read `↓0 tokens` for
439
- * the entire time the turn was visibly working. Claude Code Pro runs extended
440
- * thinking by default, so this was the normal case, not an edge.
441
- */
442
- function createStreamParser(handlers) {
443
- const h = handlers || {};
444
- const tools = new Map(); // id -> {id, index, name, args, startedAt, phase}
445
- let text = '';
446
- let thinking = '';
447
- // Thinking progress the provider MEASURED, in tokens. On a real Pro turn
448
- // `thinking_delta.thinking` is the empty string and this is the only figure
449
- // the frame carries — see the `thinking_delta` branch below.
450
- let thinkingTokens = 0;
451
- let resultLine = null;
452
-
453
- const emitRun = (block) => {
454
- let args = block.args;
455
- try {
456
- args = block.args ? JSON.parse(block.args) : {};
457
- } catch {
458
- args = {};
459
- }
460
- tools.set(block.id, { ...block, args, phase: 'run' });
461
- if (h.onTool) h.onTool({ id: block.id, name: block.name, args, phase: 'run' });
462
- };
463
-
464
- const collecting = (index) =>
465
- [...tools.values()].find((t) => t.phase === 'collecting' && t.index === index) ||
466
- [...tools.values()].find((t) => t.phase === 'collecting');
467
-
468
- return {
469
- line(raw) {
470
- let j;
471
- try {
472
- j = JSON.parse(raw);
473
- } catch {
474
- return;
475
- }
476
-
477
- if (j.type === 'stream_event' && j.event) {
478
- const e = j.event;
479
- if (e.type === 'content_block_start' && e.content_block) {
480
- if (e.content_block.type === 'tool_use') {
481
- tools.set(e.content_block.id, {
482
- id: e.content_block.id,
483
- index: e.index == null ? 0 : e.index,
484
- name: e.content_block.name,
485
- args: '',
486
- startedAt: Date.now(),
487
- phase: 'collecting',
488
- });
489
- }
490
- } else if (e.type === 'content_block_delta' && e.delta) {
491
- if (e.delta.type === 'text_delta') {
492
- const t = (e.delta.text || '').replace(/\x00/g, '');
493
- text += t;
494
- if (h.onText && t) h.onText(t);
495
- } else if (e.delta.type === 'thinking_delta') {
496
- // Same `\x00` scrub as the visible text, for the same reason: a
497
- // NUL in the frame would otherwise be handed to a terminal.
498
- const t = (e.delta.thinking || '').replace(/\x00/g, '');
499
- thinking += t;
500
- if (h.onThinking && t) h.onThinking(t);
501
- // The figure that ACTUALLY moves on a subscription turn. Measured
502
- // against Claude Code 2.1.228: every real `thinking_delta` carries
503
- // `thinking: ""` with the deliberation withheld (the finished
504
- // block ships a 5.4 KB `signature` and no text), while
505
- // `estimated_tokens` advances in increments that sum to just under
506
- // the billed `usage.output_tokens_details.thinking_tokens`
507
- // (measured: 1900 vs 1943, 1800 vs 1832, 250 vs 339). So the text
508
- // channel is empty for the WHOLE thinking phase on a Pro turn and
509
- // the earlier `onThinking`-only fix never fired — the live meter
510
- // still read `↓0 tokens` while 4114 thinking tokens were billed
511
- // across three captured turns. Incremental, not cumulative: the
512
- // increments sum to the billed figure, so they are added as they
513
- // arrive rather than treated as a running total.
514
- const est = e.delta.estimated_tokens;
515
- if (typeof est === 'number' && est > 0 && Number.isFinite(est)) {
516
- thinkingTokens += est;
517
- if (h.onThinkingProgress) h.onThinkingProgress(est);
518
- }
519
- } else if (e.delta.type === 'input_json_delta') {
520
- const t = collecting(e.index == null ? 0 : e.index);
521
- if (t) t.args += e.delta.partial_json || '';
522
- }
523
- } else if (e.type === 'content_block_stop') {
524
- const t = collecting(e.index == null ? 0 : e.index);
525
- if (t) emitRun(t);
526
- }
527
- } else if (j.type === 'user' && j.message) {
528
- const content = Array.isArray(j.message.content) ? j.message.content : [];
529
- for (const tr of content) {
530
- if (!tr || tr.type !== 'tool_result' || !tr.tool_use_id) continue;
531
- const t = tools.get(tr.tool_use_id);
532
- if (!t) continue;
533
- const elapsed = Math.max(0, Date.now() - (t.startedAt || Date.now()));
534
- if (h.onTool) {
535
- h.onTool({ id: t.id, name: t.name, phase: 'done', elapsed, error: !!tr.is_error });
536
- }
537
- tools.delete(tr.tool_use_id);
538
- }
539
- } else if (j.type === 'result') {
540
- resultLine = j;
541
- if (h.onDone) {
542
- h.onDone({
543
- text: text || j.result || '',
544
- error: j.is_error ? j.result || 'api error' : undefined,
545
- usage: j.usage || null,
546
- costUsd: typeof j.total_cost_usd === 'number' ? j.total_cost_usd : undefined,
547
- durationMs: j.duration_ms,
548
- sessionId: j.session_id,
549
- // The deliberation this round DID produce, handed up so the engine
550
- // can tell a thinking-only round apart from a genuinely empty one.
551
- // On a real Pro turn the text is normally withheld and only the
552
- // billed token count is available, so `thinking` is often empty
553
- // even when the child thought — hence both fields, and the count.
554
- thinking: thinking || '',
555
- thinkingTokens,
556
- });
557
- }
558
- }
559
- // system / assistant / rate_limit_event lines carry no UI data.
560
- },
561
- get text() {
562
- return text;
563
- },
564
- get thinking() {
565
- return thinking;
566
- },
567
- // Thinking tokens the PROVIDER measured, not inferred from text — the only
568
- // honest way to meter a Pro turn, whose thinking text is withheld.
569
- get thinkingTokens() {
570
- return thinkingTokens;
571
- },
572
- get resultLine() {
573
- return resultLine;
574
- },
575
- };
576
- }
577
-
578
- /**
579
- * Resolve `one/src/child.js` and `one/src/permissions.js` in the two layouts the
580
- * repo uses, or throw naming the file. No fallback implementation: rule 4's
581
- * whole guarantee is that there is exactly ONE argv builder, so a local copy
582
- * here would be the drift the decision forbids.
583
- */
584
- function loadSeam(dir) {
585
- const here = dir || __dirname;
586
- const candidates = [
587
- // A checkout: desktop/lib/local → <repo>/one/src
588
- path.join(here, '..', '..', '..', 'one', 'src'),
589
- // A packaged desktop app: desktop/lib/local → desktop/vendor/one/src
590
- path.join(here, '..', '..', 'vendor', 'one', 'src'),
591
- // The published CLI's mirrored tree: cli/vendor/desktop/lib/local →
592
- // cli/vendor/one/src (the manifest stages one/src there under 'mirror').
593
- path.join(here, '..', '..', '..', '..', 'one', 'src'),
594
- ];
595
- for (const base of candidates) {
596
- try {
597
- const child = require(path.join(base, 'child.js'));
598
- const permissions = require(path.join(base, 'permissions.js'));
599
- if (typeof child.claudeArgv === 'function' && typeof permissions.resolvePosture === 'function') {
600
- return { child, permissions };
601
- }
602
- } catch {
603
- /* try the next layout */
604
- }
605
- }
606
- throw new Error(
607
- 'aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing ' +
608
- 'from this install — refusing to build a second argv, because a second argv is a second policy.'
609
- );
610
- }
611
-
612
- /** Whether the argv seam resolves here, without throwing. For status panels. */
613
- function seamAvailable(dir) {
614
- try {
615
- loadSeam(dir);
616
- return { ok: true, error: null };
617
- } catch (e) {
618
- return { ok: false, error: (e && e.message) || String(e) };
619
- }
620
- }
621
-
622
- /**
623
- * The `choices[0].message` a Pro turn reports.
624
- *
625
- * `content` is the child's own final answer, as before. The addition is the
626
- * deliberation, carried on the shape the engine already reads: `reasoning_content`
627
- * is what `engine.js` `reasoningTextOf()` looks for first, so a Pro round that
628
- * spent its output thinking is now visible as exactly that.
629
- *
630
- * This matters because of how a Pro turn fails. When extended thinking is on —
631
- * which is Claude Code's default — the child can finish a round having produced
632
- * deliberation and no answer, and the engine's recovery ladder decides what to
633
- * do next by asking `reasonedButSilent(res)`, i.e. "was this round empty, or did
634
- * it think and stay silent?". Before this field existed, a Pro result never
635
- * carried reasoning at all, so that question always answered "genuinely empty"
636
- * and the ladder burned its rounds on the generic nudge — the ask that invites
637
- * the same silent thinking pass a second time. Worse, `emptyTurnError` reported
638
- * it as "No visible text came back from any of those calls", which is the wrong
639
- * diagnosis: the model was not silent, it was thinking.
640
- *
641
- * `thinking_tokens` rides alongside as the provider's own billed count. On a
642
- * real Pro turn the deliberation TEXT is withheld — measured across three turns,
643
- * every `thinking_delta` carried `thinking: ""` while thousands of tokens were
644
- * billed — so a text-only signal would still miss the case this exists for. The
645
- * count is the honest figure, and it is the only one that arrives.
646
- */
647
- function proMessage(text, thinking, thinkingTokens) {
648
- const msg = { content: text || '' };
649
- const deliberation = typeof thinking === 'string' ? thinking : '';
650
- if (deliberation) msg.reasoning_content = deliberation;
651
- if (typeof thinkingTokens === 'number' && thinkingTokens > 0 && Number.isFinite(thinkingTokens)) {
652
- msg.thinking_tokens = thinkingTokens;
653
- }
654
- return msg;
655
- }
656
-
657
- /**
658
- * Run one turn on the user's Claude Code subscription.
659
- *
660
- * Returns the SAME shape the other three transports return, because the engine
661
- * loop reads one shape (`choices[0].message.content`, `usage`, `stop_reason`) —
662
- * `extractToolCalls`, `assistantText`, `finishReasonOf` and `addUsage` all read
663
- * it. Returns NO tool_calls, and that is the design rather than an omission:
664
- * the `claude` child runs its own agent loop with its own tools, so the work is
665
- * already done by the time this resolves. Emitting tool_calls as well would
666
- * hand a second, parallel loop the same task and run every tool twice.
667
- *
668
- * @param {object} opts
669
- * @param {string} opts.prompt
670
- * @param {string} [opts.model] a `claude --model` alias (PRO_MODELS)
671
- * @param {string} [opts.system] appended to the child's own prompt
672
- * @param {string} [opts.cwd] the directory the child works in
673
- * @param {string[]} [opts.addDir] extra directories the child may work in.
674
- * The child resolves every relative path
675
- * and every tool's root against `cwd`
676
- * alone, so a turn started in a
677
- * subdirectory cannot see the tree above
678
- * it; this is what widens that. Spelled
679
- * by the ONE argv builder (one/src/child.js
680
- * addDirArgs), never typed here.
681
- * @param {object} [opts.rules] CLI permission rules (cli/src/config.js)
682
- * @param {boolean} [opts.gate] the stored /confirm posture, if known
683
- * @param {string} [opts.permissionMode] explicit passthrough, validated in child.js
684
- * @param {string} [opts.resumeSessionId] reattach to the session a prior turn
685
- * reported → the turn keeps its context
686
- * @param {string} [opts.sessionId] name a NEW session (UUID) for a first turn
687
- * @param {AbortSignal} [opts.signal]
688
- * @param {Function} [opts.onSpawn] receives the child the moment it exists
689
- * @param {number} [opts.idleTimeoutMs] silence budget (default 10 min)
690
- * @returns {Promise<object>} an engine-shaped completion
691
- */
692
- function runClaudePro(opts, deps) {
693
- const o = opts || {};
694
- const d = deps || {};
695
- const seam = d.seam || loadSeam(d.dir);
696
- const spawnFn = d.spawn || require('node:child_process').spawn;
697
-
698
- // One posture per turn, from the single resolver — never re-derived here.
699
- const posture = seam.permissions.resolvePosture({
700
- rules: o.rules,
701
- gate: o.gate,
702
- interactive: false,
703
- childKind: seam.permissions.CHILD_KINDS.HEADLESS,
704
- env: o.env || process.env,
705
- });
706
-
707
- const built = seam.child.claudeArgv({
708
- posture,
709
- prompt: o.prompt,
710
- model: o.model || undefined,
711
- permissionMode: o.permissionMode,
712
- // Continuity, handed to the ONE argv builder rather than typed as `extra`.
713
- // Without these the child starts a brand-new conversation every turn: the
714
- // engine does not replay the transcript into it (`pro` runs its own agent
715
- // loop), so the CLI's own session store is the ONLY thing that can carry
716
- // context across turns. `resumeSessionId` reattaches to the session a
717
- // previous turn reported; `sessionId` names a new one for a later resume.
718
- resumeSessionId: o.resumeSessionId,
719
- sessionId: o.sessionId,
720
- // The widened sandbox for this turn, if the caller asked for one. It rides
721
- // the descriptor rather than `extra` because `--add-dir` is variadic and its
722
- // correct spelling is a decision (child.js addDirArgs), not a flag a caller
723
- // may type.
724
- addDir: o.addDir,
725
- // `--include-partial-messages` is what makes `stream_event` lines arrive at
726
- // all, and `--verbose` is required by the CLI alongside stream-json in print
727
- // mode. Both belong to the transport (this file), not to the posture.
728
- extra: [...turnArgs(o), '--include-partial-messages', '--verbose'],
729
- });
730
-
731
- return new Promise((resolve) => {
732
- if (o.signal && o.signal.aborted) {
733
- resolve({ choices: [{ message: { content: '' }, finish_reason: 'stop' }], stopped: true });
734
- return;
735
- }
736
-
737
- // `CLAUDE_CODE_OAUTH_TOKEN` is merged into the CHILD's env only — never
738
- // written back to `o.env`/`process.env` — so a token the on-disk
739
- // credential file lacks (or has let expire) still reaches the one process
740
- // that can spend it, without making the value ambient to this host or any
741
- // other child it spawns. See claudeOAuthToken() for where it comes from.
742
- //
743
- // `childEnvPlan` additionally refuses to hand over a shadowing var that
744
- // cannot be a credential. Without it a signed-in machine runs the child as
745
- // "API key: he" and the subscription is unreachable — see childEnvPlan.
746
- const baseEnv = o.env || process.env;
747
- const token = claudeOAuthToken(baseEnv);
748
- // Whether a subscription is present decides whether a non-console
749
- // `ANTHROPIC_API_KEY` may shadow it (childEnvPlan's second rule). It is read
750
- // from the same credential file `claudeProStatus` reports on, and a failure
751
- // to read it must NOT weaken the child's env: an unreadable file means "no
752
- // subscription proven", which is the old behaviour, not a crash mid-turn.
753
- let hasSubscription = false;
754
- try {
755
- hasSubscription = !!claudeProStatus({ env: baseEnv }).subscriptionPresent;
756
- } catch {
757
- /* unprovable subscription → the floor-only rule, exactly as before */
758
- }
759
- const plan = childEnvPlan(baseEnv, token, { hasSubscription });
760
- const childEnv = plan.env;
761
- const droppedLine = envDroppedLine(plan.dropped);
762
- if (droppedLine && o.onDelta) {
763
- // Same channel the transcript already paints notes on, and emitted BEFORE
764
- // the spawn so the line lands above the child's own tool rows.
765
- try {
766
- o.onDelta({ delta: '', note: droppedLine });
767
- } catch {
768
- /* a throwing renderer must not take the turn down */
769
- }
770
- }
771
-
772
- let child;
773
- try {
774
- child = spawnFn(d.executable || 'claude', built.argv, {
775
- cwd: o.cwd || process.cwd(),
776
- stdio: ['ignore', 'pipe', 'pipe'],
777
- env: childEnv,
778
- });
779
- } catch (e) {
780
- resolve({
781
- choices: [{ message: { content: '' }, finish_reason: 'error' }],
782
- error: `claude: could not start the child (${(e && e.message) || e})`,
783
- ...(plan.dropped.length ? { envDropped: plan.dropped } : {}),
784
- });
785
- return;
786
- }
787
-
788
- if (o.onSpawn) {
789
- try {
790
- o.onSpawn(child, built.record);
791
- } catch {
792
- /* a throwing hook must not take the turn down */
793
- }
794
- }
795
-
796
- let finished = false;
797
- let stderr = '';
798
- let buffer = '';
799
- let idle = null;
800
- const idleMs = Number(o.idleTimeoutMs) || 10 * 60 * 1000;
801
-
802
- const settle = (result) => {
803
- if (finished) return;
804
- finished = true;
805
- if (idle) clearTimeout(idle);
806
- if (o.signal) o.signal.removeEventListener('abort', kill);
807
- // Recorded on every settle path, the same way `childRecord` is: what the
808
- // child was NOT given is part of what this turn did, and a caller logging
809
- // only the argv would show a turn that "should" have failed as a mystery.
810
- resolve(plan.dropped.length ? { ...result, envDropped: plan.dropped } : result);
811
- };
812
-
813
- const kill = () => {
814
- try {
815
- child.kill('SIGTERM');
816
- } catch {
817
- /* already gone */
818
- }
819
- setTimeout(() => {
820
- try {
821
- child.kill('SIGKILL');
822
- } catch {
823
- /* already gone */
824
- }
825
- }, 1500);
826
- };
827
- if (o.signal) o.signal.addEventListener('abort', kill, { once: true });
828
-
829
- // Idle watchdog, not a flat turn cap: it resets on every byte, so it fires
830
- // only on true silence — which is what a lapsed OAuth session looks like
831
- // when the child opens a re-auth prompt nobody on this side can answer.
832
- const armIdle = () => {
833
- if (idle) clearTimeout(idle);
834
- idle = setTimeout(() => {
835
- kill();
836
- settle({
837
- choices: [{ message: { content: '' }, finish_reason: 'stop' }],
838
- error: `claude: the child went silent for ${Math.round(idleMs / 1000)}s and was stopped`,
839
- });
840
- }, idleMs);
841
- };
842
- armIdle();
843
-
844
- const parser = createStreamParser({
845
- onText: (t) => {
846
- armIdle();
847
- if (o.onDelta) o.onDelta({ delta: t });
848
- },
849
- // Extended thinking, forwarded on the SAME channel the engine's pooled
850
- // brain path already uses for a worker's deliberation (`onReasoning`,
851
- // engine.js — `onDelta({ reasoning })`). Both renderers already consume
852
- // that field, so the live token meter counts the thinking phase on a Pro
853
- // turn exactly as it does everywhere else, with no consumer-side edit.
854
- // `engine.js` hands `runClaudePro` the RAW `opts.onDelta` (not the wrapped
855
- // `onReasoning`), so this transport is the one that must emit the field.
856
- onThinking: (t) => {
857
- armIdle();
858
- if (o.onDelta) o.onDelta({ reasoning: t });
859
- },
860
- // The channel that actually fires on a Pro turn. `onThinking` above is
861
- // kept for any provider that does stream deliberation text, but Claude
862
- // Code withholds it: measured across three real turns, every
863
- // `thinking_delta` carried `thinking: ""`, so `onThinking` never fired
864
- // once while 4114 thinking tokens were billed. This carries the
865
- // provider's own MEASURED count, on a numeric channel of its own rather
866
- // than the text one — the consumers turn `reasoning` text into tokens at
867
- // 4 chars:1 token, so a token count sent down that path would be divided
868
- // by four and read as a quarter of the truth.
869
- onThinkingProgress: (est) => {
870
- armIdle();
871
- if (o.onDelta) o.onDelta({ thinkingTokens: est });
872
- },
873
- onTool: (info) => {
874
- armIdle();
875
- if (!o.onDelta) return;
876
- // Same tool frame the engine's own loop emits, so the renderers paint a
877
- // subscription turn's tool rows with no second code path.
878
- o.onDelta({
879
- delta: '',
880
- tool: {
881
- name: info.name,
882
- args: info.args,
883
- ok: info.phase === 'done' ? !info.error : undefined,
884
- id: info.id,
885
- cwd: o.cwd,
886
- phase: info.phase,
887
- },
888
- });
889
- },
890
- onDone: (r) => {
891
- if (r.error) {
892
- settle({
893
- choices: [{ message: { content: r.text || '' }, finish_reason: 'error' }],
894
- usage: r.usage || undefined,
895
- error: r.error,
896
- });
897
- return;
898
- }
899
- settle({
900
- choices: [{ message: proMessage(r.text || '', r.thinking, r.thinkingTokens), finish_reason: 'stop' }],
901
- usage: r.usage || undefined,
902
- costUsd: r.costUsd,
903
- durationMs: r.durationMs,
904
- sessionId: r.sessionId,
905
- // Carried so a caller can log WHICH flags the child actually got —
906
- // rule 4's "recorded, never inferred".
907
- childRecord: built.record,
908
- });
909
- },
910
- });
911
-
912
- child.stdout.on('data', (chunk) => {
913
- armIdle();
914
- buffer += chunk.toString('utf8');
915
- const lines = buffer.split('\n');
916
- buffer = lines.pop() || '';
917
- for (const line of lines) {
918
- const t = line.trim();
919
- if (t) parser.line(t);
920
- }
921
- });
922
- child.stderr.on('data', (chunk) => {
923
- armIdle();
924
- if (stderr.length < 8192) stderr += chunk.toString('utf8');
925
- });
926
-
927
- child.on('error', (e) => {
928
- settle({
929
- choices: [{ message: { content: '' }, finish_reason: 'error' }],
930
- error:
931
- `claude: could not run the child (${(e && e.message) || e}). ` +
932
- 'Install it with `npm i -g @anthropic-ai/claude-code`, then sign in with `claude auth login`.',
933
- });
934
- });
935
-
936
- child.on('close', (code) => {
937
- if (buffer.trim()) parser.line(buffer.trim());
938
- // Only reached when no `result` line arrived — a clean exit always emits
939
- // one. Anything else is a real failure and is reported as one rather than
940
- // as an empty successful answer.
941
- settle({
942
- choices: [
943
- {
944
- message: proMessage(parser.text, parser.thinking, parser.thinkingTokens),
945
- finish_reason: 'stop',
946
- },
947
- ],
948
- usage: (parser.resultLine && parser.resultLine.usage) || undefined,
949
- childRecord: built.record,
950
- error:
951
- parser.text || code === 0
952
- ? undefined
953
- : `claude: the child exited with status ${code}${
954
- stderr.trim() ? ` — ${stderr.trim().split('\n').slice(-3).join(' ')}` : ''
955
- }`,
956
- });
957
- });
958
- });
959
- }
960
-
961
- /**
962
- * The run-log line for a child argv, from the seam that owns the wording. A
963
- * missing seam degrades to a short local summary rather than throwing — this is
964
- * a reporting path, and a turn that already ran must not fail to describe
965
- * itself.
966
- */
967
- function childLine(record, dir) {
968
- if (!record) return '';
969
- try {
970
- return loadSeam(dir).child.childRecordLine(record);
971
- } catch {
972
- const flag = record.skipFlag || 'no permission flag';
973
- return `aegis: claude child [${record.kind}] ${flag}`;
974
- }
975
- }
976
-
977
- module.exports = {
978
- claudeConfigDir,
979
- claudeOAuthToken,
980
- claudeProStatus,
981
- // The child-env half of "the subscription actually gets spent": the plan for
982
- // what the `claude` child is given (and what a shadowing value cost), the
983
- // one-line report of it, and the inspector `claudeProStatus` reports.
984
- childEnvPlan,
985
- envDroppedLine,
986
- shadowingValue,
987
- SHADOWING_ENV_VARS,
988
- PRO_MODELS,
989
- turnArgs,
990
- createStreamParser,
991
- loadSeam,
992
- seamAvailable,
993
- childLine,
994
- runClaudePro,
995
- };
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 r(e){return o?o.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const i=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function a(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function l(e,n,t){const s={...e||{}},r=[],l=o&&"function"==typeof o.credentialLooksUsable?o.credentialLooksUsable:null,c=!(!t||!t.hasSubscription);if(l)for(const e of i){const n=s[e];if("string"!=typeof n)continue;let t=null;if(l(n)?c&&"ANTHROPIC_API_KEY"===e&&!a(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const o=n.trim().length;o>0&&r.push({name:e,length:o,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:r}}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 r=!(!n||!n.hasSubscription);for(const e of i){const n=t[e];if("string"!=typeof n)continue;let o=null;if(s(n)?r&&"ANTHROPIC_API_KEY"===e&&!a(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||{},i=o.env||process.env,a=t.join(o.dir||s(i),".credentials.json"),c={claude:o.claudeVersion||null,file:a,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let u;try{u=JSON.parse(e.readFileSync(a,"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):r(i)&&(c.kind="env-token",c.loggedIn=!0),c.subscriptionPresent=c.loggedIn&&"apikey"!==c.kind,c.shadowed=d(i,{hasSubscription:c.subscriptionPresent});const h=l(i,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"},{id:"opus",label:"Opus",note:"alias the CLI resolves"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves"}]);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="",r=0,i=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)&&(r+=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&&(i=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:r}))},get text(){return o},get thinking(){return s},get thinkingTokens(){return r},get resultLine(){return i}}}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:r,claudeProStatus:u,childEnvPlan:l,envDroppedLine:c,shadowingValue:d,SHADOWING_ENV_VARS:i,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),i=o.spawn||require("node:child_process").spawn,a=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:a,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=r(n);let a=!1;try{a=!!u({env:n}).subscriptionPresent}catch{}const p=l(n,s,{hasSubscription:a}),h=p.env,f=c(p.dropped);if(f&&t.onDelta)try{t.onDelta({delta:"",note:f})}catch{}let _;try{_=i(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="",y="",b=null;const T=Number(t.idleTimeoutMs)||6e5,A=n=>{k||(k=!0,b&&clearTimeout(b),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 D=()=>{b&&clearTimeout(b),b=setTimeout((()=>{I(),A({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(T/1e3)}s and was stopped`})}),T)};D();const S=g({onText:e=>{D(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{D(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{D(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{D(),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?A({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error}):A({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=>{D(),y+=e.toString("utf8");const n=y.split("\n");y=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}})),_.stderr.on("data",(e=>{D(),v.length<8192&&(v+=e.toString("utf8"))})),_.on("error",(e=>{A({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=>{y.trim()&&S.line(y.trim()),A({choices:[{message:m(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:d.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${v.trim()?` — ${v.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}};