aegisone 1.0.17 → 1.0.20

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 (52) hide show
  1. package/README.md +2 -2
  2. package/package.json +3 -3
  3. package/scripts/bump.mjs +29 -4
  4. package/scripts/predist.mjs +2 -0
  5. package/src/dispatch.js +1 -0
  6. package/vendor/cli/README.md +3 -3
  7. package/vendor/cli/bin/aegiscode.js +29 -0
  8. package/vendor/cli/package.json +2 -2
  9. package/vendor/cli/src/app.js +370 -30
  10. package/vendor/cli/src/autonomous.js +30 -4
  11. package/vendor/cli/src/chatflow.js +132 -4
  12. package/vendor/cli/src/commands.js +223 -64
  13. package/vendor/cli/src/config.js +21 -0
  14. package/vendor/cli/src/connect.js +351 -0
  15. package/vendor/cli/src/deps.js +97 -1
  16. package/vendor/cli/src/engine.js +123 -7
  17. package/vendor/cli/src/fingerprint.js +46 -16
  18. package/vendor/cli/src/limits.js +1 -1
  19. package/vendor/cli/src/overlays.js +98 -0
  20. package/vendor/cli/src/provenance.lock.json +3 -3
  21. package/vendor/cli/src/screens.js +14 -1
  22. package/vendor/cli/vendor/client/credentials.js +9 -2
  23. package/vendor/cli/vendor/client/google-signin.js +127 -0
  24. package/vendor/cli/vendor/client/record-vault.js +431 -113
  25. package/vendor/cli/vendor/client/update.js +266 -0
  26. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +48 -8
  27. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +134 -11
  28. package/vendor/cli/vendor/desktop/lib/local/engine.js +47 -25
  29. package/vendor/cli/vendor/desktop/lib/settings.js +65 -24
  30. package/vendor/desktop/README.md +1 -1
  31. package/vendor/desktop/lib/auto.js +11 -7
  32. package/vendor/desktop/lib/fingerprint.js +76 -17
  33. package/vendor/desktop/lib/local/autonomous.js +48 -8
  34. package/vendor/desktop/lib/local/claude-pro.js +134 -11
  35. package/vendor/desktop/lib/local/engine.js +47 -25
  36. package/vendor/desktop/lib/settings.js +65 -24
  37. package/vendor/desktop/main.js +79 -24
  38. package/vendor/desktop/package.json +10 -5
  39. package/vendor/desktop/preload.js +31 -12
  40. package/vendor/desktop/renderer/app.js +676 -17
  41. package/vendor/desktop/renderer/budget.js +18 -9
  42. package/vendor/desktop/renderer/companion.js +225 -0
  43. package/vendor/desktop/renderer/fingerprint.css +16 -0
  44. package/vendor/desktop/renderer/fingerprint.js +62 -2
  45. package/vendor/desktop/renderer/index.html +285 -121
  46. package/vendor/desktop/renderer/provider-toolbar.js +136 -0
  47. package/vendor/desktop/renderer/providers.js +261 -0
  48. package/vendor/desktop/renderer/style.css +547 -171
  49. package/vendor/desktop/vendor/credentials.js +9 -2
  50. package/vendor/desktop/vendor/google-signin.js +127 -0
  51. package/vendor/desktop/vendor/record-vault.js +431 -113
  52. package/vendor/desktop/vendor/update.js +266 -0
@@ -158,6 +158,198 @@ function fetchLatest(opts = {}) {
158
158
  return fetchLatestDetailed(opts).then((r) => (r.ok ? r.latest : null));
159
159
  }
160
160
 
