aegisone 1.0.18 → 1.0.21

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 (61) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -1
  3. package/scripts/bump.mjs +29 -4
  4. package/scripts/predist.mjs +15 -2
  5. package/src/dispatch.js +1 -0
  6. package/vendor/cli/bin/aegiscode.js +41 -0
  7. package/vendor/cli/package.json +2 -1
  8. package/vendor/cli/scripts/predist.mjs +6 -3
  9. package/vendor/cli/src/app.js +436 -24
  10. package/vendor/cli/src/autonomous.js +19 -2
  11. package/vendor/cli/src/chatflow.js +77 -4
  12. package/vendor/cli/src/commands.js +220 -10
  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 +98 -8
  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 +54 -0
  20. package/vendor/cli/src/provenance.lock.json +3 -3
  21. package/vendor/cli/src/screens.js +14 -1
  22. package/vendor/cli/src/update.js +103 -12
  23. package/vendor/cli/vendor/client/aegis.js +169 -3
  24. package/vendor/cli/vendor/client/credentials.js +9 -2
  25. package/vendor/cli/vendor/client/drive-connect.js +87 -0
  26. package/vendor/cli/vendor/client/drive-upload.js +176 -0
  27. package/vendor/cli/vendor/client/google-signin.js +127 -0
  28. package/vendor/cli/vendor/client/record-vault.js +431 -113
  29. package/vendor/cli/vendor/client/update.js +366 -8
  30. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +134 -11
  31. package/vendor/cli/vendor/desktop/lib/local/engine.js +111 -26
  32. package/vendor/cli/vendor/desktop/lib/local/prompt.js +67 -37
  33. package/vendor/cli/vendor/desktop/lib/local/tools.js +49 -13
  34. package/vendor/cli/vendor/desktop/lib/settings.js +65 -24
  35. package/vendor/desktop/lib/auto.js +11 -7
  36. package/vendor/desktop/lib/fingerprint.js +76 -17
  37. package/vendor/desktop/lib/google-connect.js +171 -0
  38. package/vendor/desktop/lib/local/claude-pro.js +134 -11
  39. package/vendor/desktop/lib/local/engine.js +111 -26
  40. package/vendor/desktop/lib/local/prompt.js +67 -37
  41. package/vendor/desktop/lib/local/tools.js +49 -13
  42. package/vendor/desktop/lib/settings.js +65 -24
  43. package/vendor/desktop/main.js +270 -36
  44. package/vendor/desktop/package.json +5 -2
  45. package/vendor/desktop/preload.js +45 -12
  46. package/vendor/desktop/renderer/app.js +691 -22
  47. package/vendor/desktop/renderer/budget.js +18 -9
  48. package/vendor/desktop/renderer/companion.js +225 -0
  49. package/vendor/desktop/renderer/fingerprint.css +16 -0
  50. package/vendor/desktop/renderer/fingerprint.js +136 -2
  51. package/vendor/desktop/renderer/index.html +302 -121
  52. package/vendor/desktop/renderer/provider-toolbar.js +136 -0
  53. package/vendor/desktop/renderer/providers.js +261 -0
  54. package/vendor/desktop/renderer/style.css +547 -171
  55. package/vendor/desktop/vendor/aegis.js +169 -3
  56. package/vendor/desktop/vendor/credentials.js +9 -2
  57. package/vendor/desktop/vendor/drive-connect.js +87 -0
  58. package/vendor/desktop/vendor/drive-upload.js +176 -0
  59. package/vendor/desktop/vendor/google-signin.js +127 -0
  60. package/vendor/desktop/vendor/record-vault.js +431 -113
  61. package/vendor/desktop/vendor/update.js +366 -8
