aegiscode 7.0.7 → 7.0.9

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.7",
4
+ "version": "7.0.9",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -10,7 +10,8 @@
10
10
  "license": "AGPL-3.0-or-later",
11
11
  "homepage": "https://aegiscloud.org",
12
12
  "bin": {
13
- "aegiscode": "bin/aegiscode.js"
13
+ "aegiscode": "bin/aegiscode.js",
14
+ "aegiscodex": "bin/aegiscode.js"
14
15
  },
15
16
  "files": [
16
17
  "bin",
package/src/app.js CHANGED
@@ -26,7 +26,7 @@
26
26
  const readline = require('node:readline');
27
27
  const os = require('node:os');
28
28
  const { randomUUID } = require('node:crypto');
29
- const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt, autoProvisionApiKey, provisionFailureText, hostEnv, autonomous } = require('./deps.js');
29
+ const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt, autoProvisionApiKey, provisionFailureText, trialNote, hostEnv, autonomous, claudePro } = require('./deps.js');
30
30
  const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace, effortRung } = require('./engine.js');
31
31
  const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE, AUTO_THEME_INDEX, themeIsLight, reconcileThemeIndex } = require('./theme.js');
32
32
  const { probeTerminalBackground } = require('./caps.js');
@@ -173,7 +173,11 @@ function createApp(options = {}) {
173
173
  'info',
174
174
  `auto-provisioned a free account` +
175
175
  (result.ok ? ` (saved to ${credentials.credentialsPath()})` : ' (could not save it — reconfigure with /key)') +
176
- (result.trialGranted === false ? '. The welcome trial was withheld this hour (too many new devices from this network)' : '') +
176
+ // Shared clause: covers the withheld case AND the reused one (a
177
+ // returning fingerprint gets its old account, never a second
178
+ // trial). Inline here it only knew `trialGranted`, so a
179
+ // re-registered machine read as a clean first install.
180
+ trialNote(result) +
177
181
  `. Fund it at ${client.promptUrl('topup', 'device_autoprovision')} or run /byok to use your own key.`
178
182
  )
179
183
  );
@@ -664,7 +668,38 @@ function createApp(options = {}) {
664
668
  /* no pooled catalog to read — byok rows stand alone */
665
669
  }
666
670
  }
667
- return classScopedModels(byok);
671
+ // `want`, not the live class: this call is answering for the class it
672
+ // was ASKED about. See classScopedModels.
673
+ return classScopedModels(byok, want);
674
+ }
675
+ if (want === 'pro') {
676
+ // The Claude Code Pro class' rows come from the engine itself (the
677
+ // CLI's own aliases, claude-pro.js PRO_MODELS) rather than from a
678
+ // fetched catalog, so they are read straight off listModels('pro') —
679
+ // one source, the same one the desktop's picker reads.
680
+ //
681
+ // NOT gated on the subscription already being present — that gate used
682
+ // to hide every pro row until `~/.claude/.credentials.json` (or
683
+ // CLAUDE_CODE_OAUTH_TOKEN) already existed, which made the row
684
+ // impossible to ever reach from THIS picker: there was no way to pick
685
+ // "Claude Code Pro" to set the credential up in the first place, only
686
+ // to confirm one that was already there. A byok row offers exactly the
687
+ // same way with no key either, and picking it is what collects one
688
+ // (`collectKeyFor`, chatflow.js) — a pro row now does the same,
689
+ // through the very token `modelKeyQueue` asks for (client/env-file.js
690
+ // keyForModelId's `foreign: true` branch). `configured` on each row
691
+ // still states whether a turn would succeed RIGHT NOW; listing is a
692
+ // separate question from being ready.
693
+ const info = await engine.listModels('pro');
694
+ return (info && info.models) || [];
695
+ }
696
+ // Anything else is asked of the engine by name — 'local' especially,
697
+ // which used to fall through to the pooled catalog below and so answered
698
+ // "here are the AEGIS Cloud models" to a question about the free local
699
+ // class. Only 'aegis' (the pool) is read from the cached client fetch.
700
+ if (want !== 'aegis') {
701
+ const info = await engine.listModels(want);
702
+ return (info && info.models) || [];
668
703
  }