161
+ //: Where the AEGIS server answers "am I still allowed to talk to you".
162
+ const DEFAULT_API_BASE = 'https://aegiscloud.org';
163
+ /** /api/v1/version is a tiny JSON document; anything bigger is a proxy page. */
164
+ const VERSION_BODY_CAP = 64 * 1024;
165
+
166
+ /**
167
+ * Ask the SERVER whether this client is still serviceable.
168
+ *
169
+ * Why this exists next to the npm check: they answer different questions.
170
+ * The registry says what was *published*; the server says what it will
171
+ * *accept*. aegis1 refuses every request from a client below
172
+ * `MIN_CLIENT_VERSION` with a 426, so a client that only asks npm learns it is
173
+ * unservicable by being refused mid-task — an outage, not a notice. Asking
174
+ * `/api/v1/version` first turns the same fact into a sentence the user reads
175
+ * before they hit the wall.
176
+ *
177
+ * `/api/v1/version` is informational: it never refuses anyone, and it echoes
178
+ * the verdict for the version header we send (`upgrade_required`).
179
+ *
180
+ * Resolves `{ ok, minClient, latestCli, latestDesktop, upgradeRequired,
181
+ * downloadUrl, reason, status }` and never rejects — same contract as
182
+ * `fetchLatestDetailed`, so a host can render "registry unreachable" and
183
+ * "server unreachable" differently instead of inventing a third story.
184
+ */
185
+ function fetchServerVersionDetailed({
186
+ base = DEFAULT_API_BASE,
187
+ clientVersion = null,
188
+ timeoutMs = TIMEOUT_MS,
189
+ getImpl = null,
190
+ } = {}) {
191
+ return new Promise((resolve) => {
192
+ let settled = false;
193
+ const done = (v) => {
194
+ if (!settled) {
195
+ settled = true;
196
+ resolve(v);
197
+ }
198
+ };
199
+ const fail = (reason, status = null) =>
200
+ done({
201
+ ok: false, minClient: null, latestCli: null, latestDesktop: null,
202
+ upgradeRequired: null, downloadUrl: '', reason, status,
203
+ });
204
+ const succeed = (body, status) => {
205
+ const minClient = body && typeof body.min_client === 'string' ? body.min_client : null;
206
+ // A 200 without `min_client` is malformed, not a slow network: do not
207
+ // invite a retry ladder for a document that will parse the same way.
208
+ if (!minClient) return fail(REASONS.MALFORMED, status);
209
+ done({
210
+ ok: true,
211
+ minClient,
212
+ latestCli: typeof body.latest_cli === 'string' ? body.latest_cli : '',
213
+ latestDesktop: typeof body.latest_desktop === 'string' ? body.latest_desktop : '',
214
+ // Trust the header echo only when we actually sent a version: without
215
+ // one the server answers for `require_header=False` and the answer is
216
+ // about nothing in particular. `null` here means "the server did not
217
+ // say", which is different from "the server said no" — the caller must
218
+ // be able to fall back without overriding an answer it was given.
219
+ upgradeRequired:
220
+ clientVersion && typeof body.upgrade_required === 'boolean'
221
+ ? body.upgrade_required
222
+ : null,
223
+ downloadUrl: typeof body.download_url === 'string' ? body.download_url : '',
224
+ reason: null,
225
+ status,
226
+ });
227
+ };
228
+
229
+ try {
230
+ const url = `${String(base || DEFAULT_API_BASE).replace(/\/+$/, '')}/api/v1/version`;
231
+ const headers = { accept: 'application/json' };
232
+ if (clientVersion) headers['X-AEGIS-Version'] = String(clientVersion);
233
+
234
+ const onResponse = (res) => {
235
+ const status = res.statusCode;
236
+ if (status !== 200) {
237
+ res.resume();
238
+ if (status === 404) return fail(REASONS.NOT_FOUND, status);
239
+ if (status === 401 || status === 403) return fail(REASONS.FORBIDDEN, status);
240
+ // 426 here would mean the endpoint itself were gated; treat it as a
241
+ // real answer rather than a transport failure if it ever happens.
242
+ if (status === 426) return fail(REASONS.HTTP, status);
243
+ return fail(REASONS.HTTP, status);
244
+ }
245
+ let body = '';
246
+ res.setEncoding('utf8');
247
+ res.on('data', (c) => {
248
+ body += c;
249
+ if (body.length > VERSION_BODY_CAP) {
250
+ res.destroy();
251
+ fail(REASONS.TOO_LARGE, status);
252
+ }
253
+ });
254
+ res.on('end', () => {
255
+ if (settled) return;
256
+ try {
257
+ succeed(JSON.parse(body), status);
258
+ } catch {
259
+ fail(REASONS.MALFORMED, status);
260
+ }
261
+ });
262
+ };
263
+
264
+ if (typeof getImpl === 'function') {
265
+ // Injected transport for tests and hosts that already own a fetch:
266
+ // `getImpl({url, headers, timeoutMs})` resolves `{status, text}`.
267
+ Promise.resolve(getImpl({ url, headers, timeoutMs }))
268
+ .then((r) => {
269
+ const status = r && r.status != null ? r.status : 0;
270
+ if (!status) return fail(REASONS.NETWORK);
271
+ if (status !== 200) {
272
+ if (status === 404) return fail(REASONS.NOT_FOUND, status);
273
+ if (status === 401 || status === 403) return fail(REASONS.FORBIDDEN, status);
274
+ return fail(REASONS.HTTP, status);
275
+ }
276
+ const text = r && typeof r.text === 'string' ? r.text : '';
277
+ if (text.length > VERSION_BODY_CAP) return fail(REASONS.TOO_LARGE, status);
278
+ try {
279
+ succeed(JSON.parse(text), status);
280
+ } catch {
281
+ fail(REASONS.MALFORMED, status);
282
+ }
283
+ })
284
+ .catch(() => fail(REASONS.NETWORK));
285
+ return;
286
+ }
287
+
288
+ const req = require(/^http:\/\//i.test(url) ? 'node:http' : 'node:https')
289
+ .get(url, { headers, timeout: timeoutMs }, onResponse);
290
+ req.on('timeout', () => {
291
+ req.destroy();
292
+ fail(REASONS.TIMEOUT);
293
+ });
294
+ req.on('error', () => fail(REASONS.NETWORK));
295
+ } catch {
296
+ fail(REASONS.NETWORK);
297
+ }
298
+ });
299
+ }
300
+
301
+ /** The server's minimum client version, or null. */
302
+ function fetchServerVersion(opts = {}) {
303
+ return fetchServerVersionDetailed(opts).then((r) => (r.ok ? r.minClient : null));
304
+ }
305
+
306
+ /**
307
+ * The server's verdict, expressed in the shape the notice/plan code already
308
+ * speaks: `{ behind, latest, required, downloadUrl, ok, reason, status }`.
309
+ *
310
+ * `behind` is true when the SERVER says this client is below its minimum —
311
+ * regardless of whether npm happens to have something newer. That ordering is
312
+ * deliberate: being refused is actionable now, being merely superseded is not.
313
+ */
314
+ async function serverUpdateVerdict({
315
+ current,
316
+ base = DEFAULT_API_BASE,
317
+ timeoutMs = TIMEOUT_MS,
318
+ getImpl = null,
319
+ } = {}) {
320
+ const res = await fetchServerVersionDetailed({ base, clientVersion: current, timeoutMs, getImpl });
321
+ if (!res.ok) {
322
+ return { ok: false, behind: false, latest: null, required: null, downloadUrl: '', reason: res.reason, status: res.status };
323
+ }
324
+ const required = res.minClient || null;
325
+ // The server's echo decides. Falling back to local arithmetic only when it
326
+ // said nothing (`null`) — OR'ing the two would let our own comparison
327
+ // override the very authority we asked, which is the bug this line exists to
328
+ // not have.
329
+ const behind =
330
+ res.upgradeRequired === true
331
+ ? true
332
+ : res.upgradeRequired === false
333
+ ? false
334
+ : required
335
+ ? isNewer(required, current)
336
+ : false;
337
+ return {
338
+ ok: true,
339
+ behind,
340
+ // The server's own minimum is the target when it is the thing refusing us;
341
+ // a published version is preferred when it names one, because that is what
342
+ // the user should actually install.
343
+ latest: (behind && (res.latestCli || res.latestDesktop)) || required,
344
+ latestCli: res.latestCli,
345
+ latestDesktop: res.latestDesktop,
346
+ required,
347
+ downloadUrl: res.downloadUrl,
348
+ reason: null,
349
+ status: res.status,
350
+ };
351
+ }
352
+
161
353
  /**
162
354
  * The notice to show, from cache. Never waits on the network.
163
355
  *
@@ -333,10 +525,83 @@ function updateLine({ current, latest, behind, pkg = PKG }) {
333
525
  return `Update available: ${plan.current} → ${plan.latest} run: ${plan.instruction}`;
334
526
  }
335
527
 
528
+ /**
529
+ * The server's verdict, from cache. Never waits on the network.
530
+ *
531
+ * Same contract and the same once-a-day rule as `updateNotice`, for the same
532
+ * reason: the welcome box draws from what the last run learned, and the
533
+ * refresh lands for the next one. A first run shows nothing, which is right —
534
+ * it has no verdict yet.
535
+ *
536
+ * Returns `{ behind, latest, required, downloadUrl }`. `behind` is the server's
537
+ * answer, not a comparison this module invented, so the box says "update" only
538
+ * when the server would actually refuse this client.
539
+ */
540
+ function serverNotice({
541
+ current,
542
+ cache,
543
+ save,
544
+ now = Date.now(),
545
+ verdictImpl = serverUpdateVerdict,
546
+ intervalMs = CHECK_INTERVAL_MS,
547
+ } = {}) {
548
+ const c = cache || {};
549
+ const fresh = typeof c.checkedAt === 'number' && now - c.checkedAt < intervalMs;
550
+
551
+ if (!fresh) {
552
+ Promise.resolve()
553
+ .then(() => verdictImpl({ current }))
554
+ .then((v) => {
555
+ if (!v || typeof save !== 'function') return;
556
+ // Persist the verdict even when it is "not behind": that is what tells
557
+ // the next run it already asked today, and stops a check per launch.
558
+ save({
559
+ checkedAt: now,
560
+ behind: Boolean(v.behind),
561
+ required: v.required || null,
562
+ latest: v.latest || null,
563
+ downloadUrl: v.downloadUrl || '',
564
+ reason: v.reason || null,
565
+ });
566
+ })
567
+ .catch(() => {});
568
+ }
569
+
570
+ return {
571
+ behind: Boolean(c.behind),
572
+ latest: c.latest || null,
573
+ required: c.required || null,
574
+ downloadUrl: c.downloadUrl || '',
575
+ };
576
+ }
577
+
578
+ /**
579
+ * The line for the welcome box when the SERVER says this build is too old.
580
+ *
581
+ * Distinct from `updateLine` on purpose: "a newer release exists" and "the
582
+ * server will refuse you" are different urgency, and only the second one means
583
+ * the app is about to stop working. Says where to get it, because a user who
584
+ * is being cut off needs a destination, not a version number.
585
+ */
586
+ function serverUpdateLine({ behind, latest, required, downloadUrl } = {}) {
587
+ if (!behind) return null;
588
+ const target = latest || required || '';
589
+ const head = target
590
+ ? `This build is no longer served — update to v${target}.`
591
+ : 'This build is no longer served — update to the latest release.';
592
+ const where = downloadUrl ? ` ${downloadUrl}` : '';
593
+ return `${head}${where}`;
594
+ }
595
+
336
596
  module.exports = {
337
597
  isNewer,
338
598
  fetchLatest,
339
599
  fetchLatestDetailed,
600
+ fetchServerVersion,
601
+ fetchServerVersionDetailed,
602
+ serverUpdateVerdict,
603
+ serverNotice,
604
+ serverUpdateLine,
340
605
  isTransientReason,
341
606
  updateNotice,
342
607
  checkPublished,
@@ -345,4 +610,5 @@ module.exports = {
345
610
  PKG,
346
611
  CHECK_INTERVAL_MS,
347
612
  REASONS,
613
+ DEFAULT_API_BASE,
348
614
  };
@@ -209,8 +209,15 @@ const DEFAULT_MODEL = 'nexus-brain';
209
209
  * depends on what the user's own daemon happens to have. Both REQUIRE an
210
210
  * explicit model, refused by name instead of silently resolving to
211
211
  * something nobody chose.
212
+ * - 'pro' DOES have a default, but not one this app chooses: a blank model
213
+ * means "the `claude` CLI picks for the subscription", which is what
214
+ * `--model` omitted says (engine.js sends no flag for `default`). Once a
215
+ * model IS stated it must be one of claude-pro.js's PRO_MODELS aliases —
216
+ * the same list the model picker offers — because the child accepts only
217
+ * those four spellings, and a `provider:model` id copied from a byok task
218
+ * would otherwise be handed to `claude --model` and fail there.
212
219
  */
213
- const MODEL_CLASSES = Object.freeze(['aegis', 'byok', 'local']);
220
+ const MODEL_CLASSES = Object.freeze(['aegis', 'byok', 'local', 'pro']);
214
221
 
215
222
  const AEGIS_MODEL_RE = /^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/;
216
223
  const AEGIS_MODEL_IDS = Object.freeze(['nexus-brain', 'aegis-brain']);
@@ -270,6 +277,34 @@ function modelRefusal(id, cls) {
270
277
  }
271
278
  return '';
272
279
  }
280
+ if (normalized === 'pro') {
281
+ // The subscription route. A blank model is legal and meaningful: engine.js
282
+ // sends no `--model` at all for 'default', so the child resolves the pick
283
+ // itself. Anything STATED must be a PRO_MODELS alias, because those four
284
+ // spellings are exactly what `claude --model` accepts — a byok-style
285
+ // "provider:model" copied between tasks would be handed to the child and
286
+ // fail there, three stages into a drain, with the queue's own file naming
287
+ // something the queue never validated.
288
+ if (!stated) return '';
289
+ // Required lazily: claude-pro.js is a heavy sibling (child spawn, session
290
+ // files) and this module is loaded by queue.js at every CLI start. The
291
+ // require is a plain sibling path with no back-require, so there is no
292
+ // cycle to guard — this is about load cost, not correctness.
293
+ let aliases;
294
+ try {
295
+ aliases = require('./claude-pro.js').PRO_MODELS;
296
+ } catch {
297
+ // If the alias list cannot be read we cannot validate a stated model, and
298
+ // accepting it unvalidated is the exact failure this arm exists to stop.
299
+ return `a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick`;
300
+ }
301
+ const ids = (Array.isArray(aliases) ? aliases : []).map((m) => String(m && m.id).trim());
302
+ if (ids.includes(stated.toLowerCase())) return '';
303
+ return (
304
+ `the autonomous queue's Pro class runs the subscription through the claude CLI, ` +
305
+ `which accepts only its own model aliases (${ids.join('/')}); "${stated}" is not one`
306
+ );
307
+ }
273
308
  // normalized === 'local'
274
309
  if (!stated) return 'a local task needs a model — the tag of whatever is pulled into the local daemon';
275
310
  return '';
@@ -594,13 +629,18 @@ function createQueueWorker({
594
629
  */
595
630
  async function runTask(item, { carry = '', commit } = {}) {
596
631
  const cwd = item.cwd || process.cwd();
597
- // Aegis Cloud or nothing — checked BEFORE the turn, not at the server. An
598
- // item whose model is not a pooled tier (a hand-edited queue file, a
599
- // `--model` the CLI accepted before this rule existed, another host's
600
- // older build) would otherwise go out as `class: 'aegis'` with an id the
601
- // pool does not serve: billed work if it happens to be a per-provider
602
- // spelling, an opaque server error otherwise. Failing here names the model
603
- // and the allowed ones, and costs nothing.
632
+ // The task's own (model, class) pair checked BEFORE the turn, not at the
633
+ // server. An item whose model does not belong to its class (a hand-edited
634
+ // queue file, a `--model` the CLI accepted before this rule existed,
635
+ // another host's older build) would otherwise go out under a transport
636
+ // that does not serve it: billed work if it happens to be a per-provider
637
+ // spelling, an opaque server error otherwise, and for 'pro' a `claude
638
+ // --model` that the child rejects. Failing here names the model and the
639
+ // spellings that class accepts, and costs nothing.
640
+ //
641
+ // "Aegis Cloud or nothing" was this comment's old claim, and it stopped
642
+ // being true when byok/local were added (9eeef09) — modelRefusal is what
643
+ // actually enforces the rule now, per class, and it runs for all four.
604
644
  const cls = normalizeClass(item.class);
605
645
  const refusal = modelRefusal(item.model, cls);
606
646
  if (refusal) {
@@ -116,6 +116,23 @@ function claudeOAuthToken(env) {
116
116
  */
117
117
  const SHADOWING_ENV_VARS = Object.freeze(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']);
118
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
+
119
136
  /**
120
137
  * The env for one `claude` child, with a shadowing value that cannot be a
121
138
  * credential removed.
@@ -151,28 +168,69 @@ const SHADOWING_ENV_VARS = Object.freeze(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_T
151
168
  * value that provably cannot be a key is dropped, and the drop is REPORTED
152
169
  * rather than silent (see `envDroppedLine`).
153
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
+ *
154
196
  * @param {object} [baseEnv] the caller's env bag
155
197
  * @param {string} [token] a `CLAUDE_CODE_OAUTH_TOKEN` to hand the child
156
- * @returns {{env: object, dropped: Array<{name: string, length: number}>}}
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}>}}
157
202
  */
158
- function childEnvPlan(baseEnv, token) {
203
+ function childEnvPlan(baseEnv, token, opts) {
159
204
  const env = { ...(baseEnv || {}) };
160
205
  const dropped = [];
161
206
  const usable = envFileLib && typeof envFileLib.credentialLooksUsable === 'function'
162
207
  ? envFileLib.credentialLooksUsable
163
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);
164
212
  // A host whose env module predates the floor keeps today's behaviour (the
165
213
  // variable passes through): a second copy of the floor here is the drift
166
214
  // client/env-file.js exists to prevent.
167
215
  if (usable) {
168
216
  for (const name of SHADOWING_ENV_VARS) {
169
217
  const value = env[name];
170
- if (typeof value !== 'string' || usable(value)) continue;
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;
171
229
  delete env[name];
172
230
  // A variable set to '' shadows nothing worth reporting — it is removed
173
231
  // (harmless) but the user is not told about a value they never gave.
174
232
  const length = value.trim().length;
175
- if (length > 0) dropped.push({ name, length });
233
+ if (length > 0) dropped.push({ name, length, reason });
176
234
  }
177
235
  }
178
236
  if (token) env.CLAUDE_CODE_OAUTH_TOKEN = token;
@@ -183,20 +241,51 @@ function childEnvPlan(baseEnv, token) {
183
241
  function envDroppedLine(dropped) {
184
242
  const list = Array.isArray(dropped) ? dropped : [];
185
243
  if (!list.length) return null;
186
- const names = list.map((d) => `${d.name} (${d.length} character${d.length === 1 ? '' : 's'})`).join(', ');
187
- return `aegis: not passed to the claude child — ${names}: too short to be a credential, and the CLI would have spent it instead of your subscription`;
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('; ')}`;
188
258
  }
189
259
 
190
- /** The shadowing value in `env` that cannot be a credential, if any (see above). */
191
- function shadowingValue(env) {
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) {
192
274
  const bag = env || {};
193
275
  const usable = envFileLib && typeof envFileLib.credentialLooksUsable === 'function'
194
276
  ? envFileLib.credentialLooksUsable
195
277
  : null;
196
278
  if (!usable) return null;
279
+ const hasSubscription = !!(opts && opts.hasSubscription);
197
280
  for (const name of SHADOWING_ENV_VARS) {
198
281
  const value = bag[name];
199
- if (typeof value === 'string' && !usable(value)) return { name, length: value.trim().length };
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 };
200
289
  }
201
290
  return null;
202
291
  }
@@ -264,7 +353,30 @@ function claudeProStatus(opts) {
264
353
  // child is fixed regardless (childEnvPlan); this reports it so a status
265
354
  // surface can say why, rather than leaving `apiKeySource: ANTHROPIC_API_KEY`
266
355
  // to be discovered from `claude auth status` by hand.
267
- out.shadowed = shadowingValue(env);
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';
268
380
  return out;
269
381
  }
270
382
 
@@ -633,7 +745,18 @@ function runClaudePro(opts, deps) {
633
745
  // "API key: he" and the subscription is unreachable — see childEnvPlan.
634
746
  const baseEnv = o.env || process.env;
635
747
  const token = claudeOAuthToken(baseEnv);
636
- const plan = childEnvPlan(baseEnv, token);
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 });
637
760
  const childEnv = plan.env;
638
761
  const droppedLine = envDroppedLine(plan.dropped);
639
762
  if (droppedLine && o.onDelta) {