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.
@@ -52,6 +52,11 @@ const toolsModule = require('./tools.js');
52
52
  const promptModule = require('./prompt.js');
53
53
  const localTransport = require('./local.js');
54
54
  const { ShellSession } = require('./shell.js');
55
+ // The Claude Code Pro class' transport (the user's own subscription, spent
56
+ // through the `claude` CLI). Owned by one module — the way local.js owns the
57
+ // loopback transport — so the argv builder, the credential read and the
58
+ // stream-json parser have exactly one implementation and one test surface.
59
+ const claudePro = require('./claude-pro.js');
55
60
  const { agentSystemPrompt, agentRoleLabel } = require('./agents.js');
56
61
  // Cooperative working-tree sharing (see each module's header). The lock
57
62
  // serialises two hosts that start a turn on one checkout close together; the
@@ -389,7 +394,7 @@ const WORKTREE_LOCK_WAIT_MS = 1500;
389
394
  */
390
395
  const MAX_SUBAGENT_DEPTH = 4;
391
396
 
392
- // The three shipping classes — kept in lockstep with the CLI's HOST_CLASSES
397
+ // The four shipping classes — kept in lockstep with the CLI's HOST_CLASSES
393
398
  // (cli/src/engine.js). 'anthropic'/'openai'/'deepseek' still appear in this
394
399
  // file as BYOK *provider* ids: upstream names, never model classes.
395
400
  //
@@ -399,10 +404,16 @@ const MAX_SUBAGENT_DEPTH = 4;
399
404
  // nobody because there is no vendor: the compute was already bought.
400
405
  // Fenced by local.js `remoteRefusal()` — a remote URL here would be
401
406
  // an unpaid turn, which is why that gate exists and fails closed.
407
+ // pro — the user's OWN Claude Code Pro/Max subscription, spent by spawning
408
+ // the `claude` CLI. It reaches no AEGIS endpoint and no vendor API:
409
+ // no baseURL, no key row, no relay, so there is nothing for AEGIS to
410
+ // bill and nothing to meter. See claude-pro.js for why the argv is
411
+ // derived from one/src/child.js rather than written there.
402
412
  const CLASSES = [
403
413
  { class: 'aegis', label: 'Aegis Cloud', kind: 'cloud' },
404
414
  { class: 'byok', label: 'Bring your own key', kind: 'cloud' },
405
415
  { class: 'local', label: 'Local model', kind: 'local' },
416
+ { class: 'pro', label: 'Claude Code Pro', kind: 'subscription' },
406
417
  ];
407
418
 
408
419
  /** Local settings namespace for one BYOK provider's key. The `byok:` prefix
@@ -440,6 +451,46 @@ function splitByokModel(compound) {
440
451
  * where the key came from. The resolution chain (store first, environment
441
452
  * second) belongs to the class that spends the key, which is this one.
442
453
  */