669
704
  return await loadModels();
670
705
  } catch {
@@ -682,6 +717,19 @@ function createApp(options = {}) {
682
717
  return pickerEntries(byokCache.models).map((m) => ({ ...m, cls: 'byok' }));
683
718
  }
684
719
 
720
+ /**
721
+ * The Claude Code Pro class' rows, tagged the same way as the two above. The
722
+ * list is the CLI's own aliases (PRO_MODELS), which is why there is no cache
723
+ * here: nothing is fetched, so nothing can go stale or be missing offline.
724
+ */
725
+ function proRows() {
726
+ return pickerEntries(claudePro.PRO_MODELS.map((m) => ({
727
+ id: m.id,
728
+ label: m.label,
729
+ note: m.note,
730
+ }))).map((m) => ({ ...m, cls: 'pro' }));
731
+ }
732
+
685
733
  /**
686
734
  * The class-scoped model list — `state().models`, `/models`, the alt+p chord
687
735
  * and the `/class` auto-pick all read it, so it is one list and not four.
@@ -712,25 +760,63 @@ function createApp(options = {}) {
712
760
  *
713
761
  * @param {Array<object>} [byokOverride] rows already fetched by an async
714
762
  * caller, so an awaiting caller does not re-read a cache it just filled.
763
+ * @param {string} [cls] the class to answer FOR. Defaults to the live class,
764
+ * which is what `state().models` wants — but not what `/model` wants.
765
+ *
766
+ * THE CLASS ASKED IS NOT THE CLASS LIVE, and conflating them is what emptied
767
+ * the picker. `mergedPickerModels` (commands.js) asks this module for all
768
+ * three classes in one turn — it opens ONE list containing pooled, byok and
769
+ * Pro rows so a model in another class is reachable without knowing to run
770
+ * `/class` first. Answering every one of those asks from the LIVE class made
771
+ * that merge a lie: on the default `aegis` class the byok ask came back with
772
+ * the pooled rows again (tagged `byok`, so the picker painted Nexus and
773
+ * deepseek twice and the provider ids never at all), and on the `pro` class
774
+ * the pooled ask came back with Pro's aliases — the list a user reads as
775
+ * "only pool and sonnet, where are the rest of my models?". The requested
776
+ * class is the parameter precisely so a caller may ask about a class it is
777
+ * not on; only an absent/unknown `cls` may fall back to the live one.
715
778
  */
716
- function classScopedModels(byokOverride) {
717
- if (commandCtx.modelClass !== 'byok') return pooledRows();
779
+ function classScopedModels(byokOverride, cls) {
780
+ const want = HOST_CLASSES.includes(cls) ? cls : commandCtx.modelClass;
781
+ // The Pro class' list is its own alias set, never the pooled catalog: a
782
+ // pooled id pinned under pro would be sent to `claude --model`, which
783
+ // resolves aliases and real model names, not AEGIS ids — the same
784
+ // cross-class mismatch the byok branch below is shaped to prevent. It is
785
+ // checked before the pooled default for exactly that reason.
786
+ if (want === 'pro') return proRows();
787
+ if (want !== 'byok') return pooledRows();
718
788
  const byok = Array.isArray(byokOverride)
719
789
  ? byokOverride.map((m) => ({ ...m, cls: 'byok' }))
720
790
  : byokRows();
721
791
  return [...pooledRows(), ...byok];
722
792
  }
723
793
 
794
+ /**
795
+ * The ids the Pro class can address: claude-pro.js's PRO_MODELS, lowercased
796
+ * once. Read from the module rather than re-listed, because the transport
797
+ * spawns `claude --model <id>` with these exact strings — a second list here
798
+ * could offer a row the child rejects, which is the cross-class defect the
799
+ * byok rule below is shaped to prevent.
800
+ */
801
+ function proModelIds() {
802
+ return new Set(claudePro.PRO_MODELS.map((m) => String(m.id).toLowerCase()));
803
+ }
804
+
724
805
  /**
725
806
  * Whether a pinned id can run on `cls`, decided synchronously (switchClass is
726
- * not async). byok ids are `provider:model`; aegis takes anything that is
727
- * not — the pooled catalog is validated separately, at launch, by
728
- * validatePinnedModel.
807
+ * not async). byok ids are `provider:model`; aegis and local take anything
808
+ * that is not — the pooled catalog is validated separately, at launch, by
809
+ * validatePinnedModel. pro takes ONLY its own aliases.
729
810
  */
730
811
  function pinBelongsToClass(cls, id) {
731
812
  const s = String(id == null ? '' : id);
732
813
  if (cls === 'byok') return s.includes(':');
733
- // aegis: not a byok id.
814
+ // pro: `claude --model` resolves these aliases and full model names, and
815
+ // AEGIS ids are neither. Without this rule a pooled id ("deepseek") pinned
816
+ // under pro is handed to the child, which fails the turn with a message
817
+ // about a model rather than about the class the user is on.
818
+ if (cls === 'pro') return proModelIds().has(s.toLowerCase());
819
+ // aegis/local: not a byok id.
734
820
  return !s.includes(':');
735
821
  }
736
822
 
@@ -814,6 +900,25 @@ function createApp(options = {}) {
814
900
  );
815
901
  return pinned;
816
902
  }
903
+ // A Pro pin is validated against the child's OWN alias list, locally, and
904
+ // never against the pooled catalog: that catalogue cannot contain these
905
+ // aliases, so checking it here would clear every legitimate Pro pin on every
906
+ // launch. There is no fetch on this path either — the list is a constant, so
907
+ // this is the one class whose validation cannot be defeated by being offline.
908
+ if (commandCtx.modelClass === 'pro') {
909
+ if (proModelIds().has(String(pinned).toLowerCase())) return null;
910
+ commandCtx.model = null;
911
+ updateConfig({ model: null, currentModelId: null });
912
+ emit(
913
+ render.renderNotice(
914
+ ctx(),
915
+ 'warn',
916
+ `pinned model "${pinned}" is not one the Claude Code CLI resolves — pin cleared, ` +
917
+ `the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((m) => m.id).join(', ')}).`
918
+ )
919
+ );
920
+ return pinned;
921
+ }
817
922
  let models;
818
923
  try {
819
924
  models = await loadModels();
@@ -877,6 +982,13 @@ function createApp(options = {}) {
877
982
  let chars = 0;
878
983
  let partial = '';
879
984
  let reasoning = 0;
985
+ // Thinking tokens the PROVIDER measured, added verbatim. A subscription
986
+ // turn withholds its deliberation text (`thinking_delta.thinking` is the
987
+ // empty string), so the `reasoning` char count above stays 0 for the whole
988
+ // thinking phase and the spinner read `↓0 tokens` while thousands of
989
+ // thinking tokens were billed. Not routed through `w()`/4: this is already
990
+ // a token count, and dividing it would print a quarter of the truth.
991
+ let thinkingTokens = 0;
880
992
  let verb = VERBS[Math.floor(Math.random() * VERBS.length)];
881
993
  let sawReasoning = false;
882
994
  let usedTools = false;
@@ -900,7 +1012,10 @@ function createApp(options = {}) {
900
1012
  // distinguishable — but leaving it out of the figure here stalled the
901
1013
  // spinner on `↓0 tokens` for the whole thinking phase of every turn,
902
1014
  // which is the row that exists to show the turn is moving.
903
- streamed: estimateTokensFromCells(chars + reasoning),
1015
+ streamed: estimateTokensFromCells(chars + reasoning) + thinkingTokens,
1016
+ // See render.js: any contribution from `thinkingTokens` is Anthropic's
1017
+ // own under-counting running estimate, not the real billed figure.
1018
+ streamedFloor: thinkingTokens > 0,
904
1019
  }),
905
1020
  ]);
