aegiscode 7.0.6 → 7.0.8

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 {
@@ -985,6 +1036,10 @@ function createLocalEngine({
985
1036
  // not the transport — discovery is an outbound call to api.<vendor>, not to
986
1037
  // the AEGIS relay. Undefined in production, which means the global fetch.
987
1038
  fetchImpl,
1039
+ // Injectable for tests, like `localTransport` above: the git half of the Pro
1040
+ // child's sandbox widening (proAddDirs). Production passes nothing and the
1041
+ // real `./git-scope.js` is resolved at call time.
1042
+ gitScope,
988
1043
  }) {
989
1044
  const controllers = new Map(); // sessionId -> AbortController
990
1045
  const T = tools || toolsModule;
@@ -1034,6 +1089,22 @@ function createLocalEngine({
1034
1089
  // gate that only remembers "yes" turns a single click into a retry storm;
1035
1090
  // remembering "no" makes the first answer stick.
1036
1091
  const sessionDenials = new Map(); // rootSessionId -> Set<toolName>
1092
+ // ── Pro-class conversation continuity ────────────────────────────────────
1093
+ //
1094
+ // `claude` keeps its own session store, and the Pro child is spawned fresh
1095
+ // for every turn. Continuity therefore has to be carried by US: the session
1096
+ // id the child reports is remembered here, keyed by the CONVERSATION's root
1097
+ // session id, and handed back as `--resume` on the next turn. Without this
1098
+ // map every Pro turn is a brand-new conversation — the child is told nothing
1099
+ // about the prior turns, because `pro` has no `messages` channel (the child
1100
+ // runs its own agent loop), so "Claude has no memory of this conversation"
1101
+ // was literally true.
1102
+ //
1103
+ // Keyed by root, like the allowlists above: one thread, one memory. In-memory
1104
+ // only, and cleared by the same newChat()/`/clear` hook that clears the gate,
1105
+ // because "clear the conversation" must clear what the child remembers too —
1106
+ // a resumed child would otherwise answer from turns the user just erased.
1107
+ const proSessions = new Map(); // rootSessionId -> child session UUID
1037
1108
  const pendingApprovals = new Map(); // approvalId -> { resolve }
1038
1109
  const pendingRoundAsks = new Map(); // askId -> { resolve }
1039
1110
 
@@ -1085,6 +1156,10 @@ function createLocalEngine({
1085
1156
  function clearSessionApprovals(rootSessionId) {
1086
1157
  sessionAllowlists.delete(rootSessionId);
1087
1158
  sessionDenials.delete(rootSessionId);
1159
+ // And the Pro child's memory of the conversation, for the same reason: a
1160
+ // new chat (or `/clear`) that left the child resumed would let it answer
1161
+ // from turns the user just deleted, which looks like the clear failed.
1162
+ proSessions.delete(rootSessionId);
1088
1163
  return { ok: true };
1089
1164
  }
1090
1165
 
@@ -1389,8 +1464,18 @@ function createLocalEngine({
1389
1464
  // something", which is what an unconfigured row would say.
1390
1465
  return { ...c, configured: true };
1391
1466
  }
1392
- // Unreachable while CLASSES lists only aegis + byok + local; kept so a
1393
- // future class added without a status rule reads as unconfigured rather
1467
+ if (c.class === 'pro') {
1468
+ // Configured means "there is a Claude Code subscription to spend": a
1469
+ // credential file with a token in it. Deliberately NOT gated on the
1470
+ // `claude` binary being on PATH as well — that is a separate state with
1471
+ // its own remedy, and folding the two together would answer "sign in"
1472
+ // to someone who is signed in and merely missing the CLI.
1473
+ const status = claudePro.claudeProStatus({ env: process.env });
1474
+ const seam = claudePro.seamAvailable();
1475
+ return { ...c, configured: status.loggedIn, status, seam };
1476
+ }
1477
+ // Unreachable while CLASSES lists only aegis + byok + local + pro; kept so
1478
+ // a future class added without a status rule reads as unconfigured rather
1394
1479
  // than silently appearing ready (the "no saved key" fallback shape).
1395
1480
  return { ...c, configured: false };
1396
1481
  });
@@ -1465,7 +1550,8 @@ function createLocalEngine({
1465
1550
  // on, and the one the renderer's per-provider rows mirror. Reporting it
1466
1551
  // unconfigured while `chat()` happily spends the env key is exactly the
1467
1552
  // "no saved key" contradiction this file removes.
1468
- const fromEnv = providerKeyFromEnv(p.id);
1553
+ const envRec = providerKeyRecord(p.id);
1554
+ const fromEnv = envRec.key || '';
1469
1555
  const rawModels = Array.isArray(p.models) ? p.models : [];
1470
1556
  for (const m of rawModels) {
1471
1557
  const modelId = typeof m === 'string' ? m : m && m.id;
@@ -1475,6 +1561,12 @@ function createLocalEngine({
1475
1561
  label: `${p.label || p.id} — ${modelId}`,
1476
1562
  provider: p.id,
1477
1563
  configured: Boolean(rowCfg.configured || fromEnv),
1564
+ // Why a row with no usable key is keyless, when the env file refused
1565
+ // the value it was given rather than never being given one. Carried
1566
+ // on the row because the renderer's per-provider line is the only
1567
+ // place the user can see it before they send a turn. Null when there
1568
+ // is nothing to explain (a saved key, or no env value at all).
1569
+ keyRejected: envRec.rejected || null,
1478
1570
  });
1479
1571
  }
1480
1572
  }
@@ -1512,14 +1604,46 @@ function createLocalEngine({
1512
1604
  }
1513
1605
  return { class: cls, models: tags, baseURL: status.baseURL, listed };
1514
1606
  }
1515
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok' and
1516
- // 'local', all returned above. Thrown rather than falling through to an
1607
+ if (cls === 'pro') {
1608
+ // The model list is the CLI's OWN aliases. The subscription does not
1609
+ // expose an id list this process may query, and inventing full model
1610
+ // names here would be exactly the "client names a model the transport
1611
+ // cannot address" defect — `claude --model` takes these aliases, so these
1612
+ // are the rows (claude-pro.js PRO_MODELS).
1613
+ const status = claudePro.claudeProStatus({ env: process.env });
1614
+ const models = claudePro.PRO_MODELS.map((m) => ({
1615
+ id: m.id,
1616
+ label: m.label,
1617
+ note: m.note,
1618
+ configured: status.loggedIn,
1619
+ }));
1620
+ return {
1621
+ class: cls,
1622
+ models,
1623
+ // Nothing to key: the subscription IS the credential, and there is no
1624
+ // AEGIS spend on this class for the relay's balance gate to consider.
1625
+ needsProviderKey: false,
1626
+ needsAegisKey: false,
1627
+ subscription: status.subscription,
1628
+ loggedIn: status.loggedIn,
1629
+ credentialFile: status.file,
1630
+ // A shell `ANTHROPIC_API_KEY` too short to be a credential makes the CLI
1631
+ // prefer that name over the subscription, so a signed-in machine ran
1632
+ // turns as "API key: he". The child is fixed either way (claude-pro.js
1633
+ // childEnvPlan); reported here so the picker can name the var instead of
1634
+ // leaving it to be discovered from `claude auth status` by hand.
1635
+ shadowed: status.shadowed || null,
1636
+ seam: claudePro.seamAvailable(),
1637
+ };
1638
+ }
1639
+ // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
1640
+ // and 'pro', all returned above. Thrown rather than falling through to an
1517
1641
  // empty list, because "no models" is a state the renderer renders as a
1518
1642
  // normal empty picker — an unknown class would look like a
1519
1643
  // configured-but-empty account instead of the bug it is. Same shape as
1520
1644
  // dispatch's tail.
1521
1645
  throw new Error(
1522
- `listModels: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok' and 'local' only`
1646
+ `listModels: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
1523
1647
  );
1524
1648
  }
1525
1649
 
@@ -1531,6 +1655,64 @@ function createLocalEngine({
1531
1655
  return hostEnv(env || {}, (payload && payload.env) || {}, payload);
1532
1656
  }
1533
1657
 
1658
+ /**
1659
+ * The directories the Claude Pro child is additionally allowed to work in,
1660
+ * for a turn running in `cwd` — the Pro path's half of "the model is not
1661
+ * walled into one subdirectory".
1662
+ *
1663
+ * Two candidates, and only two:
1664
+ *
1665
+ * · the repository root, from `git-scope.js` — the module the turn guard and
1666
+ * the queue already share, so "where does this work happen" is answered in
1667
+ * one place rather than re-derived here;
1668
+ * · the project data directory (`$AEGISCODE_HOME`, else `~/.aegiscode`),
1669
+ * because a turn asked to look at its own session/queue/memory files is
1670
+ * otherwise asked to read a path outside its sandbox — the second real
1671
+ * report of this wall.
1672
+ *
1673
+ * Resolved at CALL time, not at load: `git-scope.js` is staged beside this
1674
+ * file in both layouts (one/scripts/predist.mjs), and a checkout that has not
1675
+ * been staged must still load the engine. A missing module therefore degrades
1676
+ * to "no widening", which is the pre-existing behaviour — never to a second,
1677
+ * local implementation of git root discovery.
1678
+ *
1679
+ * Deduplicated against `cwd` itself: telling the child that its own working
1680
+ * directory is also an extra directory is noise in the argv, in the record and
1681
+ * in the run-log line, and noise is where a real widening hides.
1682
+ */
1683
+ function proAddDirs(cwd) {
1684
+ const out = [];
1685
+ // Separator-normalised comparison only — this file deliberately does not
1686
+ // grow a `node:path` dependency at module scope for two string checks, and
1687
+ // both candidates arrive absolute from modules that already resolved them.
1688
+ const norm = (p) => String(p || '').replace(/[\\/]+$/, '');
1689
+ const here = norm(cwd);
1690
+ const add = (dir) => {
1691
+ const abs = norm(dir);
1692
+ if (!abs || abs === here || out.includes(abs)) return;
1693
+ out.push(abs);
1694
+ };
1695
+ let scope = gitScope;
1696
+ if (scope === undefined) {
1697
+ try {
1698
+ scope = require('./git-scope.js');
1699
+ } catch {
1700
+ scope = null;
1701
+ }
1702
+ }
1703
+ try {
1704
+ if (scope && typeof scope.gitRoot === 'function') add(scope.gitRoot(cwd));
1705
+ } catch {
1706
+ /* not a repo, or git is absent: no wider tree to grant */
1707
+ }
1708
+ try {
1709
+ if (credentialsLib && typeof credentialsLib.aegisHome === 'function') add(credentialsLib.aegisHome());
1710
+ } catch {
1711
+ /* no data directory resolved: nothing to add */
1712
+ }
1713
+ return out;
1714
+ }
1715
+
1534
1716
  /** One transport round for the chosen class. */
1535
1717
  async function dispatch(cls, opts) {
1536
1718
  if (cls === 'aegis') {
@@ -1780,12 +1962,103 @@ function createLocalEngine({
1780
1962
  }
1781
1963
  }
1782
1964
 
1783
- // Unreachable by construction: CLASSES lists only 'aegis', 'byok' and
1784
- // 'local', all returned above. Thrown rather than falling through to a
1965
+ if (cls === 'pro') {
1966
+ // The user's own Claude subscription. This transport is unlike the other
1967
+ // three in a way that decides its whole shape: the `claude` child runs
1968
+ // its OWN agent loop, with its own tools, so there is no `tools` argument
1969
+ // to send and none is invented — passing this engine's schemas would ask
1970
+ // a process that already has a tool loop to re-run our tools inside it.
1971
+ // `opts.messages`/`opts.tools` are deliberately unused here for that
1972
+ // reason, and the dispatch returns the child's own final answer.
1973
+ //
1974
+ // ── … and the consequence of that, which used to be a bug ─────────────
1975
+ //
1976
+ // Because the transcript is NOT replayed into the child, the child's own
1977
+ // session store was the only thing that could carry context between
1978
+ // turns — and nothing ever told it to resume one. Every turn was a
1979
+ // brand-new conversation: "Claude has no memory of this conversation"
1980
+ // was literally true, and no amount of `messages` upstream could fix it,
1981
+ // because they were dropped on purpose one paragraph above.
1982
+ //
1983
+ // So the child's reported session id is remembered per CONVERSATION and
1984
+ // handed back as `--resume`. Keyed by the conversation (rootSessionId),
1985
+ // never by `sessionId`: the CLI mints a fresh uuid per turn for
1986
+ // cancellation, so keying by it would resume nothing, every turn.
1987
+ //
1988
+ // We deliberately do NOT pass `sessionId` (`--session-id`) to name the
1989
+ // conversation upfront: the CLI's own `/new` mints `aegis-xxxxxxxx`,
1990
+ // which is not a UUID the child accepts, and the child's self-minted id
1991
+ // is authoritative anyway. It is read back off the `result` line instead.
1992
+ const convKey = opts.sessionKey || opts.rootSessionId || opts.sessionId;
1993
+ const remembered = convKey ? proSessions.get(convKey) : null;
1994
+ // ── the sandbox the child is actually given ───────────────────────────
1995
+ //
1996
+ // A headless `claude` child resolves every relative path and every tool's
1997
+ // root against the directory it was spawned in, so a turn started in a
1998
+ // SUBDIRECTORY of the repo cannot read or run anything above it. Reported
1999
+ // from this product for real: a session launched in `cli/` that needed
2000
+ // `test/` came back with "I can't run outside the sandboxed directory
2001
+ // `cli/`" — the model, not a bug in the tools, describing this boundary.
2002
+ //
2003
+ // The repo root is the right width: it is the tree the user opened, it is
2004
+ // one directory (never a glob, never the home dir), and it is derived
2005
+ // rather than guessed — `git-scope.js` is the module the turn guard and
2006
+ // the queue already ask for "where is this work happening". Best-effort:
2007
+ // outside a repo there is no wider directory to grant and the child keeps
2008
+ // exactly the posture it had.
2009
+ // The turn's own working directory rides on `opts.cwd` (threaded in by
2010
+ // `chat()` as `turnCwd`), never on the enclosing scope's local — that
2011
+ // reference is the exact `ReferenceError: turnCwd is not defined` this
2012
+ // file already carries a regression case for.
2013
+ const addDir = proAddDirs(opts.cwd);
2014
+ //
2015
+ // The permission half of the argv is NOT built here. It comes from
2016
+ // resolvePosture() inside runClaudePro, through the one argv builder
2017
+ // (one/src/child.js), so this host and AEGISONE's faces cannot disagree
2018
+ // about what the child was allowed to do.
2019
+ const proRes = await claudePro.runClaudePro({
2020
+ prompt: opts.prompt,
2021
+ model: opts.model && opts.model !== 'default' ? opts.model : undefined,
2022
+ system: opts.system,
2023
+ cwd: opts.cwd,
2024
+ // The widened sandbox, threaded through to the ONE argv builder. A
2025
+ // directory the engine could not derive (or that adds nothing, e.g. the
2026
+ // turn already runs at the repo root) is simply absent from this list,
2027
+ // and absent means "exactly the posture the child had before".
2028
+ addDir,
2029
+ // Carry the conversation, if we have one to carry.
2030
+ resumeSessionId: remembered || undefined,
2031
+ // The stored posture this host already reads for its own gate, handed
2032
+ // to the resolver rather than re-read there — one answer per turn.
2033
+ gate: typeof getConfirmMode === 'function' ? !getConfirmMode() : undefined,
2034
+ signal: opts.signal,
2035
+ onDelta: opts.onDelta,
2036
+ onSpawn: (child, record) => {
2037
+ // Rule 4's "recorded, never inferred": the child's real flags are
2038
+ // reported on the same channel tool activity uses, so a Pro turn's
2039
+ // transcript shows what it was allowed to do.
2040
+ if (opts.onDelta && record) {
2041
+ opts.onDelta({ delta: '', note: claudePro.childLine(record) });
2042
+ }
2043
+ void child;
2044
+ },
2045
+ });
2046
+ // Remember the id the child reported, so the NEXT turn in this thread
2047
+ // resumes this conversation. Recorded only on a turn that actually
2048
+ // produced one: a failed turn must not overwrite a good id with
2049
+ // `undefined` and silently turn the next turn into a new conversation.
2050
+ if (convKey && proRes && proRes.sessionId && !proRes.error) {
2051
+ proSessions.set(convKey, proRes.sessionId);
2052
+ }
2053
+ return proRes;
2054
+ }
2055
+
2056
+ // Unreachable by construction: CLASSES lists only 'aegis', 'byok', 'local'
2057
+ // and 'pro', all returned above. Thrown rather than falling through to a
1785
2058
  // default transport, because a class that silently borrows another's wire
1786
2059
  // format is this file's recurring failure mode.
1787
2060
  throw new Error(
1788
- `dispatch: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok' and 'local' only`
2061
+ `dispatch: unknown model class ${JSON.stringify(cls)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`
1789
2062
  );
1790
2063
  }
1791
2064
 
@@ -1932,9 +2205,39 @@ function createLocalEngine({
1932
2205
  throw err;
1933
2206
  }
1934
2207
  if (cls === 'byok' && !apiKey) {
2208
+ // Anthropic is the one provider with a SECOND, non-API route, and it is
2209
+ // the one a user with a Claude subscription actually owns. Pinning
2210
+ // `anthropic:claude-sonnet-5` is a promise that this machine has a
2211
+ // console API key for api.anthropic.com; a Pro/Max subscription is NOT
2212
+ // one and is deliberately not usable as one (claude-pro.js's own
2213
+ // header). So when the machine holds a subscription and no usable
2214
+ // anthropic key, the honest instruction is the Pro class — it spends
2215
+ // the subscription they already pay for instead of a key they do not
2216
+ // have. Checked through claudeProStatus() rather than by looking for a
2217
+ // token here, so this message and the picker cannot disagree about
2218
+ // whether a subscription is present.
2219
+ const pro = byokParts.provider === 'anthropic' ? claudePro.claudeProStatus({ env: process.env }) : null;
2220
+ // A key the env file REFUSED outranks both of the messages below. The
2221
+ // generic "no key yet" tells a user to go paste one, which is the wrong
2222
+ // instruction when the file already holds a value that cannot be a
2223
+ // credential: they will paste the same broken thing again, or conclude
2224
+ // their account is broken. This is the exact state that produced an
2225
+ // upstream `{"type":"authentication_error","message":"Invalid bearer
2226
+ // token"}` and read to the user as "Anthropic auth failed".
2227
+ const refused = providerKeyRecord(byokParts.provider).rejected;
1935
2228
  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>.`
2229
+ refused
2230
+ ? `${refused}. That is why this turn has no ${byokParts.provider} key: an env value ` +
2231
+ `that short is a paste that lost its payload, not a credential. Fix ${refused.split(' ')[0]} ` +
2232
+ `in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: ` +
2233
+ `/byok-key ${byokParts.provider} <key> to set one here.`
2234
+ : pro && pro.loggedIn
2235
+ ? `No Anthropic API key on this machine — an "anthropic:…" id is served by your own ` +
2236
+ `console key, which a Claude subscription is not. Use the subscription instead: ` +
2237
+ `/class pro (it spends your Claude Code ${pro.subscription || 'Pro'} plan through the ` +
2238
+ `claude CLI) — or add a real console key: /byok-key anthropic <key>.`
2239
+ : `No key for "${byokParts.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, ` +
2240
+ `no setup) — or add this provider's own key: /byok-key ${byokParts.provider} <key>.`
1938
2241
  );
1939
2242
  err.status = 400;
1940
2243
  throw err;
@@ -1978,6 +2281,20 @@ function createLocalEngine({
1978
2281
  }
1979
2282
  const base = {
1980
2283
  cls, model, mode: payload && payload.mode, maxTokens, statedMaxTokens, autonomous, sessionId, signal, onDelta, cfg, apiKey, toolChoice,
2284
+ // The turn's working directory, computed above as `turnCwd` — `dispatch`
2285
+ // is its own function, not a closure over `chat`'s locals, so the 'pro'
2286
+ // branch (the only one that spawns a child in a directory) needs it
2287
+ // threaded through here rather than reaching for the enclosing scope's
2288
+ // variable, which does not exist from inside `dispatch`.
2289
+ cwd: turnCwd,
2290
+ // The CONVERSATION's identity, distinct from `sessionId` (which both
2291
+ // hosts mint fresh per TURN — the CLI in ask(), for cancellation).
2292
+ // Continuity that must outlive one turn is keyed by these, never by
2293
+ // `sessionId`: the Pro child's remembered session is one per open
2294
+ // thread, so keying it by a per-turn id would start a new child
2295
+ // conversation every single turn and look exactly like no memory.
2296
+ rootSessionId,
2297
+ sessionKey: (payload && payload.sessionKey) || undefined,
1981
2298
  effort: payload && payload.effort,
1982
2299
  workers: payload && payload.workers,
1983
2300
  // Deep recall (`aegis_recall_deep`) is an explicit per-session opt-in
@@ -83,7 +83,7 @@ let provisionAttempted = false;
83
83
  async function ensureApiKey() {
84
84
  if (aegis.apiKey || provisionAttempted) return;
85
85
  provisionAttempted = true;
86
- const result = await autoProvisionApiKey(aegis, credentials);
86
+ const result = await autoProvisionApiKey(aegis, credentials, { app: 'mcp' });
87
87
  if (result.error) {
88
88
  process.stderr.write(`aegis: device auto-registration failed (${result.error.message}) — falling back to manual setup.\n`);
89
89
  return;