454
+ /**
455
+ * The env-file's own answer for a provider's key, as a RECORD.
456
+ *
457
+ * `providerKeyFromEnv` below deliberately answers with the key alone, which is
458
+ * what every spend site wants. Anything that has to EXPLAIN a keyless row wants
459
+ * the record instead, because the two reasons a provider has no env key look
460
+ * nothing alike to the user:
461
+ *
462
+ * absent nothing supplied one — "paste a key".
463
+ * refused the value supplied cannot be a credential at all. Measured on
464
+ * this machine 2026-10-14: a shell `ANTHROPIC_API_KEY=he` (2
465
+ * characters, a paste that lost its payload) made every
466
+ * `anthropic:*` row read as configured and every turn fail
467
+ * upstream with `{"type":"authentication_error","message":
468
+ * "Invalid bearer token"}`.
469
+ *
470
+ * The second case is the one that sends a user hunting for a new key while the
471
+ * broken two characters sit in the file they are editing, so the reason is
472
+ * carried rather than dropped. client/env-file.js owns the floor and the wording
473
+ * (its `credentialLooksUsable`); this only reads it.
474
+ *
475
+ * @returns {{key: string, env: string, rejected: string|null}}
476
+ */
477
+ function providerKeyRecord(provider) {
478
+ const empty = { key: '', env: '', rejected: null };
479
+ if (!envFile || typeof envFile.providerKeyFromEnv !== 'function') return empty;
480
+ try {
481
+ const rec = envFile.providerKeyFromEnv(provider) || empty;
482
+ return {
483
+ key: typeof rec.key === 'string' ? rec.key : '',
484
+ env: typeof rec.env === 'string' ? rec.env : '',
485
+ rejected: typeof rec.rejected === 'string' && rec.rejected ? rec.rejected : null,
486
+ };
487
+ } catch {
488
+ // A host whose env module predates the record (or whose file is unreadable)
489
+ // degrades to "no key", which is exactly what the string accessor does.
490
+ return empty;
491
+ }
492
+ }
493
+
443
494
  function providerKeyFromEnv(provider) {
444
495
  if (!envFile || typeof envFile.providerKeyFromEnv !== 'function') return '';
445
496
  try {
@@ -692,6 +743,51 @@ function extractToolCalls(res) {
692
743
  }
693
744
 
694
745
  /** The textual content of one assistant turn (empty when it only called tools). */
746
+ /**
747
+ * The prompt a Pro turn actually hands the child.
748
+ *
749
+ * `pro` is the one class that does not replay `opts.messages` into its
750
+ * transport: the `claude` child runs its own agent loop, so sending this
751
+ * engine's transcript would make it re-run every tool call a second time. That
752
+ * decision is right for an ordinary turn and silently wrong for the engine's
753
+ * RE-ASK rounds — the synthesis pass and the recovery ladder both re-dispatch
754
+ * with `prompt: ''` plus a grown `messages`, which is the shape every other
755
+ * class reads as "continue this conversation; the new instruction is the last
756
+ * user message in the history". The Pro branch read only `opts.prompt`, so each
757
+ * of those rounds spawned `claude -p ''`: an empty prompt, on a child whose
758
+ * stdin is `'ignore'`, with `--resume` as its only other context.
759
+ *
760
+ * The consequence was the failure this function exists to prevent. A Pro turn
761
+ * whose first round came back empty could never be recovered, because every
762
+ * recovery round was guaranteed empty too — the ladder then reported "2 extra
763
+ * recovery calls with a larger budget and a changed ask came back empty too"
764
+ * over a transport that had been asked nothing at all. Measured on
765
+ * claude-code-pro, 2026-10-11.
766
+ *
767
+ * So when a round carries no prompt of its own, the LAST user message in
768
+ * `opts.messages` becomes the child's prompt. The nudges the ladder appends are
769
+ * exactly that, and `--resume` reattaches the child to its own session, so the
770
+ * instruction lands in a conversation that already holds the findings — which
771
+ * is what makes the recovery round a re-ask rather than a fresh, empty one.
772
+ *
773
+ * An ordinary turn is untouched: it has its own prompt, so the first branch
774
+ * returns before `messages` is ever consulted.
775
+ */
776
+ function proTurnPrompt(opts) {
777
+ const own = typeof opts.prompt === 'string' ? opts.prompt.trim() : '';
778
+ if (own) return opts.prompt;
779
+ const messages = Array.isArray(opts.messages) ? opts.messages : [];
780
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
781
+ const m = messages[i];
782
+ if (!m || m.role !== 'user') continue;
783
+ if (typeof m.content === 'string' && m.content.trim()) return m.content;
784
+ }
785
+ // Nothing to borrow: keep the caller's own value rather than inventing text,
786
+ // so a round with genuinely no ask still reaches the ladder and is reported
787
+ // as the empty round it is.
788
+ return opts.prompt;
789
+ }
790
+
695
791
  function assistantText(res) {
696
792
  const msg = res && res.choices && res.choices[0] && res.choices[0].message;
697
793
  return (msg && typeof msg.content === 'string' && msg.content) || '';
@@ -757,6 +853,42 @@ function reasoningTextOf(res) {
757
853
  return '';
758
854
  }
759
855
 
856
+ /**
857
+ * Deliberation the provider MEASURED but withheld, in tokens.
858
+ *
859
+ * The companion to `reasoningTextOf()` above, for the one case where there is no
860
+ * text to read: Claude Code Pro runs extended thinking by default and withholds
861
+ * the deliberation itself, so `thinking_delta.thinking` arrives as the empty
862
+ * string while the billed count climbs. A round like that carries real reasoning
863
+ * and no reasoning TEXT, so a text-only predicate reads it as "the model said
864
+ * nothing" — the wrong diagnosis, and the one that made a Pro turn report
865
+ * "No visible text came back" while the child had in fact been thinking.
866
+ *
867
+ * Read from the message shape first (what `claude-pro.js` `proMessage()` sets)
868
+ * and then from the standard usage detail `completion_tokens_details.
869
+ * reasoning_tokens`, so a provider that meters deliberation on the usage
870
+ * envelope is seen too.
871
+ */
872
+ function reasoningTokensOf(res) {
873
+ if (!res) return 0;
874
+ const choice = res.choices && res.choices[0];
875
+ const msg = (choice && choice.message) || {};
876
+ const usage = res.usage || {};
877
+ const details = usage.completion_tokens_details || usage.output_tokens_details || {};
878
+ const candidates = [
879
+ msg.thinking_tokens,
880
+ msg.reasoning_tokens,
881
+ choice && choice.thinking_tokens,
882
+ res.thinking_tokens,
883
+ details.reasoning_tokens,
884
+ details.thinking_tokens,
885
+ ];
886
+ for (const c of candidates) {
887
+ if (typeof c === 'number' && Number.isFinite(c) && c > 0) return c;
888
+ }
889
+ return 0;
890
+ }
891
+
760
892
  /**
761
893
  * The empty turn `isTruncated()` cannot see, and the reason this error survived
762
894
  * a truncation retry that was already in place: a reasoning model that spends
@@ -767,9 +899,14 @@ function reasoningTextOf(res) {
767
899
  * `reasoning_content`, which fell straight through both retry gates to
768
900
  * emptyTurnError. Reasoning tokens and answer tokens share one budget, so the
769
901
  * recovery is identical to a 'length' cut: buy room and ask once more.
902
+ *
903
+ * A round with no reasoning TEXT but a non-zero reasoning-token count counts as
904
+ * reasoning here: that is a Pro turn whose deliberation was withheld, and
905
+ * treating it as genuinely empty is what sent it to the generic nudge instead
906
+ * of the ask that names the problem.
770
907
  */
771
908
  function reasonedButSilent(res) {
772
- return !assistantText(res) && reasoningTextOf(res) !== '';
909
+ return !assistantText(res) && (reasoningTextOf(res) !== '' || reasoningTokensOf(res) > 0);
773
910
  }
774
911
 
775
912
  /**
@@ -928,8 +1065,20 @@ const RECOVERY_ROUNDS = 2;
928
1065
  * real tool log on screen, keeps the transcript honest, and names the cause
929
1066
  * (renderer prints `Error: <message>`).
930
1067
  */
931
- function emptyTurnError({ cls, model, finishReason, reasoningChars, effort, recoveryRounds }) {
1068
+ function emptyTurnError({ cls, model, finishReason, reasoningChars, reasoningTokens, effort, recoveryRounds }) {
932
1069
  const calls = Number(recoveryRounds) || 0;
1070
+ // A withheld deliberation has no chars to count, so the two signals are
1071
+ // reported as the one fact they both are: the round spent its output on
1072
+ // thinking. Without this the Pro case printed "No visible text came back from
1073
+ // any of those calls", which describes a transport that produced nothing —
1074
+ // the opposite of a child that reasoned at length and wrote no answer.
1075
+ const tokens = Number(reasoningTokens) || 0;
1076
+ const reasoned = !!reasoningChars || tokens > 0;
1077
+ const reasonClause = reasoningChars
1078
+ ? `, hidden reasoning: ${reasoningChars} chars and no visible text`
1079
+ : tokens > 0
1080
+ ? `, ~${tokens} thinking tokens billed and no visible text`
1081
+ : '';
933
1082
  const err = new Error(
934
1083
  `The model returned no answer after ${cls}/${model} was asked to summarise its results` +
935
1084
  (calls
@@ -938,8 +1087,8 @@ function emptyTurnError({ cls, model, finishReason, reasoningChars, effort, reco
938
1087
  : '') +
939
1088
  ` (stop reason: ${finishReason || 'none'}` +
940
1089
  `${effort ? `, effort: ${effort}` : ''}` +
941
- `${reasoningChars ? `, hidden reasoning: ${reasoningChars} chars and no visible text` : ''}). ` +
942
- (reasoningChars
1090
+ `${reasonClause}). ` +
1091
+ (reasoned
943
1092
  ? // Deliberately NOT "raise the Effort rung". The budget was already taken
944
1093
  // out of the equation before this error could be reached: the recovery
945
1094
  // calls above ran at the top of the ladder, so pointing at the ceiling
@@ -985,6 +1134,10 @@ function createLocalEngine({
985
1134
  // not the transport — discovery is an outbound call to api.<vendor>, not to
986
1135
  // the AEGIS relay. Undefined in production, which means the global fetch.
987
1136
  fetchImpl,
1137
+ // Injectable for tests, like `localTransport` above: the git half of the Pro
1138
+ // child's sandbox widening (proAddDirs). Production passes nothing and the
1139
+ // real `./git-scope.js` is resolved at call time.
1140
+ gitScope,
988
1141
  }) {
989
1142
  const controllers = new Map(); // sessionId -> AbortController
990
1143
  const T = tools || toolsModule;
@@ -1034,6 +1187,22 @@ function createLocalEngine({
1034
1187
  // gate that only remembers "yes" turns a single click into a retry storm;
1035
1188
  // remembering "no" makes the first answer stick.
1036
1189
  const sessionDenials = new Map(); // rootSessionId -> Set<toolName>
1190
+ // ── Pro-class conversation continuity ────────────────────────────────────
1191
+ //
1192
+ // `claude` keeps its own session store, and the Pro child is spawned fresh
1193
+ // for every turn. Continuity therefore has to be carried by US: the session
1194
+ // id the child reports is remembered here, keyed by the CONVERSATION's root
1195
+ // session id, and handed back as `--resume` on the next turn. Without this
1196
+ // map every Pro turn is a brand-new conversation — the child is told nothing
1197
+ // about the prior turns, because `pro` has no `messages` channel (the child
1198
+ // runs its own agent loop), so "Claude has no memory of this conversation"
1199
+ // was literally true.
1200
+ //
1201
+ // Keyed by root, like the allowlists above: one thread, one memory. In-memory
1202
+ // only, and cleared by the same newChat()/`/clear` hook that clears the gate,
1203
+ // because "clear the conversation" must clear what the child remembers too —
1204
+ // a resumed child would otherwise answer from turns the user just erased.
1205
+ const proSessions = new Map(); // rootSessionId -> child session UUID
1037
1206
  const pendingApprovals = new Map(); // approvalId -> { resolve }
1038
1207
  const pendingRoundAsks = new Map(); // askId -> { resolve }
1039
1208
 
@@ -1085,6 +1254,10 @@ function createLocalEngine({
1085
1254
  function clearSessionApprovals(rootSessionId) {
1086
1255
  sessionAllowlists.delete(rootSessionId);
1087
1256
  sessionDenials.delete(rootSessionId);
1257
+ // And the Pro child's memory of the conversation, for the same reason: a
1258
+ // new chat (or `/clear`) that left the child resumed would let it answer
1259
+ // from turns the user just deleted, which looks like the clear failed.
1260
+ proSessions.delete(rootSessionId);
1088
1261
  return { ok: true };
1089
1262
  }
1090
1263
 
@@ -1389,8 +1562,18 @@ function createLocalEngine({
1389
1562
  // something", which is what an unconfigured row would say.
1390
1563
  return { ...c, configured: true };
1391
1564
  }
1392
- // Unreachable while CLASSES lists only aegis + byok + local; kept so a
1393
- // future class added without a status rule reads as unconfigured rather
1565
+ if (c.class === 'pro') {
1566
+ // Configured means "there is a Claude Code subscription to spend": a
1567
+ // credential file with a token in it. Deliberately NOT gated on the
1568
+ // `claude` binary being on PATH as well — that is a separate state with
1569
+ // its own remedy, and folding the two together would answer "sign in"
1570
+ // to someone who is signed in and merely missing the CLI.
1571
+ const status = claudePro.claudeProStatus({ env: process.env });
1572
+ const seam = claudePro.seamAvailable();
1573
+ return { ...c, configured: status.loggedIn, status, seam };
1574
+ }
1575
+ // Unreachable while CLASSES lists only aegis + byok + local + pro; kept so
1576
+ // a future class added without a status rule reads as unconfigured rather
1394
1577
  // than silently appearing ready (the "no saved key" fallback shape).
1395
1578
  return { ...c, configured: false };
1396
1579
  });
@@ -1465,7 +1648,8 @@ function createLocalEngine({
1465
1648
  // on, and the one the renderer's per-provider rows mirror. Reporting it
1466
1649
  // unconfigured while `chat()` happily spends the env key is exactly the
1467
1650
  // "no saved key" contradiction this file removes.
1468
- const fromEnv = providerKeyFromEnv(p.id);
1651
+ const envRec = providerKeyRecord(p.id);
1652
+ const fromEnv = envRec.key || '';
1469
1653
  const rawModels = Array.isArray(p.models) ? p.models : [];
1470
1654
  for (const m of rawModels) {
1471
1655
  const modelId = typeof m === 'string' ? m : m && m.id;
@@ -1475,6 +1659,12 @@ function createLocalEngine({
1475
1659
  label: `${p.label || p.id} — ${modelId}`,
1476
1660
  provider: p.id,
1477
1661
  configured: Boolean(rowCfg.configured || fromEnv),
1662
+ // Why a row with no usable key is keyless, when the env file refused
1663
+ // the value it was given rather than never being given one. Carried
1664
+ // on the row because the renderer's per-provider line is the only
1665
+ // place the user can see it before they send a turn. Null when there
1666
+ // is nothing to explain (a saved key, or no env value at all).
1667
+ keyRejected: envRec.rejected || null,
1478
1668
  });
1479
1669
  }
1480
1670
  }
@@ -1512,14 +1702,46 @@ function createLocalEngine({
1512
1702
  }
1513
1703
  return { class: cls, models: tags, baseURL: status.baseURL, listed };
1514
1704
  }
1515
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok' and
1516
- // 'local', all returned above. Thrown rather than falling through to an
1705
+ if (cls === 'pro') {
1706
+ // The model list is the CLI's OWN aliases. The subscription does not
1707
+ // expose an id list this process may query, and inventing full model
1708
+ // names here would be exactly the "client names a model the transport
1709
+ // cannot address" defect — `claude --model` takes these aliases, so these
1710
+ // are the rows (claude-pro.js PRO_MODELS).
1711
+ const status = claudePro.claudeProStatus({ env: process.env });
1712
+ const models = claudePro.PRO_MODELS.map((m) => ({
1713
+ id: m.id,
1714
+ label: m.label,
1715
+ note: m.note,
1716
+ configured: status.loggedIn,
1717
+ }));
1718
+ return {
1719
+ class: cls,
1720
+ models,
1721
+ // Nothing to key: the subscription IS the credential, and there is no
1722
+ // AEGIS spend on this class for the relay's balance gate to consider.
1723
+ needsProviderKey: false,
1724
+ needsAegisKey: false,
1725
+ subscription: status.subscription,
1726
+ loggedIn: status.loggedIn,
1727
+ credentialFile: status.file,
1728
+ // A shell `ANTHROPIC_API_KEY` too short to be a credential makes the CLI
1729
+ // prefer that name over the subscription, so a signed-in machine ran
1730
+ // turns as "API key: he". The child is fixed either way (claude-pro.js
1731
+ // childEnvPlan); reported here so the picker can name the var instead of
1732
+ // leaving it to be discovered from `claude auth status` by hand.
1733
+ shadowed: status.shadowed || null,
1734
+ seam: claudePro.seamAvailable(),
1735
+ };
1736
+ }
1737
+ // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
1738
+ // and 'pro', all returned above. Thrown rather than falling through to an
1517
1739
  // empty list, because "no models" is a state the renderer renders as a
1518
1740
  // normal empty picker — an unknown class would look like a
1519
1741
  // configured-but-empty account instead of the bug it is. Same shape as
1520
1742
  // dispatch's tail.
1521
1743
  throw new Error(
1522
- `listModels: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok' and 'local' only`
1744
+ `listModels: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
1523
1745
  );
1524
1746
  }
1525
1747
 
@@ -1531,6 +1753,64 @@ function createLocalEngine({
1531
1753
  return hostEnv(env || {}, (payload && payload.env) || {}, payload);
1532
1754
  }
1533
1755
 
1756
+ /**
1757
+ * The directories the Claude Pro child is additionally allowed to work in,
1758
+ * for a turn running in `cwd` — the Pro path's half of "the model is not
1759
+ * walled into one subdirectory".
1760
+ *
1761
+ * Two candidates, and only two:
1762
+ *
1763
+ * · the repository root, from `git-scope.js` — the module the turn guard and
1764
+ * the queue already share, so "where does this work happen" is answered in
1765
+ * one place rather than re-derived here;
1766
+ * · the project data directory (`$AEGISCODE_HOME`, else `~/.aegiscode`),
1767
+ * because a turn asked to look at its own session/queue/memory files is
1768
+ * otherwise asked to read a path outside its sandbox — the second real
1769
+ * report of this wall.
1770
+ *
1771
+ * Resolved at CALL time, not at load: `git-scope.js` is staged beside this
1772
+ * file in both layouts (one/scripts/predist.mjs), and a checkout that has not
1773
+ * been staged must still load the engine. A missing module therefore degrades
1774
+ * to "no widening", which is the pre-existing behaviour — never to a second,
1775
+ * local implementation of git root discovery.
1776
+ *
1777
+ * Deduplicated against `cwd` itself: telling the child that its own working
1778
+ * directory is also an extra directory is noise in the argv, in the record and
1779
+ * in the run-log line, and noise is where a real widening hides.
1780
+ */
1781
+ function proAddDirs(cwd) {
1782
+ const out = [];
1783
+ // Separator-normalised comparison only — this file deliberately does not
1784
+ // grow a `node:path` dependency at module scope for two string checks, and
1785
+ // both candidates arrive absolute from modules that already resolved them.
1786
+ const norm = (p) => String(p || '').replace(/[\\/]+$/, '');
1787
+ const here = norm(cwd);
1788
+ const add = (dir) => {
1789
+ const abs = norm(dir);
1790
+ if (!abs || abs === here || out.includes(abs)) return;
1791
+ out.push(abs);
1792
+ };
1793
+ let scope = gitScope;
1794
+ if (scope === undefined) {
1795
+ try {
1796
+ scope = require('./git-scope.js');
1797
+ } catch {
1798
+ scope = null;
1799
+ }
1800
+ }
1801
+ try {
1802
+ if (scope && typeof scope.gitRoot === 'function') add(scope.gitRoot(cwd));
1803
+ } catch {
1804
+ /* not a repo, or git is absent: no wider tree to grant */
1805
+ }
1806
+ try {
1807
+ if (credentialsLib && typeof credentialsLib.aegisHome === 'function') add(credentialsLib.aegisHome());
1808
+ } catch {
1809
+ /* no data directory resolved: nothing to add */
1810
+ }
1811
+ return out;
1812
+ }
1813
+
1534
1814
  /** One transport round for the chosen class. */
1535
1815
  async function dispatch(cls, opts) {
1536
1816
  if (cls === 'aegis') {
@@ -1696,6 +1976,12 @@ function createLocalEngine({
1696
1976
  provider,
1697
1977
  model: bareModel,
1698
1978
  providerKey: opts.apiKey,
1979
+ // Only meaningful for provider "custom" (aegis1 reads it ONLY on
1980
+ // that id) — forwarded unconditionally anyway, same as the other
1981
+ // fields above, rather than special-cased per provider here.
1982
+ // `cfg` is this provider's settings row (byokNamespace(provider)),
1983
+ // the same row /byok-key and /model-add write.
1984
+ baseURL: opts.cfg && opts.cfg.baseURL,
1699
1985
  prompt: opts.prompt,
1700
1986
  system: opts.system,
1701
1987
  messages: opts.messages,
@@ -1780,12 +2066,106 @@ function createLocalEngine({
1780
2066
  }
1781
2067
  }
1782
2068
 
1783
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok' and
1784
- // 'local', all returned above. Thrown rather than falling through to a
2069
+ if (cls === 'pro') {
2070
+ // The user's own Claude subscription. This transport is unlike the other
2071
+ // three in a way that decides its whole shape: the `claude` child runs
2072
+ // its OWN agent loop, with its own tools, so there is no `tools` argument
2073
+ // to send and none is invented — passing this engine's schemas would ask
2074
+ // a process that already has a tool loop to re-run our tools inside it.
2075
+ // `opts.messages`/`opts.tools` are deliberately unused here for that
2076
+ // reason, and the dispatch returns the child's own final answer.
2077
+ //
2078
+ // ── … and the consequence of that, which used to be a bug ─────────────
2079
+ //
2080
+ // Because the transcript is NOT replayed into the child, the child's own
2081
+ // session store was the only thing that could carry context between
2082
+ // turns — and nothing ever told it to resume one. Every turn was a
2083
+ // brand-new conversation: "Claude has no memory of this conversation"
2084
+ // was literally true, and no amount of `messages` upstream could fix it,
2085
+ // because they were dropped on purpose one paragraph above.
2086
+ //
2087
+ // So the child's reported session id is remembered per CONVERSATION and
2088
+ // handed back as `--resume`. Keyed by the conversation (rootSessionId),
2089
+ // never by `sessionId`: the CLI mints a fresh uuid per turn for
2090
+ // cancellation, so keying by it would resume nothing, every turn.
2091
+ //
2092
+ // We deliberately do NOT pass `sessionId` (`--session-id`) to name the
2093
+ // conversation upfront: the CLI's own `/new` mints `aegis-xxxxxxxx`,
2094
+ // which is not a UUID the child accepts, and the child's self-minted id
2095
+ // is authoritative anyway. It is read back off the `result` line instead.
2096
+ const convKey = opts.sessionKey || opts.rootSessionId || opts.sessionId;
2097
+ const remembered = convKey ? proSessions.get(convKey) : null;
2098
+ // ── the sandbox the child is actually given ───────────────────────────
2099
+ //
2100
+ // A headless `claude` child resolves every relative path and every tool's
2101
+ // root against the directory it was spawned in, so a turn started in a
2102
+ // SUBDIRECTORY of the repo cannot read or run anything above it. Reported
2103
+ // from this product for real: a session launched in `cli/` that needed
2104
+ // `test/` came back with "I can't run outside the sandboxed directory
2105
+ // `cli/`" — the model, not a bug in the tools, describing this boundary.
2106
+ //
2107
+ // The repo root is the right width: it is the tree the user opened, it is
2108
+ // one directory (never a glob, never the home dir), and it is derived
2109
+ // rather than guessed — `git-scope.js` is the module the turn guard and
2110
+ // the queue already ask for "where is this work happening". Best-effort:
2111
+ // outside a repo there is no wider directory to grant and the child keeps
2112
+ // exactly the posture it had.
2113
+ // The turn's own working directory rides on `opts.cwd` (threaded in by
2114
+ // `chat()` as `turnCwd`), never on the enclosing scope's local — that
2115
+ // reference is the exact `ReferenceError: turnCwd is not defined` this
2116
+ // file already carries a regression case for.
2117
+ const addDir = proAddDirs(opts.cwd);
2118
+ //
2119
+ // The permission half of the argv is NOT built here. It comes from
2120
+ // resolvePosture() inside runClaudePro, through the one argv builder
2121
+ // (one/src/child.js), so this host and AEGISONE's faces cannot disagree
2122
+ // about what the child was allowed to do.
2123
+ const proRes = await claudePro.runClaudePro({
2124
+ // The re-ask round's instruction, when this round has none of its own.
2125
+ // See proTurnPrompt(): without it every recovery round spawned the
2126
+ // child with an empty prompt and the turn could never be recovered.
2127
+ prompt: proTurnPrompt(opts),
2128
+ model: opts.model && opts.model !== 'default' ? opts.model : undefined,
2129
+ system: opts.system,
2130
+ cwd: opts.cwd,
2131
+ // The widened sandbox, threaded through to the ONE argv builder. A
2132
+ // directory the engine could not derive (or that adds nothing, e.g. the
2133
+ // turn already runs at the repo root) is simply absent from this list,
2134
+ // and absent means "exactly the posture the child had before".
2135
+ addDir,
2136
+ // Carry the conversation, if we have one to carry.
2137
+ resumeSessionId: remembered || undefined,
2138
+ // The stored posture this host already reads for its own gate, handed
2139
+ // to the resolver rather than re-read there — one answer per turn.
2140
+ gate: typeof getConfirmMode === 'function' ? !getConfirmMode() : undefined,
2141
+ signal: opts.signal,
2142
+ onDelta: opts.onDelta,
2143
+ onSpawn: (child, record) => {
2144
+ // Rule 4's "recorded, never inferred": the child's real flags are
2145
+ // reported on the same channel tool activity uses, so a Pro turn's
2146
+ // transcript shows what it was allowed to do.
2147
+ if (opts.onDelta && record) {
2148
+ opts.onDelta({ delta: '', note: claudePro.childLine(record) });
2149
+ }
2150
+ void child;
2151
+ },
2152
+ });
2153
+ // Remember the id the child reported, so the NEXT turn in this thread
2154
+ // resumes this conversation. Recorded only on a turn that actually
2155
+ // produced one: a failed turn must not overwrite a good id with
2156
+ // `undefined` and silently turn the next turn into a new conversation.
2157
+ if (convKey && proRes && proRes.sessionId && !proRes.error) {
2158
+ proSessions.set(convKey, proRes.sessionId);
2159
+ }
2160
+ return proRes;
2161
+ }
2162
+
2163
+ // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
2164
+ // and 'pro', all returned above. Thrown rather than falling through to a
1785
2165
  // default transport, because a class that silently borrows another's wire
1786
2166
  // format is this file's recurring failure mode.
1787
2167
  throw new Error(
1788
- `dispatch: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok' and 'local' only`
2168
+ `dispatch: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
1789
2169
  );
1790
2170
  }
1791
2171
 
@@ -1932,9 +2312,39 @@ function createLocalEngine({
1932
2312
  throw err;
1933
2313
  }
1934
2314
  if (cls === 'byok' && !apiKey) {
2315
+ // Anthropic is the one provider with a SECOND, non-API route, and it is
2316
+ // the one a user with a Claude subscription actually owns. Pinning
2317
+ // `anthropic:claude-sonnet-5` is a promise that this machine has a
2318
+ // console API key for api.anthropic.com; a Pro/Max subscription is NOT
2319
+ // one and is deliberately not usable as one (claude-pro.js's own
2320
+ // header). So when the machine holds a subscription and no usable
2321
+ // anthropic key, the honest instruction is the Pro class — it spends
2322
+ // the subscription they already pay for instead of a key they do not
2323
+ // have. Checked through claudeProStatus() rather than by looking for a
2324
+ // token here, so this message and the picker cannot disagree about
2325
+ // whether a subscription is present.
2326
+ const pro = byokParts.provider === 'anthropic' ? claudePro.claudeProStatus({ env: process.env }) : null;
2327
+ // A key the env file REFUSED outranks both of the messages below. The
2328
+ // generic "no key yet" tells a user to go paste one, which is the wrong
2329
+ // instruction when the file already holds a value that cannot be a
2330
+ // credential: they will paste the same broken thing again, or conclude
2331
+ // their account is broken. This is the exact state that produced an
2332
+ // upstream `{"type":"authentication_error","message":"Invalid bearer
2333
+ // token"}` and read to the user as "Anthropic auth failed".
2334
+ const refused = providerKeyRecord(byokParts.provider).rejected;
1935
2335
  const err = new Error(
1936
- `No key for "${byokParts.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, ` +
1937
- `no setup) — or add this provider's own key: /byok-key ${byokParts.provider} <key>.`
2336
+ refused
2337
+ ? `${refused}. That is why this turn has no ${byokParts.provider} key: an env value ` +
2338
+ `that short is a paste that lost its payload, not a credential. Fix ${refused.split(' ')[0]} ` +
2339
+ `in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: ` +
2340
+ `/byok-key ${byokParts.provider} <key> to set one here.`
2341
+ : pro && pro.loggedIn
2342
+ ? `No Anthropic API key on this machine — an "anthropic:…" id is served by your own ` +
2343
+ `console key, which a Claude subscription is not. Use the subscription instead: ` +
2344
+ `/class pro (it spends your Claude Code ${pro.subscription || 'Pro'} plan through the ` +
2345
+ `claude CLI) — or add a real console key: /byok-key anthropic <key>.`
2346
+ : `No key for "${byokParts.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, ` +
2347
+ `no setup) — or add this provider's own key: /byok-key ${byokParts.provider} <key>.`
1938
2348
  );
1939
2349
  err.status = 400;
1940
2350
  throw err;
@@ -1978,6 +2388,20 @@ function createLocalEngine({
1978
2388
  }
1979
2389
  const base = {
1980
2390
  cls, model, mode: payload && payload.mode, maxTokens, statedMaxTokens, autonomous, sessionId, signal, onDelta, cfg, apiKey, toolChoice,
2391
+ // The turn's working directory, computed above as `turnCwd` — `dispatch`
2392
+ // is its own function, not a closure over `chat`'s locals, so the 'pro'
2393
+ // branch (the only one that spawns a child in a directory) needs it
2394
+ // threaded through here rather than reaching for the enclosing scope's
2395
+ // variable, which does not exist from inside `dispatch`.
2396
+ cwd: turnCwd,
2397
+ // The CONVERSATION's identity, distinct from `sessionId` (which both
2398
+ // hosts mint fresh per TURN — the CLI in ask(), for cancellation).
2399
+ // Continuity that must outlive one turn is keyed by these, never by
2400
+ // `sessionId`: the Pro child's remembered session is one per open
2401
+ // thread, so keying it by a per-turn id would start a new child
2402
+ // conversation every single turn and look exactly like no memory.
2403
+ rootSessionId,
2404
+ sessionKey: (payload && payload.sessionKey) || undefined,
1981
2405
  effort: payload && payload.effort,
1982
2406
  workers: payload && payload.workers,
1983
2407
  // Deep recall (`aegis_recall_deep`) is an explicit per-session opt-in
@@ -2454,6 +2878,10 @@ function createLocalEngine({
2454
2878
  recoveryRounds,
2455
2879
  finishReason: finishReasonOf(res),
2456
2880
  reasoningChars: reasoningTextOf(res).length,
2881
+ // The withheld-deliberation case (a Pro turn with extended
2882
+ // thinking on): no chars to count, but the provider billed the
2883
+ // thinking. Without this the report claims nothing came back.
2884
+ reasoningTokens: reasoningTokensOf(res),
2457
2885
  });
2458
2886
  }
2459
2887
  return withTurnUsage(res);