906
1021
  };
@@ -938,6 +1053,13 @@ function createApp(options = {}) {
938
1053
  if (p.reasoning) return p.reasoning(r);
939
1054
  return undefined;
940
1055
  },
1056
+ // Token-count channel, distinct from `reasoning` above (which is text).
1057
+ // A presenter drives its own spinner, so it must receive this or the live
1058
+ // figure stays at 0 for the whole thinking phase of a subscription turn.
1059
+ thinkingTokens: (n) => {
1060
+ if (p.thinkingTokens) return p.thinkingTokens(n);
1061
+ return undefined;
1062
+ },
941
1063
  tool: (tool) => {
942
1064
  if (p.tool) return p.tool(tool);
943
1065
  if (live) live.clear();
@@ -994,6 +1116,19 @@ function createApp(options = {}) {
994
1116
  // same function the tests import is the one the live path calls.
995
1117
  const onDelta = (chunk) => {
996
1118
  if (!chunk) return;
1119
+ // Provider-measured thinking progress — the ONLY live signal on a
1120
+ // subscription turn, whose deliberation text is withheld. Counted and
1121
+ // repainted, but never handed to `present.reasoning`: that channel is
1122
+ // text and its consumers accumulate display width from it.
1123
+ if (chunk.thinkingTokens) {
1124
+ thinkingTokens += chunk.thinkingTokens;
1125
+ if (!sawReasoning) {
1126
+ sawReasoning = true;
1127
+ verb = 'Reasoning';
1128
+ }
1129
+ present.thinkingTokens(chunk.thinkingTokens);
1130
+ paint();
1131
+ }
997
1132
  if (chunk.reasoning) {
998
1133
  reasoning += w(chunk.reasoning);
999
1134
  // The pool's worker findings arrive on the reasoning channel before
@@ -1005,8 +1140,7 @@ function createApp(options = {}) {
1005
1140
  }
1006
1141
  present.reasoning(chunk.reasoning);
1007
1142
  }
1008
- if (chunk.delta) {
1009
- chars += w(chunk.delta);
1143
+ if (chunk.delta) { chars += w(chunk.delta);
1010
1144
  partial += chunk.delta;
1011
1145
  present.text(chunk.delta);
1012
1146
  }
@@ -1064,6 +1198,12 @@ function createApp(options = {}) {
1064
1198
  // `--no-stream` and piped runs get a single body rather than SSE.
1065
1199
  stream: commandCtx.stream !== false,
1066
1200
  sessionId,
1201
+ // The CONVERSATION id, which `sessionId` above is not — that one is
1202
+ // minted fresh for THIS turn so a cancel can target it. Memory that
1203
+ // has to outlive a turn (the Pro class's `claude` child session) is
1204
+ // keyed by this one instead, so a thread keeps its context and
1205
+ // `/new` or `/resume` genuinely starts/continues a different one.
1206
+ sessionKey: commandCtx.sessionId,
1067
1207
  // Opt-in to the round-horizon dialog (see engine.js requestRoundsAsk)
1068
1208
  // only when there is actually a `rounds` prompter to answer it — a
1069
1209
  // one-shot `-p` run or any other caller with no presenter keeps the
@@ -1502,6 +1642,17 @@ function createApp(options = {}) {
1502
1642
  get: () => commandCtx.sessionId,
1503
1643
  set: (v) => { commandCtx.sessionId = v; },
1504
1644
  });
1645
+ // Drop whatever a transport remembered ABOUT this conversation, as opposed
1646
+ // to what this host keeps in `transcript`. `/clear` empties the transcript,
1647
+ // but the Pro class's memory lives in the `claude` child's own session —
1648
+ // reattaching to it afterwards would answer from turns the user just
1649
+ // erased, which reads as the clear having failed. Keyed by session id, the
1650
+ // same id `sessionKey` travels as, so the two cannot drift.
1651
+ c.clearConversationMemory = () => {
1652
+ if (engine && typeof engine.clearSessionApprovals === 'function') {
1653
+ engine.clearSessionApprovals(commandCtx.sessionId);
1654
+ }
1655
+ };
1505
1656
  return c;
1506
1657
  }
1507
1658
 
@@ -1698,7 +1849,7 @@ function createApp(options = {}) {
1698
1849
  err.write(
1699
1850
  `aegiscode: auto-provisioned a free account` +
1700
1851
  (result.ok ? ` (saved to ${credentials.credentialsPath()})` : ' (could not save it — reconfigure with /key)') +
1701
- (result.trialGranted === false ? '. The welcome trial was withheld this hour (too many new devices from this network)' : '') +
1852
+ trialNote(result) +
1702
1853
  `. Fund it at ${client.promptUrl('topup', 'device_autoprovision')} or run /byok to use your own key.\n`
1703
1854
  );
1704
1855
  }
package/src/chatflow.js CHANGED
@@ -54,6 +54,9 @@ const { LineEditor } = require('./input.js');
54
54
  const { renderMarkdown } = require('./markdown.js');
55
55
  const overlays = require('./overlays.js');
56
56
  const models = require('./models.js');
57
+ const { resolveShared } = require('./sharedpaths.js');
58
+ const { validateApiKey } = require(resolveShared(require('node:path').join('client', 'credentials.js')));
59
+ const claudePro = require(resolveShared(require('node:path').join('desktop', 'lib', 'local', 'claude-pro.js')));
57
60
  const fuzzy = require('./fuzzy.js');
58
61
  const { fmtTokens, fmtEur, fmtElapsed, fmtUsageSplit, displayTokens, pathName, feeBillable } = require('./format.js');
59
62
  const { editPreview } = require('./diff.js');
@@ -254,6 +257,61 @@ function historyPairs(rows) {
254
257
  .map((m) => ({ role: m.role, content: m.text }));
255
258
  }
256
259
 
260
+ // A byok "anthropic:<model>" id's model half → the PRO_MODELS alias it reads
261
+ // closest to. 'default' when nothing matches, which is every dated/snapshot
262
+ // id (`claude-sonnet-4-20250514`) as much as a name this table has not been
263
+ // taught — the subscription's own default is a safer landing than guessing
264
+ // wrong.
265
+ const PRO_ALIAS_KEYWORDS = Object.freeze(['opus', 'haiku', 'sonnet']);
266
+
267
+ /**
268
+ * A picked "anthropic:<model>" byok row this machine has no console key for,
269
+ * but IS already signed into Claude Code Pro/Max for, is better served by the
270
+ * subscription it already pays for than by a prompt for a second credential
271
+ * it does not have — `engine.js`'s own refusal message for this exact state
272
+ * already says so ("Use the subscription instead: /class pro"); this is that
273
+ * suggestion applied at pick time instead of left for the user to notice in
274
+ * an error and type a second command.
275
+ *
276
+ * A row with a real console key already stored takes that key, unchanged —
277
+ * the override only fires when `modelKeyPlan` would otherwise have to ask for
278
+ * one. Pure and unit-testable: every fact it needs (whether a key is already
279
+ * stored, whether the subscription is signed in, the PRO_MODELS table) is
280
+ * injected rather than read from a live host/environment.
281
+ *
282
+ * @param {object} chosen a picker row ({id, cls, ...})
283
+ * @param {object} o
284
+ * @param {boolean} o.hasStored the byok provider store already holds an
285
+ * anthropic key (desktop Provider settings / `/byok-key anthropic`)
286
+ * @param {boolean} o.proLoggedIn this machine is signed into Claude Code Pro
287
+ * @param {Array<{id:string,label:string,note:string}>} o.proModels
288
+ * `claudePro.PRO_MODELS`, injected rather than required here
289
+ * @returns {{row:object, message:string|null}} the row to actually pin (the
290
+ * original, unchanged, when the override does not apply) and a note to
291
+ * surface when it does
292
+ */
293
+ function overrideAnthropicByokWithPro(chosen, o = {}) {
294
+ if (!chosen || chosen.cls !== 'byok') return { row: chosen, message: null };
295
+ const id = String(chosen.id || '');
296
+ const colon = id.indexOf(':');
297
+ if (colon < 0 || id.slice(0, colon).trim().toLowerCase() !== 'anthropic') {
298
+ return { row: chosen, message: null };
299
+ }
300
+ if (!o.needsKey) return { row: chosen, message: null }; // a real console key is already usable
301
+ if (!o.proLoggedIn) return { row: chosen, message: null }; // no subscription either — the normal prompt stands
302
+ const modelPart = id.slice(colon + 1).toLowerCase();
303
+ const proModels = Array.isArray(o.proModels) && o.proModels.length ? o.proModels : [{ id: 'default', label: 'Default', note: '' }];
304
+ const aliasId = PRO_ALIAS_KEYWORDS.find((kw) => modelPart.includes(kw)) || 'default';
305
+ const row = proModels.find((m) => m.id === aliasId) || proModels[0];
306
+ return {
307
+ row: { id: row.id, label: row.label, note: row.note, cls: 'pro' },
308
+ message:
309
+ `${id} has no Anthropic console key on this machine, but Claude Code Pro is signed in — ` +
310
+ `using the subscription instead (claude --model ${row.id}). Add a real console key any ` +
311
+ `time with /byok-key anthropic <key> to run this row directly.`,
312
+ };
313
+ }
314
+
257
315
  /**
258
316
  * Palette ranking query for a typed command line: "/memory tiers" must keep
259
317
  * ranking on "memory" so the command stays listed while the user finishes the
@@ -328,7 +386,7 @@ function spinnerLine(state, ctx) {
328
386
  // from the spinner while the model was working.
329
387
  const tail = ctx && ctx.thinking
330
388
  ? span(t.gray, ` (${secs}s · thinking)`)
331
- : span(t.gray, ` (${secs}s · ↓${fmtTokens(state.streamed || 0)} tokens)`);
389
+ : span(t.gray, ` (${secs}s · ↓${state.streamedFloor ? '≥' : ''}${fmtTokens(state.streamed || 0)} tokens)`);
332
390
  const glyph = GLYPH.spin[(state.frame || 0) % GLYPH.spin.length];
333
391
  return [span(t.coral, glyph), ...tinted, span(t.white, '… '), tail];
334
392
  }
@@ -1131,7 +1189,8 @@ async function runSession(host) {
1131
1189
  // Both spinner renderers label this field `tokens`, so handing them
1132
1190
  // cells printed the character count as a token count and the live
1133
1191
  // figure read ~4x high.
1134
- streamed: estimateTokensFromCells(streamedCells()),
1192
+ streamed: estimateTokensFromCells(streamedCells()) + thinkingTokens,
1193
+ streamedFloor: thinkingTokens > 0,
1135
1194
  },
1136
1195
  ctx
1137
1196
  )
@@ -1278,6 +1337,12 @@ async function runSession(host) {
1278
1337
  // reset per turn and never reaches the accounting row, which is built from
1279
1338
  // what the provider measured.
1280
1339
  let streamedChars = 0;
1340
+ // Thinking tokens the PROVIDER measured, added verbatim. `streamedChars` is a
1341
+ // display width that becomes tokens at 4:1, which cannot express this: a
1342
+ // subscription turn sends `thinking_delta.thinking` as the empty string and
1343
+ // reports progress in `estimated_tokens` instead, so the char counter stayed
1344
+ // at 0 for the entire thinking phase while thousands of tokens were billed.
1345
+ let thinkingTokens = 0;
1281
1346
  const streamedCells = () => streamedChars;
1282
1347
  // ── the turn ──
1283
1348
 
@@ -1387,6 +1452,7 @@ async function runSession(host) {
1387
1452
  spinnerFrame = 0;
1388
1453
  startedAt = Date.now();
1389
1454
  streamedChars = 0;
1455
+ thinkingTokens = 0;
1390
1456
  toolSeq = 0;
1391
1457
  turnTools = [];
1392
1458
  verb = VERBS[turnCount % VERBS.length];
@@ -1428,6 +1494,12 @@ async function runSession(host) {
1428
1494
  // nothing needs a different explanation from one that produced nothing at
1429
1495
  // all.
1430
1496
  reasoning: (delta) => { sawReasoning = true; streamedChars += w(delta); },
1497
+ // Provider-measured thinking progress, in tokens. Separate from
1498
+ // `reasoning` above because that one is TEXT (accumulated as display
1499
+ // width, converted at 4:1) and this is already a token count. On a
1500
+ // subscription turn this is the only live signal that arrives during the
1501
+ // thinking phase — the text channel sends empty strings throughout.
1502
+ thinkingTokens: (n) => { sawReasoning = true; thinkingTokens += n; scheduleRender(); },
1431
1503
  tool: (tool) => {
1432
1504
  // One entry per tool call, not one per frame. The engine opens a `run`
1433
1505
  // frame before the tool executes and closes it with a `done` frame
@@ -1994,10 +2066,15 @@ async function runSession(host) {
1994
2066
  return;
1995
2067
  }
1996
2068
  for (const step of queue) {
1997
- // Pooled rows bill the account; a vendor step names its provider. The
1998
- // label says WHICH key is wanted, because two prompts in a row for the
1999
- // same row must not read as the same question asked twice.
2000
- const label = step.role === 'account' ? 'AEGIS account key' : `${step.provider} key`;
2069
+ // Pooled rows bill the account; a vendor step names its provider; the
2070
+ // Claude Code Pro step has neither — it is the subscription's own OAuth
2071
+ // token, minted with `claude setup-token` (or lifted from wherever it is
2072
+ // already set aside). The label says WHICH key is wanted, because two
2073
+ // prompts in a row for the same row must not read as the same question
2074
+ // asked twice.
2075
+ const label = step.role === 'account' ? 'AEGIS account key'
2076
+ : step.role === 'claude-pro' ? 'Claude Code OAuth token (`claude setup-token` mints one)'
2077
+ : `${step.provider} key`;
2001
2078
  const key = String(
2002
2079
  (await c.readSecret(`${label} → ${step.env} (kept off screen, Enter to skip): `)) || ''
2003
2080
  ).trim();
@@ -2008,15 +2085,38 @@ async function runSession(host) {
2008
2085
  note(`no key given — ${step.env} is still unset, so ${chosen.id} will fail until it is.`);
2009
2086
  continue;
2010
2087
  }
2088
+ // Shape check before it ever touches disk: this is the same structural
2089
+ // check the account-key login flow has always had (empty / whitespace /
2090
+ // under 16 chars), now applied here too. Without it a truncated paste
2091
+ // (a 2-char clipboard miss, once landed as a literal ANTHROPIC_API_KEY)
2092
+ // writes straight to .env, reads as "configured" to every status check
2093
+ // that only asks `inFile`, and the row fails upstream on every real turn
2094
+ // with an opaque provider error — "key needed" never shows again because
2095
+ // the picker believes it already has one.
2096
+ const shapeLabel = step.role === 'account' ? 'AEGIS'
2097
+ : step.role === 'claude-pro' ? 'Claude Code OAuth'
2098
+ : step.provider || 'that provider';
2099
+ const shape = validateApiKey(key, { label: shapeLabel });
2100
+ if (!shape.ok) {
2101
+ note(`not saved — ${shape.message}. ${step.env} is still unset.`);
2102
+ continue;
2103
+ }
2011
2104
  // `env: step.env` is what makes a per-step store possible at all: the row
2012
2105
  // alone cannot say which of its two keys this value is for.
2013
- const res = models.storeModelKey(chosen, key, { env: step.env });
2106
+ const res = models.storeModelKey(chosen, shape.key, { env: step.env });
2014
2107
  if (!res.ok) {
2015
2108
  note(`could not save the key: ${res.error || 'unknown error'}`);
2016
2109
  continue;
2017
2110
  }
2111
+ // A foreign secret (CLAUDE_CODE_OAUTH_TOKEN) lands in secrets.env, which
2112
+ // is read explicitly by the one transport that needs it — not loaded
2113
+ // ambiently at start-up the way `.env` is — so it gets its own wording
2114
+ // rather than the "both hosts read that file" line, which is true of
2115
+ // `.env` and would overstate what secrets.env actually does.
2018
2116
  note(res.changed
2019
- ? `${step.env} saved to ${res.file} (0600) — both hosts read that file; nothing to export.`
2117
+ ? res.foreign
2118
+ ? `${step.env} saved to ${res.file} (0600) — read only by the Claude Code Pro transport, never exported.`
2119
+ : `${step.env} saved to ${res.file} (0600) — both hosts read that file; nothing to export.`
2020
2120
  : `${step.env} was already set in ${res.file}.`);
2021
2121
  }
2022
2122
  };
@@ -2032,10 +2132,34 @@ async function runSession(host) {
2032
2132
  */
2033
2133
  const applyModelRow = async (chosen) => {
2034
2134
  if (!chosen) return;
2035
- if (chosen.cls === 'byok' && ctx.modelClass !== 'byok') await dispatch('/class byok');
2135
+ {
2136
+ // Swap an anthropic byok row for the equivalent Claude Code Pro alias
2137
+ // when this machine is signed into the subscription and holds no real
2138
+ // console key — see `overrideAnthropicByokWithPro` (module scope, pure)
2139
+ // for the full reasoning.
2140
+ const plan = models.modelKeyPlan(chosen, {
2141
+ hasStored: host.hasProviderKey ? !!host.hasProviderKey('anthropic') : false,
2142
+ });
2143
+ const { row, message } = overrideAnthropicByokWithPro(chosen, {
2144
+ needsKey: !!(plan && plan.needed),
2145
+ proLoggedIn: models.claudeProLoggedIn(),
2146
+ proModels: claudePro.PRO_MODELS,
2147
+ });
2148
+ chosen = row;
2149
+ if (message) note(message);
2150
+ }
2151
+ // A row that belongs to another class moves the session to that class
2152
+ // BEFORE the pin is stored, for the same reason byok's row does (and it is
2153
+ // the same one-line rule, not a second copy of it): a pro alias pinned while
2154
+ // the session sits on aegis would be sent to the pool as an AEGIS id, and
2155
+ // an AEGIS id pinned under pro would be handed to `claude --model`. Both
2156
+ // fail on the next turn, with a message about a model rather than the class.
2157
+ if (chosen.cls && chosen.cls !== 'aegis' && ctx.modelClass !== chosen.cls) {
2158
+ await dispatch(`/class ${chosen.cls}`);
2159
+ }
2036
2160
  ctx.model = chosen.id;
2037
2161
  host.updateConfig({ model: chosen.id, currentModelId: chosen.id, modelClass: ctx.modelClass });
2038
- note(`model: ${chosen.id}${chosen.cls === 'byok' ? ' (byok)' : ''}`);
2162
+ note(`model: ${chosen.id}${chosen.cls === 'byok' ? ' (byok)' : chosen.cls === 'pro' ? ' (Claude Code Pro)' : ''}`);
2039
2163
  await collectKeyFor(chosen);
2040
2164
  };
2041
2165
 
@@ -2729,6 +2853,7 @@ module.exports = {
2729
2853
  summarizeTurnTools,
2730
2854
  finalizeTurnText,
2731
2855
  historyPairs,
2856
+ overrideAnthropicByokWithPro,
2732
2857
  paletteQuery,
2733
2858
  headerLine,
2734
2859
  separatorLine,