aegiscode 7.0.10 → 7.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/aegiscode.js CHANGED
@@ -42,6 +42,11 @@ Usage:
42
42
  echo "q" | aegiscode -p - read the prompt from stdin
43
43
 
44
44
  Account:
45
+ aegiscode connect sign this machine in — registers a device account
46
+ if it has none (idempotent per machine), and that
47
+ key is what cloud memory and the record vault use
48
+ aegiscode connect --status is this machine connected? (--json; exit 1 if not)
49
+ aegiscode connect --logout sign out (forget the saved key here)
45
50
  aegiscode login [<key>] save your AEGIS API key (prompts, no echo, if omitted)
46
51
  aegiscode logout remove the saved key
47
52
  aegiscode key status show which key is in use and where it came from
@@ -202,6 +207,16 @@ function parseArgs(argv) {
202
207
  opts.commandArg = sub;
203
208
  opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
204
209
  argv = [];
210
+ } else if (head === 'connect') {
211
+ // Same position-0 rule and the same passthrough as `gate`/`fingerprint`:
212
+ // everything after `connect` is the subcommand's (`--status`, `--logout`,
213
+ // `--app`, `--base`), so the tail is handed over verbatim — and a bare
214
+ // `connect` means "sign this machine in", which is the thing a new user
215
+ // actually needs, not a help page.
216
+ opts.command = 'connect';
217
+ opts.commandArg = null;
218
+ opts.commandArgv = argv.slice(1);
219
+ argv = [];
205
220
  } else if (head === 'provenance') {
206
221
  // Same position-0 rule and the same reason as `gate`: it is a one-shot
207
222
  // question about THIS BINARY, not a prompt that happens to start with the
@@ -632,6 +647,20 @@ async function main(argv = process.argv.slice(2)) {
632
647
  });
633
648
  }
634
649
 
650
+ // Signing this machine in (and registering it, on a fresh install). Before a
651
+ // session is built, for the same reason `fingerprint` is: it is a one-shot
652
+ // question with a scriptable answer, and it must work with no terminal at all
653
+ // — the first-run prompt, CI, and `aegiscode connect --status` in a health
654
+ // check all need it without a TUI.
655
+ if (opts.command === 'connect') {
656
+ const { runConnect } = require('../src/connect.js');
657
+ return runConnect(opts.commandArgv || [], {
658
+ json: opts.json,
659
+ stdout: process.stdout,
660
+ stderr: process.stderr,
661
+ });
662
+ }
663
+
635
664
  // The agent-key gate on aegiscodex-dev / aegiscode-plugin. Dispatched here,
636
665
  // before a session is built, for the same reason `fingerprint` is: it is a
637
666
  // one-shot administrative question ("can this machine edit that tree?"),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.10",
4
+ "version": "7.0.12",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
package/src/app.js CHANGED
@@ -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 {
@@ -1518,6 +1711,7 @@ function createApp(options = {}) {
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);
1520
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);
1521
1715
  else if (o.type === 'resume') lines = overlays.renderResumeList(o.items || [], o.sel || 0, W, rows);
1522
1716
  else if (o.type === 'confirm') lines = render.renderApproval(ctx(), o.info || {}, W).map((s) => [spanRow(s)]);
1523
1717
  if (!lines) return;
@@ -1838,8 +2032,63 @@ function createApp(options = {}) {
1838
2032
 
1839
2033
  // --- entry points ---------------------------------------------------------
1840
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
+
1841
2081
  /** Non-interactive: one prompt, plain output, exit code. */
1842
- 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();
1843
2092
  adoptLegacyKeyOnce();
1844
2093
  // Same self-service a fresh `aegiscode -p ...` deserves as a fresh
1845
2094
  // interactive session (runInteractive) or a fresh `/ask` (runPrompt):
@@ -1875,9 +2124,41 @@ function createApp(options = {}) {
1875
2124
  // and the reported charge would be whatever the account spent last rather
1876
2125
  // than what this call cost.
1877
2126
  await refreshSpend();
1878
- 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 } : {});
1879
2158
  await refreshSpend();
1880
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);
1881
2162
  if (json) {
1882
2163
  out.write(
1883
2164
  JSON.stringify(
@@ -1888,6 +2169,15 @@ function createApp(options = {}) {
1888
2169
  tokens,
1889
2170
  ms: res.ms,
1890
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 } : {}),
1891
2181
  balance_eur: session.balance,
1892
2182
  },
1893
2183
  null,
@@ -1896,6 +2186,7 @@ function createApp(options = {}) {
1896
2186
  );
1897
2187
  } else {
1898
2188
  out.write(res.text + '\n');
2189
+ if (refusal) err.write(`aegiscode: the provider refused this turn — ${refusal}\n`);
1899
2190
  if (tokens != null) {
1900
2191
  const t = themeOf(ctx());
1901
2192
  out.write(
@@ -1905,7 +2196,7 @@ function createApp(options = {}) {
1905
2196
  );
1906
2197
  }
1907
2198
  }
1908
- return res.interrupted ? 130 : 0;
2199
+ return res.interrupted ? 130 : (refusal ? 1 : 0);
1909
2200
  }
1910
2201
 
1911
2202
  /** Fold one completed turn's usage into the session tallies.
@@ -2296,7 +2587,12 @@ function createApp(options = {}) {
2296
2587
  }
2297
2588
  // The class first: a stored BYOK pin is only meaningful under byok, and the
2298
2589
  // pin check right after this reads whichever class won.
2299
- 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;
2300
2596
  if (!opts.model && cfg.model) commandCtx.model = cfg.model;
2301
2597
  // Restored through effortRung(), so a config written by an older build is
2302
2598
  // never a value this one does not send: `null`, `''` and the retired
@@ -2366,7 +2662,22 @@ function createApp(options = {}) {
2366
2662
  * injected readline, `--print` — it stays the linear loop, so output remains
2367
2663
  * pipeable and scriptable.
2368
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
+ */
2369
2672
  async function runInteractive() {
2673
+ try {
2674
+ return await runInteractiveSession();
2675
+ } finally {
2676
+ await releaseLocalModel();
2677
+ }
2678
+ }
2679
+
2680
+ async function runInteractiveSession() {
2370
2681
  const tty =
2371
2682
  !options.readline &&
2372
2683
  options.chatflow !== false &&
package/src/autonomous.js CHANGED
@@ -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