@@ -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,83 @@ 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
+
184
+ /**
185
+ * One tool call, readable — the arg summary published in `--json`'s `tool_log`.
186
+ *
187
+ * Truncated on a character boundary so a row stays a record a person can read
188
+ * while still showing WHAT each call was. A list of tool names cannot tell
189
+ * "read four files" apart from "ran the same test twelve times", and the
190
+ * archived AEGIS rows carried only names.
191
+ *
192
+ * @param {unknown} a the call's arguments
193
+ * @returns {string} a single line, at most 140 characters
194
+ */
195
+ function briefArgs(a) {
196
+ let s;
197
+ try { s = typeof a === 'string' ? a : JSON.stringify(a ?? ''); } catch { s = String(a); }
198
+ s = String(s).replace(/\s+/g, ' ').trim();
199
+ return s.length > 140 ? `${s.slice(0, 137)}...` : s;
200
+ }
201
+
125
202
  function createApp(options = {}) {
126
203
  const opts = {
127
204
  model: null,
@@ -225,6 +302,18 @@ function createApp(options = {}) {
225
302
  // reason confirmMode is a callback: a captured value made `/class`
226
303
  // cosmetic, changing the panel and not what the next turn ran on.
227
304
  getClass: () => commandCtx.modelClass,
305
+ // Whether the `pro` class is enabled (config.js `proEnabled`, off by
306
+ // default). Read per call for the same reason getClass is: `/class pro
307
+ // off` must remove it from the picker and stop the very next turn, not
308
+ // the next launch. A read failure answers "off" — fail closed, because
309
+ // the alternative spends a subscription nobody opted into.
310
+ getProEnabled: () => {
311
+ try {
312
+ return proEnabled(loadConfig());
313
+ } catch {
314
+ return false;
315
+ }
316
+ },
228
317
  getConfirmMode: () => {
229
318
  if (options.confirmMode !== undefined) return confirmMode;
230
319
  // AEGISONE D8 rule 5 — the skip posture, resolved by the SAME function
@@ -621,10 +710,49 @@ function createApp(options = {}) {
621
710
  // (the engine's splitByokModel), built from the server's provider catalog
622
711
  // plus the provider rows this machine actually holds a key for — so this list
623
712
  // is per-machine, not per-account, and cannot be served by the pooled catalog.
624
- const byokCache = { at: 0, models: [] };
713
+ const byokCache = { at: 0, models: [], declared: '' };
714
+
715
+ /**
716
+ * The user-model declarations (`$AEGISCODE_HOME/models.json`) as one
717
+ * comparable string, or '' when they cannot be read.
718
+ *
719
+ * The byok list is not only the server's: `engine.listModels('byok')` folds
720
+ * the USER's own declarations into each provider row (`client/user-models.js`
721
+ * `withUserModels`), so the id set can change with no network call and no
722
+ * provider catalog change. A custom provider in particular has NO catalog
723
+ * model at all — its rows exist solely because someone declared them — so a
724
+ * cache keyed only on time shows an empty provider for up to five minutes
725
+ * after the declaration was written.
726
+ *
727
+ * That is the cross-host case this exists for: the desktop's Custom provider
728
+ * card, `/model-add` in another terminal, and a hand-edited file all write
729
+ * the SAME file, and none of them can reach this process's `byokCache`. So
730
+ * the file's content is part of the cache key: a declaration made elsewhere
731
+ * is visible the next time the picker is opened, not five minutes later.
732
+ *
733
+ * Read through `engine.userModels()` rather than the path, so this stays one
734
+ * store and one implementation (the CLI's engine is the same module the
735
+ * desktop uses). A store that throws is treated as unchanged — the time
736
+ * window still expires the cache, so a broken read cannot pin stale rows
737
+ * forever.
738
+ */
739
+ function declaredModelsKey() {
740
+ try {
741
+ if (typeof engine.userModels !== 'function') return '';
742
+ const map = (engine.userModels() || {}).map || {};
743
+ return JSON.stringify(Object.keys(map).sort().map((p) => [p, map[p]]));
744
+ } catch {
745
+ return '';
746
+ }
747
+ }
625
748
 
626
749
  async function loadByokModels({ force = false } = {}) {
627
- const fresh = byokCache.models.length && Date.now() - byokCache.at < MODEL_CACHE_MS;
750
+ const declared = declaredModelsKey();
751
+ const fresh =
752
+ byokCache.models.length &&
753
+ Date.now() - byokCache.at < MODEL_CACHE_MS &&
754
+ // The declarations are part of the key: see declaredModelsKey().
755
+ declared === byokCache.declared;
628
756
  if (!force && fresh) return byokCache.models;
629
757
  // An injected engine (tests, embedding) may predate the class surface; an
630
758
  // empty list is the honest answer then, not a fabricated one.
@@ -641,6 +769,7 @@ function createApp(options = {}) {
641
769
  note: m.configured ? 'key on this machine' : `no key — /byok-key ${m.provider}`,
642
770
  }));
643
771
  byokCache.at = Date.now();
772
+ byokCache.declared = declared;
644
773
  return byokCache.models;
645
774
  }
646
775
 
@@ -652,7 +781,14 @@ function createApp(options = {}) {
652
781
  * able to chat on the server's own default.
653
782
  */
654
783
  async function listModelsFor(cls) {
655
- const want = HOST_CLASSES.includes(cls) ? cls : commandCtx.modelClass;
784
+ // The OFFERED set, not HOST_CLASSES: a class that is not selectable (a
785
+ // disabled `pro`) yields NOTHING rather than the live class's rows. The
786
+ // merged picker tags whatever comes back as belonging to the class it
787
+ // asked about, so substituting pooled rows here would paint pooled ids as
788
+ // Pro rows — and pinning one would move the session onto the subscription.
789
+ const allowed = selectableClasses();
790
+ if (cls && !allowed.includes(cls) && HOST_CLASSES.includes(cls)) return [];
791
+ const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
656
792
  try {
657
793
  if (want === 'byok') {
658
794
  const byok = await loadByokModels();
@@ -777,7 +913,13 @@ function createApp(options = {}) {
777
913
  * not on; only an absent/unknown `cls` may fall back to the live one.
778
914
  */
779
915
  function classScopedModels(byokOverride, cls) {
780
- const want = HOST_CLASSES.includes(cls) ? cls : commandCtx.modelClass;
916
+ const allowed = selectableClasses();
917
+ const want = allowed.includes(cls) ? cls : commandCtx.modelClass;
918
+ // A disabled `pro` yields no rows at all — not the pooled ones either,
919
+ // because the caller asked for pro's id space and answering with pooled ids
920
+ // is the cross-class mix-up this branch exists to prevent (the merged
921
+ // picker would tag them `pro`).
922
+ if (cls === 'pro' && !allowed.includes('pro')) return [];
781
923
  // The Pro class' list is its own alias set, never the pooled catalog: a
782
924
  // pooled id pinned under pro would be sent to `claude --model`, which
783
925
  // resolves aliases and real model names, not AEGIS ids — the same
@@ -820,9 +962,25 @@ function createApp(options = {}) {
820
962
  return !s.includes(':');
821
963
  }
822
964
 
965
+ /**
966
+ * The classes selectable right now. `pro` is behind the `proEnabled` gate
967
+ * (config.js, default off): HOST_CLASSES says this host CAN run it, this says
968
+ * whether it has been opted into. Every surface that lists or validates a
969
+ * class reads this, so the gate cannot be honoured in one place and ignored
970
+ * in another. A config read failure answers "pro is off" (fail closed).
971
+ */
972
+ function selectableClasses() {
973
+ try {
974
+ return offeredClasses(proEnabled(loadConfig()));
975
+ } catch {
976
+ return offeredClasses(false);
977
+ }
978
+ }
979
+
823
980
  /**
824
981
  * Switch the live class. Refuses anything this host cannot run (engine.js's
825
- * HOST_CLASSES is the authority).
982
+ * HOST_CLASSES is the authority) and anything it does not offer — `pro` needs
983
+ * a one-time `/class pro on` first.
826
984
  *
827
985
  * A pin is cleared when it does not belong to the class being entered: a
828
986
  * pooled id pinned under byok would be parsed as provider `<pooled id>` and
@@ -833,8 +991,17 @@ function createApp(options = {}) {
833
991
  */
834
992
  function switchClass(next) {
835
993
  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(', ')}` };
994
+ const allowed = selectableClasses();
995
+ if (!allowed.includes(want)) {
996
+ if (want === 'pro') {
997
+ return {
998
+ ok: false,
999
+ error:
1000
+ 'the pro class (your Claude Code subscription) is off by default — ' +
1001
+ 'enable it once with `/class pro on`',
1002
+ };
1003
+ }
1004
+ return { ok: false, error: `unknown class "${next}" — classes: ${allowed.join(', ')}` };
838
1005
  }
839
1006
  const prev = commandCtx.modelClass;
840
1007
  commandCtx.modelClass = want;
@@ -906,18 +1073,62 @@ function createApp(options = {}) {
906
1073
  // launch. There is no fetch on this path either — the list is a constant, so
907
1074
  // this is the one class whose validation cannot be defeated by being offline.
908
1075
  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;
1076
+ if (!proModelIds().has(String(pinned).toLowerCase())) {
1077
+ commandCtx.model = null;
1078
+ updateConfig({ model: null, currentModelId: null });
1079
+ emit(
1080
+ render.renderNotice(
1081
+ ctx(),
1082
+ 'warn',
1083
+ `pinned model "${pinned}" is not one the Claude Code CLI resolves — pin cleared, ` +
1084
+ `the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((m) => m.id).join(', ')}).`
1085
+ )
1086
+ );
1087
+ return pinned;
1088
+ }
1089
+ // The alias resolves — but resolving an alias is not the same as having
1090
+ // anything to spend on it. This is the phantom-pin case aegiscodex-dev
1091
+ // learned first (phantomPin() in its src/backend.js): when the host has
1092
+ // no subscription and no console key, the `claude` child has no usable
1093
+ // credential, and the turn does not fail loudly here — it fails after a
1094
+ // round-trip with "Invalid API key" or "You've hit your session limit",
1095
+ // which reads like a provider outage rather than a missing credential.
1096
+ // Checked before the turn, so the user is told why and the pin stops
1097
+ // re-creating the problem on the next launch.
1098
+ let proCallable = true;
1099
+ try {
1100
+ const st = claudePro.claudeProStatus({ env: process.env });
1101
+ // `credentialPresent` — not `subscriptionPresent`, and not a fresh read
1102
+ // of `process.env` here. Three different questions live in this area and
1103
+ // conflating them is how the pin went unchecked in the first place:
1104
+ // - "is there a subscription to shadow?" → subscriptionPresent
1105
+ // (excludes a bare console key on disk, by design)
1106
+ // - "can this host serve a pro turn?" → credentialPresent (this one)
1107
+ // - "is this env value a credential?" → childEnvPlan's verdict
1108
+ // The third is why this reads a field instead of testing
1109
+ // `process.env.ANTHROPIC_API_KEY` directly: the planner REFUSES a value
1110
+ // that would be dropped from the child, so an env var alone is not
1111
+ // evidence of a route. See childEnvPlan / isAnthropicConsoleKey.
1112
+ proCallable = !!st.credentialPresent;
1113
+ } catch {
1114
+ // An unprovable credential is not a proven absence: leave the pin alone.
1115
+ proCallable = true;
1116
+ }
1117
+ if (!proCallable) {
1118
+ commandCtx.model = null;
1119
+ updateConfig({ model: null, currentModelId: null });
1120
+ emit(
1121
+ render.renderNotice(
1122
+ ctx(),
1123
+ 'warn',
1124
+ `pinned model "${pinned}" needs a Claude Pro subscription or an ` +
1125
+ `ANTHROPIC_API_KEY, and this host has neither — pin cleared. ` +
1126
+ `Run \`claude /login\`, export a console key, or \`/class pro off\`.`
1127
+ )
1128
+ );
1129
+ return pinned;
1130
+ }
1131
+ return null;
921
1132
  }
922
1133
  let models;
923
1134
  try {
@@ -1518,6 +1729,7 @@ function createApp(options = {}) {
1518
1729
  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
1730
  else if (o.type === 'effort') lines = overlays.renderEffortPicker(o.sel || 0, W, commandCtx.effort);
1520
1731
  else if (o.type === 'class') lines = overlays.renderClassPicker(o.items || [], o.sel || 0, W, o.current || commandCtx.modelClass, classLabelOf);
1732
+ else if (o.type === 'provider') lines = overlays.renderProviderPicker(o.items || [], o.sel || 0, W, o.current, o.hint);
1521
1733
  else if (o.type === 'resume') lines = overlays.renderResumeList(o.items || [], o.sel || 0, W, rows);
1522
1734
  else if (o.type === 'confirm') lines = render.renderApproval(ctx(), o.info || {}, W).map((s) => [spanRow(s)]);
1523
1735
  if (!lines) return;
@@ -1838,8 +2050,63 @@ function createApp(options = {}) {
1838
2050
 
1839
2051
  // --- entry points ---------------------------------------------------------
1840
2052
 
2053
+ /**
2054
+ * Give the local lane back its hardware, on the way out.
2055
+ *
2056
+ * The desktop has done this from its quit path since the class shipped
2057
+ * (`main.js` before-quit -> `engine.unloadLocalModels` -> local.js
2058
+ * `unloadAll`): "closing the app closes the model". The CLI had no equivalent
2059
+ * at all, so exiting a session after a `local` turn left the weights resident
2060
+ * for the remainder of the pin the turn itself set — `DEFAULT_WARM_SECS` is
2061
+ * 1800 (local.js), i.e. up to thirty minutes of a loaded model on hardware
2062
+ * nobody was using anymore, which is the one cost this lane exists to not
2063
+ * have.
2064
+ *
2065
+ * Best-effort by construction: `unloadAll` never throws and each request is
2066
+ * bounded by `UNLOAD_TIMEOUT_MS` (4s) inside the transport, so a daemon that
2067
+ * is slow, wedged or already gone cannot turn a clean exit into a hang or a
2068
+ * crash. Called from every exit path of every entry point below — INCLUDING
2069
+ * `-p`, whose whole life may be one local turn.
2070
+ *
2071
+ * Deliberately not a `process.on('exit')` handler: that callback cannot
2072
+ * await, so the request would be issued into a process that is already
2073
+ * tearing the socket down. Awaiting at the end of the session is what makes
2074
+ * the eviction actually reach the daemon.
2075
+ */
2076
+ async function releaseLocalModel() {
2077
+ if (!engine || typeof engine.unloadLocalModels !== 'function') return;
2078
+ try {
2079
+ await engine.unloadLocalModels();
2080
+ } catch {
2081
+ /* the model's own keep-alive lapses; never fail an exit over cleanup */
2082
+ }
2083
+ }
2084
+
2085
+ /**
2086
+ * One-shot run: the turn itself (`runOnceTurn`), then the local lane handed
2087
+ * back even if that turn threw. A `-p` run can BE a whole local session, so
2088
+ * it needs the same closing the interactive loop gets — see
2089
+ * `releaseLocalModel`.
2090
+ */
2091
+ async function runOnce(prompt, opts = {}) {
2092
+ try {
2093
+ return await runOnceTurn(prompt, opts);
2094
+ } finally {
2095
+ await releaseLocalModel();
2096
+ }
2097
+ }
2098
+
1841
2099
  /** Non-interactive: one prompt, plain output, exit code. */
1842
- async function runOnce(prompt, { json = false } = {}) {
2100
+ async function runOnceTurn(prompt, { json = false } = {}) {
2101
+ // The one-shot path used to skip this entirely, so `-p` always ran
2102
+ // DEFAULT_CLASS ('aegis', the pooled route) no matter what the user had
2103
+ // pinned: `/class byok` (or a saved byok/byok-model pin) applied to the
2104
+ // interactive loop only. That made the documented headless entry point
2105
+ // unable to use BYOK at all — it billed the pool instead, or, on a box
2106
+ // whose pooled backend was down, failed with a provider timeout while the
2107
+ // user's own key sat unused. Same restore the REPL does, before the first
2108
+ // turn and therefore before `ask()` resolves a route.
2109
+ restorePrefs();
1843
2110
  adoptLegacyKeyOnce();
1844
2111
  // Same self-service a fresh `aegiscode -p ...` deserves as a fresh
1845
2112
  // interactive session (runInteractive) or a fresh `/ask` (runPrompt):
@@ -1875,19 +2142,127 @@ function createApp(options = {}) {
1875
2142
  // and the reported charge would be whatever the account spent last rather
1876
2143
  // than what this call cost.
1877
2144
  await refreshSpend();
1878
- const res = await ask(prompt);
2145
+ // Under `--json`, stdout carries ONE document and nothing else. A turn that
2146
+ // uses tools renders a row per call (`ask()`'s `tool` presenter below), and
2147
+ // those rows went to `out` — so the document was preceded by ANSI-coloured
2148
+ // progress text and no parser could read it. Measured: a tool-using turn
2149
+ // emitted 1238 bytes of `Bash ⎿ ✔` rows before the JSON, which is why the
2150
+ // harness sweep recorded `tokens_in: 0` for tasks the CLI had in fact
2151
+ // SOLVED. The rows are still shown, just on stderr, where a human sees them
2152
+ // and a parser does not.
2153
+ // Every tool call this turn really made, by name. `--json` is the only
2154
+ // machine-readable surface the CLI has, and the harness measures "how much
2155
+ // work did the loop do" from it. A tool-using turn that reports no tools is
2156
+ // indistinguishable from a turn that answered from memory — the benchmark
2157
+ // scored three tasks SOLVED with `tool_calls: 0` while the workspace showed
2158
+ // genuine edits, because nothing published the count.
2159
+ const toolsUsed = [];
2160
+ const toolLog = [];
2161
+ const jsonPresenter = json
2162
+ ? {
2163
+ tool: (tool) => {
2164
+ // One entry per CALL, not per frame. The engine reports every tool
2165
+ // twice — `phase: 'run'` before it executes and `phase: 'done'`
2166
+ // with the outcome — and both arrive here. Pushing on both doubled
2167
+ // `tools` (a 6-call turn published 12-14 names), and the benchmark
2168
+ // adapters count array elements as calls, so AEGIS's tool count was
2169
+ // inflated by exactly 2x while its `tokens_per_solved` was flattered
2170
+ // by the same factor. The done frame now only settles the entry it
2171
+ // belongs to.
2172
+ const phase = tool && tool.phase;
2173
+ if (phase === 'done') {
2174
+ const match = (tool.id && toolLog.find((c) => c.id === tool.id && c.settled !== true))
2175
+ || (tool.id ? null : toolLog[toolLog.length - 1]);
2176
+ if (match) {
2177
+ match.settled = true;
2178
+ match.ok = tool.ok !== false;
2179
+ } else {
2180
+ // A `done` frame with no unsettled entry to settle is a call we
2181
+ // are learning about for the first time — the engine batched or
2182
+ // outlived the matching `run` frame (seen on the sweep: one
2183
+ // `run` then every later call arriving already `done`). Falling
2184
+ // back to "settle the last entry" silently discarded those
2185
+ // calls: a task that ran 7 tools published `tool_calls: 1`
2186
+ // while its own stderr rendered all 7. Record it, already
2187
+ // settled, so counting stays at one per call.
2188
+ if (tool && tool.name) toolsUsed.push(tool.name);
2189
+ toolLog.push({
2190
+ name: (tool && tool.name) || null,
2191
+ id: (tool && tool.id) || null,
2192
+ args: briefArgs(tool && tool.args),
2193
+ settled: true,
2194
+ ok: tool.ok !== false,
2195
+ });
2196
+ }
2197
+ } else {
2198
+ if (tool && tool.name) toolsUsed.push(tool.name);
2199
+ toolLog.push({
2200
+ name: (tool && tool.name) || null,
2201
+ id: (tool && tool.id) || null,
2202
+ // The same brief rendering a reader gets on stderr, so an
2203
+ // archived run can say WHAT the calls were rather than only how
2204
+ // many. `--json` used to publish the count and no evidence:
2205
+ // a 14-entry `tools` array was all a benchmark row could see.
2206
+ args: briefArgs(tool && tool.args),
2207
+ settled: false,
2208
+ ok: null,
2209
+ });
2210
+ }
2211
+ const diff = tool && tool.preview !== undefined ? tool.preview : null;
2212
+ const lines = render.renderTurn(
2213
+ ctx(),
2214
+ { role: 'tool', label: tool.name, args: tool.args, ok: tool.ok, diff, diffOpen: false },
2215
+ width()
2216
+ );
2217
+ for (const l of Array.isArray(lines) ? lines : [lines]) err.write(l + '\n');
2218
+ return undefined;
2219
+ },
2220
+ }
2221
+ : null;
2222
+ const res = await ask(prompt, jsonPresenter ? { presenter: jsonPresenter } : {});
1879
2223
  await refreshSpend();
1880
2224
  const tokens = usageTokens(res.usage);
2225
+ // A refusal that arrived as content: report it as a failure, not an answer.
2226
+ const refusal = providerRefusal(res.text, res.usage);
1881
2227
  if (json) {
1882
2228
  out.write(
1883
2229
  JSON.stringify(
1884
2230
  {
1885
2231
  text: res.text,
1886
2232
  model: res.model,
2233
+ // The route this turn actually took, so a run can PROVE its class
2234
+ // instead of asserting it in prose. The benchmark spent two sweeps
2235
+ // comparing a pooled-relay CLI turn against a BYOK-direct desktop
2236
+ // turn while both rows claimed `deepseek-flash`; the 3.5× cost gap
2237
+ // was the transport, and nothing in the document said so. `--json`
2238
+ // is the only machine-readable surface this CLI has.
2239
+ class: commandCtx.modelClass,
2240
+ // The engine stamps `calls` onto this accumulator (one per provider
2241
+ // dispatch), so it is the turn's real round-trip count. Republished
2242
+ // under the name every benchmark adapter already looks for:
2243
+ // `harness-bench.mjs` read `e.rounds` and, finding nothing, fell
2244
+ // back to `1`, so every archived AEGIS row claimed a single round
2245
+ // for turns that made dozens.
2246
+ rounds: (res.usage && Number(res.usage.calls)) || null,
1887
2247
  usage: res.usage,
1888
2248
  tokens,
1889
2249
  ms: res.ms,
1890
2250
  interrupted: res.interrupted,
2251
+ // Present only when the turn actually called tools, so a reader can
2252
+ // tell "answered from memory" from "did work" without inferring it
2253
+ // from a token count.
2254
+ ...(toolsUsed.length ? { tools: toolsUsed } : {}),
2255
+ // The evidence beside the count: name + a one-line arg summary per
2256
+ // call, with the outcome written back from the matching done frame.
2257
+ // `tools` above is kept unchanged because five archived runs and a
2258
+ // test read it, and it is the field that says HOW MANY rounds
2259
+ // touched a tool; this one says which.
2260
+ ...(toolLog.length ? { tool_log: toolLog } : {}),
2261
+ // Present only when the reply was a provider refusal. A caller that
2262
+ // gates on `error` can now tell a dead turn from a working one;
2263
+ // before this field existed both were `{text, tokens: 0}` with
2264
+ // exit 0, and the harness scored a broken run as a scored zero.
2265
+ ...(refusal ? { error: refusal } : {}),
1891
2266
  balance_eur: session.balance,
1892
2267
  },
1893
2268
  null,
@@ -1896,6 +2271,7 @@ function createApp(options = {}) {
1896
2271
  );
1897
2272
  } else {
1898
2273
  out.write(res.text + '\n');
2274
+ if (refusal) err.write(`aegiscode: the provider refused this turn — ${refusal}\n`);
1899
2275
  if (tokens != null) {
1900
2276
  const t = themeOf(ctx());
1901
2277
  out.write(
@@ -1905,7 +2281,7 @@ function createApp(options = {}) {
1905
2281
  );
1906
2282
  }
1907
2283
  }
1908
- return res.interrupted ? 130 : 0;
2284
+ return res.interrupted ? 130 : (refusal ? 1 : 0);
1909
2285
  }
1910
2286
 
1911
2287
  /** Fold one completed turn's usage into the session tallies.
@@ -2296,7 +2672,28 @@ function createApp(options = {}) {
2296
2672
  }
2297
2673
  // The class first: a stored BYOK pin is only meaningful under byok, and the
2298
2674
  // pin check right after this reads whichever class won.
2299
- if (HOST_CLASSES.includes(cfg.modelClass)) commandCtx.modelClass = cfg.modelClass;
2675
+ //
2676
+ // Gated on the OFFERED set, not HOST_CLASSES: a config written while `pro`
2677
+ // was enabled must not restore a subscription session onto a machine where
2678
+ // it has been turned off, or where this install never opted in. Such a
2679
+ // stored value falls back to the live default rather than being trusted.
2680
+ if (selectableClasses().includes(cfg.modelClass)) commandCtx.modelClass = cfg.modelClass;
2681
+ // A `--class` flag outranks the stored pin, the same way `--model` outranks
2682
+ // `cfg.model` on the next line. Clamped to the OFFERED set for the reason
2683
+ // the restore above is: a class this host cannot run (or `pro` on an install
2684
+ // that never opted in) must not be honoured just because it was typed.
2685
+ // An unknown or unoffered value is refused rather than silently downgraded
2686
+ // to the pooled route — a headless turn that asked for byok and got billed
2687
+ // to the pool is the exact defect this flag exists to fix.
2688
+ if (opts.class) {
2689
+ const want = String(opts.class).trim().toLowerCase();
2690
+ if (!selectableClasses().includes(want)) {
2691
+ throw new Error(
2692
+ `--class ${opts.class}: not available on this host (offered: ${selectableClasses().join(', ')})`
2693
+ );
2694
+ }
2695
+ commandCtx.modelClass = want;
2696
+ }
2300
2697
  if (!opts.model && cfg.model) commandCtx.model = cfg.model;
2301
2698
  // Restored through effortRung(), so a config written by an older build is
2302
2699
  // never a value this one does not send: `null`, `''` and the retired
@@ -2366,7 +2763,22 @@ function createApp(options = {}) {
2366
2763
  * injected readline, `--print` — it stays the linear loop, so output remains
2367
2764
  * pipeable and scriptable.
2368
2765
  */
2766
+ /**
2767
+ * Interactive session: the loop itself (`runInteractiveSession`), then the
2768
+ * local lane handed back. Wrapped for the same reason `runOnce` is: the loop
2769
+ * has several exits (a declined onboarding, `/quit`, a reset key stream, the
2770
+ * linear REPL), and "closing the session closes the model" must hold on all
2771
+ * of them rather than on the one path a `return` happens to reach.
2772
+ */
2369
2773
  async function runInteractive() {
2774
+ try {
2775
+ return await runInteractiveSession();
2776
+ } finally {
2777
+ await releaseLocalModel();
2778
+ }
2779
+ }
2780
+
2781
+ async function runInteractiveSession() {
2370
2782
  const tty =
2371
2783
  !options.readline &&
2372
2784
  options.chatflow !== false &&
@@ -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
 
@@ -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