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
@@ -27,7 +27,7 @@ const readline = require('node:readline');
27
27
  const os = require('node:os');
28
28
  const { randomUUID } = require('node:crypto');
29
29
  const { createTools, createClient, usageTokens, usageBuckets, buildSystemPrompt, autoProvisionApiKey, provisionFailureText, trialNote, hostEnv, autonomous, claudePro } = require('./deps.js');
30
- const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace, effortRung } = require('./engine.js');
30
+ const { createEngine, HOST_CLASSES, DEFAULT_CLASS, byokNamespace, effortRung, offeredClasses, proEnabled } = 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');
33
33
  const { LiveRegion, termWidth, w } = require('./screen.js');
@@ -122,6 +122,65 @@ function normalizeDecision(decision) {
122
122
  return 'deny';
123
123
  }
124
124
 
125
+ // ── "that was not an answer" ────────────────────────────────────────────────
126
+ //
127
+ // A provider-side refusal can arrive shaped exactly like a completion: HTTP
128
+ // 200, an assistant message, `usage` absent or zero. Measured 2026-10-21 on
129
+ // this CLI, twice, from live runs:
130
+ //
131
+ // {"text":"Invalid API key · Fix external API key","tokens":0,"balance_eur":1.54}
132
+ // {"text":"You've hit your session limit · resets 9:50pm (Europe/Stockholm)"}
133
+ //
134
+ // Both exited 0. Nothing about the process told a caller that the turn had
135
+ // failed: a shell script, a CI job, or the harness adapter reading `--json`
136
+ // sees a non-empty `text` and calls it success. The harness did exactly that
137
+ // and scored a *broken* run as a scored zero rather than an error.
138
+ //
139
+ // The engine already treats this class as a diagnosed failure mode — see
140
+ // `phantomPin()` and the `session limit` notes in aegiscodex-dev's
141
+ // src/backend.js, where a spent OAuth session "reads like a provider outage
142
+ // rather than a bad pin". This host ships the transport and the CLI, not that
143
+ // brain, so it cannot prevent the misroute; what it *can* do is refuse to pass
144
+ // the resulting sentence off as an answer.
145
+ //
146
+ // Deliberately narrow, because calling a real answer an error is its own bug:
147
+ // - Only when the turn produced NO tokens. A billed turn did work; whatever
148
+ // it says is the model's output, even if it reads oddly.
149
+ // - Only when the whole reply is one short line. A long answer that happens
150
+ // to discuss API keys must not be caught by a substring match.
151
+ // - Only known provider-refusal shapes. Not "any sentence with 'error'".
152
+ const PROVIDER_REFUSAL_PATTERNS = Object.freeze([
153
+ /^invalid api key\b/i,
154
+ /^fix external api key\b/i,
155
+ /^you've hit your session limit\b/i,
156
+ /^you have hit your session limit\b/i,
157
+ /^provider request timed out\b/i,
158
+ /^insufficient (?:credit|balance|quota)\b/i,
159
+ /^rate limit(?:ed)?\b/i,
160
+ /^unauthorized\b/i,
161
+ ]);
162
+
163
+ /**
164
+ * Whether `text` is a provider refusal that arrived dressed as a completion.
165
+ *
166
+ * @param {unknown} text the assistant content `ask()` returned
167
+ * @param {unknown} usage the turn's usage record, if any
168
+ * @returns {string|null} the matched refusal, or null when it is a real answer
169
+ */
170
+ function providerRefusal(text, usage) {
171
+ if (typeof text !== 'string') return null;
172
+ // A billed turn is not a refusal, whatever it says.
173
+ const total = usage && (usage.total_tokens || 0);
174
+ const out = usage && (usage.output_tokens || usage.completion_tokens || 0);
175
+ if (total > 0 || out > 0) return null;
176
+ const line = text.trim();
177
+ if (!line || line.length > 160 || line.includes('\n')) return null;
178
+ for (const re of PROVIDER_REFUSAL_PATTERNS) {
179
+ if (re.test(line)) return line;
180
+ }
181
+ return null;
182
+ }
183
+
125
184
  function createApp(options = {}) {
126
185
  const opts = {
127
186
  model: null,
@@ -225,6 +284,18 @@ function createApp(options = {}) {
225
284
  // reason confirmMode is a callback: a captured value made `/class`
226
285
  // cosmetic, changing the panel and not what the next turn ran on.
227
286
  getClass: () => commandCtx.modelClass,
287
+ // Whether the `pro` class is enabled (config.js `proEnabled`, off by
288
+ // default). Read per call for the same reason getClass is: `/class pro
289
+ // off` must remove it from the picker and stop the very next turn, not
290
+ // the next launch. A read failure answers "off" — fail closed, because
291
+ // the alternative spends a subscription nobody opted into.
292
+ getProEnabled: () => {
293
+ try {
294
+ return proEnabled(loadConfig());
295
+ } catch {
296
+ return false;
297
+ }
298
+ },
228
299
  getConfirmMode: () => {
229
300
  if (options.confirmMode !== undefined) return confirmMode;
230
301
  // AEGISONE D8 rule 5 — the skip posture, resolved by the SAME function
@@ -621,10 +692,49 @@ function createApp(options = {}) {
621
692
  // (the engine's splitByokModel), built from the server's provider catalog
622
693
  // plus the provider rows this machine actually holds a key for — so this list
623
694
  // is per-machine, not per-account, and cannot be served by the pooled catalog.
624
- const byokCache = { at: 0, models: [] };
695
+ const byokCache = { at: 0, models: [], declared: '' };
696
+
697
+ /**
698
+ * The user-model declarations (`$AEGISCODE_HOME/models.json`) as one
699
+ * comparable string, or '' when they cannot be read.
700
+ *
701
+ * The byok list is not only the server's: `engine.listModels('byok')` folds
702
+ * the USER's own declarations into each provider row (`client/user-models.js`
703
+ * `withUserModels`), so the id set can change with no network call and no
704
+ * provider catalog change. A custom provider in particular has NO catalog
705
+ * model at all — its rows exist solely because someone declared them — so a
706
+ * cache keyed only on time shows an empty provider for up to five minutes
707
+ * after the declaration was written.
708
+ *
709
+ * That is the cross-host case this exists for: the desktop's Custom provider
710
+ * card, `/model-add` in another terminal, and a hand-edited file all write
711
+ * the SAME file, and none of them can reach this process's `byokCache`. So
712
+ * the file's content is part of the cache key: a declaration made elsewhere
713
+ * is visible the next time the picker is opened, not five minutes later.
714
+ *
715
+ * Read through `engine.userModels()` rather than the path, so this stays one
716
+ * store and one implementation (the CLI's engine is the same module the
717
+ * desktop uses). A store that throws is treated as unchanged — the time
718
+ * window still expires the cache, so a broken read cannot pin stale rows
719
+ * forever.
720
+ */
721
+ function declaredModelsKey() {
722
+ try {
723
+ if (typeof engine.userModels !== 'function') return '';
724
+ const map = (engine.userModels() || {}).map || {};
725
+ return JSON.stringify(Object.keys(map).sort().map((p) => [p, map[p]]));
726
+ } catch {
727
+ return '';
728
+ }
729
+ }
625
730
 
626
731
  async function loadByokModels({ force = false } = {}) {
627
- const fresh = byokCache.models.length && Date.now() - byokCache.at < MODEL_CACHE_MS;
732
+ const declared = declaredModelsKey();
733
+ const fresh =
734
+ byokCache.models.length &&
735
+ Date.now() - byokCache.at < MODEL_CACHE_MS &&
736
+ // The declarations are part of the key: see declaredModelsKey().
737
+ declared === byokCache.declared;
628
738
  if (!force && fresh) return byokCache.models;
629
739
  // An injected engine (tests, embedding) may predate the class surface; an
630
740
  // empty list is the honest answer then, not a fabricated one.
@@ -641,6 +751,7 @@ function createApp(options = {}) {
641
751
  note: m.configured ? 'key on this machine' : `no key — /byok-key ${m.provider}`,
642
752
  }));
643
753
  byokCache.at = Date.now();
754
+ byokCache.declared = declared;
644
755
  return byokCache.models;
645
756
  }
646
757
 
@@ -652,7 +763,14 @@ function createApp(options = {}) {
652
763
  * able to chat on the server's own default.
653
764
  */
654
765
  async function listModelsFor(cls) {
655
- const want = HOST_CLASSES.includes(cls) ? cls : commandCtx.modelClass;
766
+ // The OFFERED set, not HOST_CLASSES: a class that is not selectable (a
767
+ // disabled `pro`) yields NOTHING rather than the live class's rows. The
768
+ // merged picker tags whatever comes back as belonging to the class it
769
+ // asked about, so substituting pooled rows here would paint pooled ids as
770
+ // Pro rows — and pinning one would move the session onto the subscription.
771
+ const allowed = selectableClasses();
772
+ if (cls && !allowed.includes(cls) && HOST_CLASSES.includes(cls)) return [];
773
+ const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
656
774
  try {
657
775
  if (want === 'byok') {
658
776
  const byok = await loadByokModels();
@@ -777,7 +895,13 @@ function createApp(options = {}) {
777
895
  * not on; only an absent/unknown `cls` may fall back to the live one.
778
896
  */
779
897
  function classScopedModels(byokOverride, cls) {
780
- const want = HOST_CLASSES.includes(cls) ? cls : commandCtx.modelClass;
898
+ const allowed = selectableClasses();
899
+ const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
900
+ // A disabled `pro` yields no rows at all — not the pooled ones either,
901
+ // because the caller asked for pro's id space and answering with pooled ids
902
+ // is the cross-class mix-up this branch exists to prevent (the merged
903
+ // picker would tag them `pro`).
904
+ if (cls === 'pro' && !allowed.includes('pro')) return [];
781
905
  // The Pro class' list is its own alias set, never the pooled catalog: a
782
906
  // pooled id pinned under pro would be sent to `claude --model`, which
783
907
  // resolves aliases and real model names, not AEGIS ids — the same
@@ -820,9 +944,25 @@ function createApp(options = {}) {
820
944
  return !s.includes(':');
821
945
  }
822
946
 
947
+ /**
948
+ * The classes selectable right now. `pro` is behind the `proEnabled` gate
949
+ * (config.js, default off): HOST_CLASSES says this host CAN run it, this says
950
+ * whether it has been opted into. Every surface that lists or validates a
951
+ * class reads this, so the gate cannot be honoured in one place and ignored
952
+ * in another. A config read failure answers "pro is off" (fail closed).
953
+ */
954
+ function selectableClasses() {
955
+ try {
956
+ return offeredClasses(proEnabled(loadConfig()));
957
+ } catch {
958
+ return offeredClasses(false);
959
+ }
960
+ }
961
+
823
962
  /**
824
963
  * Switch the live class. Refuses anything this host cannot run (engine.js's
825
- * HOST_CLASSES is the authority).
964
+ * HOST_CLASSES is the authority) and anything it does not offer — `pro` needs
965
+ * a one-time `/class pro on` first.
826
966
  *
827
967
  * A pin is cleared when it does not belong to the class being entered: a
828
968
  * pooled id pinned under byok would be parsed as provider `<pooled id>` and
@@ -833,8 +973,17 @@ function createApp(options = {}) {
833
973
  */
834
974
  function switchClass(next) {
835
975
  const want = String(next == null ? '' : next).trim().toLowerCase();
836
- if (!HOST_CLASSES.includes(want)) {
837
- return { ok: false, error: `unknown class "${next}" — classes: ${HOST_CLASSES.join(', ')}` };
976
+ const allowed = selectableClasses();
977
+ if (!allowed.includes(want)) {
978
+ if (want === 'pro') {
979
+ return {
980
+ ok: false,
981
+ error:
982
+ 'the pro class (your Claude Code subscription) is off by default — ' +
983
+ 'enable it once with `/class pro on`',
984
+ };
985
+ }
986
+ return { ok: false, error: `unknown class "${next}" — classes: ${allowed.join(', ')}` };
838
987
  }
839
988
  const prev = commandCtx.modelClass;
840
989
  commandCtx.modelClass = want;
@@ -906,18 +1055,62 @@ function createApp(options = {}) {
906
1055
  // launch. There is no fetch on this path either — the list is a constant, so
907
1056
  // this is the one class whose validation cannot be defeated by being offline.
908
1057
  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;
1058
+ if (!proModelIds().has(String(pinned).toLowerCase())) {
1059
+ commandCtx.model = null;
1060
+ updateConfig({ model: null, currentModelId: null });
1061
+ emit(
1062
+ render.renderNotice(
1063
+ ctx(),
1064
+ 'warn',
1065
+ `pinned model "${pinned}" is not one the Claude Code CLI resolves — pin cleared, ` +
1066
+ `the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((m) => m.id).join(', ')}).`
1067
+ )
1068
+ );
1069
+ return pinned;
1070
+ }
1071
+ // The alias resolves — but resolving an alias is not the same as having
1072
+ // anything to spend on it. This is the phantom-pin case aegiscodex-dev
1073
+ // learned first (phantomPin() in its src/backend.js): when the host has
1074
+ // no subscription and no console key, the `claude` child has no usable
1075
+ // credential, and the turn does not fail loudly here — it fails after a
1076
+ // round-trip with "Invalid API key" or "You've hit your session limit",
1077
+ // which reads like a provider outage rather than a missing credential.
1078
+ // Checked before the turn, so the user is told why and the pin stops
1079
+ // re-creating the problem on the next launch.
1080
+ let proCallable = true;
1081
+ try {
1082
+ const st = claudePro.claudeProStatus({ env: process.env });
1083
+ // `credentialPresent` — not `subscriptionPresent`, and not a fresh read
1084
+ // of `process.env` here. Three different questions live in this area and
1085
+ // conflating them is how the pin went unchecked in the first place:
1086
+ // - "is there a subscription to shadow?" → subscriptionPresent
1087
+ // (excludes a bare console key on disk, by design)
1088
+ // - "can this host serve a pro turn?" → credentialPresent (this one)
1089
+ // - "is this env value a credential?" → childEnvPlan's verdict
1090
+ // The third is why this reads a field instead of testing
1091
+ // `process.env.ANTHROPIC_API_KEY` directly: the planner REFUSES a value
1092
+ // that would be dropped from the child, so an env var alone is not
1093
+ // evidence of a route. See childEnvPlan / isAnthropicConsoleKey.
1094
+ proCallable = !!st.credentialPresent;
1095
+ } catch {
1096
+ // An unprovable credential is not a proven absence: leave the pin alone.
1097
+ proCallable = true;
1098
+ }
1099
+ if (!proCallable) {
1100
+ commandCtx.model = null;
1101
+ updateConfig({ model: null, currentModelId: null });
1102
+ emit(
1103
+ render.renderNotice(
1104
+ ctx(),
1105
+ 'warn',
1106
+ `pinned model "${pinned}" needs a Claude Pro subscription or an ` +
1107
+ `ANTHROPIC_API_KEY, and this host has neither — pin cleared. ` +
1108
+ `Run \`claude /login\`, export a console key, or \`/class pro off\`.`
1109
+ )
1110
+ );
1111
+ return pinned;
1112
+ }
1113
+ return null;
921
1114
  }
922
1115
  let models;
923
1116
  try {
@@ -1517,6 +1710,8 @@ function createApp(options = {}) {
1517
1710
  else if (o.type === 'palette') lines = overlays.renderPalette(visibleCommands(), { query: o.query || '', sel: o.sel || 0 }, W, rows);
1518
1711
  else if (o.type === 'model') lines = overlays.renderModelPicker(o.items || [], o.sel || 0, W, rows, o.current != null ? o.current : commandCtx.model, o.cls || commandCtx.modelClass, classLabelOf);
1519
1712
  else if (o.type === 'effort') lines = overlays.renderEffortPicker(o.sel || 0, W, commandCtx.effort);
1713
+ else if (o.type === 'class') lines = overlays.renderClassPicker(o.items || [], o.sel || 0, W, o.current || commandCtx.modelClass, classLabelOf);
1714
+ else if (o.type === 'provider') lines = overlays.renderProviderPicker(o.items || [], o.sel || 0, W, o.current, o.hint);
1520
1715
  else if (o.type === 'resume') lines = overlays.renderResumeList(o.items || [], o.sel || 0, W, rows);
1521
1716
  else if (o.type === 'confirm') lines = render.renderApproval(ctx(), o.info || {}, W).map((s) => [spanRow(s)]);
1522
1717
  if (!lines) return;
@@ -1742,6 +1937,17 @@ function createApp(options = {}) {
1742
1937
  // leave a working prompt rather than aborting the command.
1743
1938
  const spec = await describeSecret(cmd, args);
1744
1939
  if (spec && spec.note) emit(render.renderNotice(ctx(), 'info', spec.note));
1940
+ // An explicit `prompt: null` is a refusal, not a missing description.
1941
+ // Reading it as "no description" and falling through to the generic
1942
+ // prompt is how `/byok-set <typo>` printed "unknown provider … Nothing
1943
+ // was sent" and then asked for the key anyway and sent it: the command
1944
+ // had decided this must not be stored, and the dispatcher overrode it.
1945
+ if (spec && spec.prompt === null) return true;
1946
+ // The command may have resolved the typed word to a canonical id
1947
+ // (`together-ai` → `together`). Send that. Otherwise the prompt names
1948
+ // the real provider while the request carries the alias the server does
1949
+ // not know, and the save fails after the user has already pasted a key.
1950
+ if (spec && spec.provider) args = { ...args, provider: spec.provider };
1745
1951
  const key = await askSecret((spec && spec.prompt) || `provider key for ${args.provider}: `);
1746
1952
  if (!key) {
1747
1953
  emit(render.renderNotice(ctx(), 'warn', 'empty key — nothing sent'));
@@ -1826,8 +2032,63 @@ function createApp(options = {}) {
1826
2032
 
1827
2033
  // --- entry points ---------------------------------------------------------
1828
2034
 
2035
+ /**
2036
+ * Give the local lane back its hardware, on the way out.
2037
+ *
2038
+ * The desktop has done this from its quit path since the class shipped
2039
+ * (`main.js` before-quit -> `engine.unloadLocalModels` -> local.js
2040
+ * `unloadAll`): "closing the app closes the model". The CLI had no equivalent
2041
+ * at all, so exiting a session after a `local` turn left the weights resident
2042
+ * for the remainder of the pin the turn itself set — `DEFAULT_WARM_SECS` is
2043
+ * 1800 (local.js), i.e. up to thirty minutes of a loaded model on hardware
2044
+ * nobody was using anymore, which is the one cost this lane exists to not
2045
+ * have.
2046
+ *
2047
+ * Best-effort by construction: `unloadAll` never throws and each request is
2048
+ * bounded by `UNLOAD_TIMEOUT_MS` (4s) inside the transport, so a daemon that
2049
+ * is slow, wedged or already gone cannot turn a clean exit into a hang or a
2050
+ * crash. Called from every exit path of every entry point below — INCLUDING
2051
+ * `-p`, whose whole life may be one local turn.
2052
+ *
2053
+ * Deliberately not a `process.on('exit')` handler: that callback cannot
2054
+ * await, so the request would be issued into a process that is already
2055
+ * tearing the socket down. Awaiting at the end of the session is what makes
2056
+ * the eviction actually reach the daemon.
2057
+ */
2058
+ async function releaseLocalModel() {
2059
+ if (!engine || typeof engine.unloadLocalModels !== 'function') return;
2060
+ try {
2061
+ await engine.unloadLocalModels();
2062
+ } catch {
2063
+ /* the model's own keep-alive lapses; never fail an exit over cleanup */
2064
+ }
2065
+ }
2066
+
2067
+ /**
2068
+ * One-shot run: the turn itself (`runOnceTurn`), then the local lane handed
2069
+ * back even if that turn threw. A `-p` run can BE a whole local session, so
2070
+ * it needs the same closing the interactive loop gets — see
2071
+ * `releaseLocalModel`.
2072
+ */
2073
+ async function runOnce(prompt, opts = {}) {
2074
+ try {
2075
+ return await runOnceTurn(prompt, opts);
2076
+ } finally {
2077
+ await releaseLocalModel();
2078
+ }
2079
+ }
2080
+
1829
2081
  /** Non-interactive: one prompt, plain output, exit code. */
1830
- async function runOnce(prompt, { json = false } = {}) {
2082
+ async function runOnceTurn(prompt, { json = false } = {}) {
2083
+ // The one-shot path used to skip this entirely, so `-p` always ran
2084
+ // DEFAULT_CLASS ('aegis', the pooled route) no matter what the user had
2085
+ // pinned: `/class byok` (or a saved byok/byok-model pin) applied to the
2086
+ // interactive loop only. That made the documented headless entry point
2087
+ // unable to use BYOK at all — it billed the pool instead, or, on a box
2088
+ // whose pooled backend was down, failed with a provider timeout while the
2089
+ // user's own key sat unused. Same restore the REPL does, before the first
2090
+ // turn and therefore before `ask()` resolves a route.
2091
+ restorePrefs();
1831
2092
  adoptLegacyKeyOnce();
1832
2093
  // Same self-service a fresh `aegiscode -p ...` deserves as a fresh
1833
2094
  // interactive session (runInteractive) or a fresh `/ask` (runPrompt):
@@ -1863,9 +2124,41 @@ function createApp(options = {}) {
1863
2124
  // and the reported charge would be whatever the account spent last rather
1864
2125
  // than what this call cost.
1865
2126
  await refreshSpend();
1866
- const res = await ask(prompt);
2127
+ // Under `--json`, stdout carries ONE document and nothing else. A turn that
2128
+ // uses tools renders a row per call (`ask()`'s `tool` presenter below), and
2129
+ // those rows went to `out` — so the document was preceded by ANSI-coloured
2130
+ // progress text and no parser could read it. Measured: a tool-using turn
2131
+ // emitted 1238 bytes of `Bash ⎿ ✔` rows before the JSON, which is why the
2132
+ // harness sweep recorded `tokens_in: 0` for tasks the CLI had in fact
2133
+ // SOLVED. The rows are still shown, just on stderr, where a human sees them
2134
+ // and a parser does not.
2135
+ // Every tool call this turn really made, by name. `--json` is the only
2136
+ // machine-readable surface the CLI has, and the harness measures "how much
2137
+ // work did the loop do" from it. A tool-using turn that reports no tools is
2138
+ // indistinguishable from a turn that answered from memory — the benchmark
2139
+ // scored three tasks SOLVED with `tool_calls: 0` while the workspace showed
2140
+ // genuine edits, because nothing published the count.
2141
+ const toolsUsed = [];
2142
+ const jsonPresenter = json
2143
+ ? {
2144
+ tool: (tool) => {
2145
+ if (tool && tool.name) toolsUsed.push(tool.name);
2146
+ const diff = tool && tool.preview !== undefined ? tool.preview : null;
2147
+ const lines = render.renderTurn(
2148
+ ctx(),
2149
+ { role: 'tool', label: tool.name, args: tool.args, ok: tool.ok, diff, diffOpen: false },
2150
+ width()
2151
+ );
2152
+ for (const l of Array.isArray(lines) ? lines : [lines]) err.write(l + '\n');
2153
+ return undefined;
2154
+ },
2155
+ }
2156
+ : null;
2157
+ const res = await ask(prompt, jsonPresenter ? { presenter: jsonPresenter } : {});
1867
2158
  await refreshSpend();
1868
2159
  const tokens = usageTokens(res.usage);
2160
+ // A refusal that arrived as content: report it as a failure, not an answer.
2161
+ const refusal = providerRefusal(res.text, res.usage);
1869
2162
  if (json) {
1870
2163
  out.write(
1871
2164
  JSON.stringify(
@@ -1876,6 +2169,15 @@ function createApp(options = {}) {
1876
2169
  tokens,
1877
2170
  ms: res.ms,
1878
2171
  interrupted: res.interrupted,
2172
+ // Present only when the turn actually called tools, so a reader can
2173
+ // tell "answered from memory" from "did work" without inferring it
2174
+ // from a token count.
2175
+ ...(toolsUsed.length ? { tools: toolsUsed } : {}),
2176
+ // Present only when the reply was a provider refusal. A caller that
2177
+ // gates on `error` can now tell a dead turn from a working one;
2178
+ // before this field existed both were `{text, tokens: 0}` with
2179
+ // exit 0, and the harness scored a broken run as a scored zero.
2180
+ ...(refusal ? { error: refusal } : {}),
1879
2181
  balance_eur: session.balance,
1880
2182
  },
1881
2183
  null,
@@ -1884,6 +2186,7 @@ function createApp(options = {}) {
1884
2186
  );
1885
2187
  } else {
1886
2188
  out.write(res.text + '\n');
2189
+ if (refusal) err.write(`aegiscode: the provider refused this turn — ${refusal}\n`);
1887
2190
  if (tokens != null) {
1888
2191
  const t = themeOf(ctx());
1889
2192
  out.write(
@@ -1893,7 +2196,7 @@ function createApp(options = {}) {
1893
2196
  );
1894
2197
  }
1895
2198
  }
1896
- return res.interrupted ? 130 : 0;
2199
+ return res.interrupted ? 130 : (refusal ? 1 : 0);
1897
2200
  }
1898
2201
 
1899
2202
  /** Fold one completed turn's usage into the session tallies.
@@ -2158,11 +2461,21 @@ function createApp(options = {}) {
2158
2461
  // Without these two the picker would re-prompt for a key the machine
2159
2462
  // demonstrably holds, which is how the same key got saved twice.
2160
2463
  accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
2464
+ // `get()` is the MASKED read — it returns {provider, baseURL, configured,
2465
+ // keyMask} and never carries a `.key` field. Reading `row.key` here made
2466
+ // this predicate permanently false, so the picker re-prompted for a key
2467
+ // the machine demonstrably held: the exact bug the comment above says it
2468
+ // exists to prevent. `rawKey()` is the reader that returns the plaintext;
2469
+ // `configured` is the fallback for a store that offers only `get()`.
2161
2470
  hasProviderKey: (provider) => {
2162
2471
  const store = engine.settings;
2163
- if (!store || typeof store.get !== 'function' || !provider) return false;
2164
- const row = (store.get(byokNamespace(provider)) || {});
2165
- return !!String(row.key || '').trim();
2472
+ if (!store || !provider) return false;
2473
+ const row = byokNamespace(provider);
2474
+ if (typeof store.rawKey === 'function') {
2475
+ return !!String(store.rawKey(row) || '').trim();
2476
+ }
2477
+ if (typeof store.get !== 'function') return false;
2478
+ return !!((store.get(row) || {}).configured);
2166
2479
  },
2167
2480
  loadModels: (o) => loadModels(o),
2168
2481
  buildState: () => buildState(),
@@ -2274,7 +2587,12 @@ function createApp(options = {}) {
2274
2587
  }
2275
2588
  // The class first: a stored BYOK pin is only meaningful under byok, and the
2276
2589
  // pin check right after this reads whichever class won.
2277
- if (HOST_CLASSES.includes(cfg.modelClass)) commandCtx.modelClass = cfg.modelClass;
2590
+ //
2591
+ // Gated on the OFFERED set, not HOST_CLASSES: a config written while `pro`
2592
+ // was enabled must not restore a subscription session onto a machine where
2593
+ // it has been turned off, or where this install never opted in. Such a
2594
+ // stored value falls back to the live default rather than being trusted.
2595
+ if (selectableClasses().includes(cfg.modelClass)) commandCtx.modelClass = cfg.modelClass;
2278
2596
  if (!opts.model && cfg.model) commandCtx.model = cfg.model;
2279
2597
  // Restored through effortRung(), so a config written by an older build is
2280
2598
  // never a value this one does not send: `null`, `''` and the retired
@@ -2344,7 +2662,22 @@ function createApp(options = {}) {
2344
2662
  * injected readline, `--print` — it stays the linear loop, so output remains
2345
2663
  * pipeable and scriptable.
2346
2664
  */
2665
+ /**
2666
+ * Interactive session: the loop itself (`runInteractiveSession`), then the
2667
+ * local lane handed back. Wrapped for the same reason `runOnce` is: the loop
2668
+ * has several exits (a declined onboarding, `/quit`, a reset key stream, the
2669
+ * linear REPL), and "closing the session closes the model" must hold on all
2670
+ * of them rather than on the one path a `return` happens to reach.
2671
+ */
2347
2672
  async function runInteractive() {
2673
+ try {
2674
+ return await runInteractiveSession();
2675
+ } finally {
2676
+ await releaseLocalModel();
2677
+ }
2678
+ }
2679
+
2680
+ async function runInteractiveSession() {
2348
2681
  const tty =
2349
2682
  !options.readline &&
2350
2683
  options.chatflow !== false &&
@@ -2473,11 +2806,18 @@ function createApp(options = {}) {
2473
2806
  cloudsync,
2474
2807
  keyStatus: () => credentials.keyStatus(),
2475
2808
  accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
2809
+ // Same masked-read defect as the host binding above — see the comment
2810
+ // there. Kept identical so the two hosts cannot disagree about whether a
2811
+ // key is stored.
2476
2812
  hasProviderKey: (provider) => {
2477
2813
  const store = engine.settings;
2478
- if (!store || typeof store.get !== 'function' || !provider) return false;
2479
- const row = (store.get(byokNamespace(provider)) || {});
2480
- return !!String(row.key || '').trim();
2814
+ if (!store || !provider) return false;
2815
+ const row = byokNamespace(provider);
2816
+ if (typeof store.rawKey === 'function') {
2817
+ return !!String(store.rawKey(row) || '').trim();
2818
+ }
2819
+ if (typeof store.get !== 'function') return false;
2820
+ return !!((store.get(row) || {}).configured);
2481
2821
  },
2482
2822
  sessionId: () => commandCtx.sessionId,
2483
2823
  tokenSummary,
@@ -33,7 +33,8 @@
33
33
  const path = require('node:path');
34
34
 
35
35
  const { queue, autonomous } = require('./deps.js');
36
- const { createEngine } = require('./engine.js');
36
+ const { createEngine, proEnabled } = require('./engine.js');
37
+ const { loadConfig } = require('./config.js');
37
38
  const { fmtElapsed } = require('./format.js');
38
39
  const limits = require('./limits.js');
39
40
 
@@ -57,7 +58,7 @@ const EXECUTES = new Set(['run', 'proceed', 'retry', 'reconcile']);
57
58
  */
58
59
  function parseFlags(argv) {
59
60
  const opts = { terms: [], json: false, flags: {} };
60
- const takesValue = new Set(['cwd', 'model', 'effort', 'workers', 'max', 'max-rounds', 'source']);
61
+ const takesValue = new Set(['cwd', 'model', 'effort', 'workers', 'max', 'max-rounds', 'source', 'class']);
61
62
  for (let i = 0; i < argv.length; i++) {
62
63
  const a = argv[i];
63
64
  if (a === '--json') {
@@ -154,7 +155,23 @@ function buildEngine({ io, quiet = false }) {
154
155
  if (!client.apiKey) {
155
156
  return { error: `no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV}` };
156
157
  }
157
- const engine = createEngine({ client, getConfirmMode: () => false });
158
+ // No `getClass` — deliberate (see engine.js chat()'s comment): a drain has
159
+ // no interactive session to read, so a queued task's own stated class is
160
+ // what runs. `getProEnabled` IS required even so, because liveClasses()
161
+ // treats a missing one as "off" and would strip `pro` out of the allowed
162
+ // set before the stated class is ever checked against it — leaving a
163
+ // `--class pro` task silently downgraded to DEFAULT_CLASS on every drain.
164
+ const engine = createEngine({
165
+ client,
166
+ getConfirmMode: () => false,
167
+ getProEnabled: () => {
168
+ try {
169
+ return proEnabled(loadConfig());
170
+ } catch {
171
+ return false;
172
+ }
173
+ },
174
+ });
158
175
  // The Pro gate (Phase 7). Built from the SAME shared decision the desktop
159
176
  // uses, bound to this host's channel so a refusal links `?s=cli` and not
160
177
  // `?s=desktop` — see cli/src/entitlement.js. Passed to the worker below as
@@ -264,6 +281,13 @@ async function runQueueCommand(command, argv, io = {}) {
264
281
  item = queue.addTask(process.env, {
265
282
  task,
266
283
  cwd,
284
+ // WHICH TRANSPORT THIS TASK RUNS ON. Omitted means 'aegis' (queue.js
285
+ // normalizes a blank class, and every pre-existing task means the
286
+ // pooled brain). The flag exists so a Pro subscription — the class the
287
+ // desktop has had since claude-pro.js and the queue never did — can be
288
+ // queued from a timer: `--class pro` with no --model lets the claude
289
+ // CLI pick, `--class pro --model opus` pins one of its aliases.
290
+ class: args.flags.class || null,
267
291
  model: args.flags.model || null,
268
292
  effort: args.flags.effort || null,
269
293
  workers: intFlag(args.flags, 'workers'),
@@ -471,8 +495,10 @@ function usageText() {
471
495
  'aegiscode autonomous <command> — the unattended work queue',
472
496
  '',
473
497
  'Commands:',
474
- ' add "<task>" queue a task (--cwd, --model, --effort, --commit,',
498
+ ' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,',
475
499
  ' --single-pass, --workers N, --max-rounds N)',
500
+ ' --class aegis|byok|local|pro (default aegis); --model must',
501
+ ' match the class (pro takes a claude alias, or none at all)',
476
502
  ' list show queued tasks and the tail of the runs log',
477
503
  ' run drain ONE task, then stop',
478
504
  ' proceed drain every pending task (--max N, --stop-on-error, --commit)',