aegiscode 7.0.11 → 7.0.13

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
@@ -89,6 +94,11 @@ Provenance (this binary, and whether it is still the published one):
89
94
 
90
95
  Options:
91
96
  -m, --model <id> pin a model id (see /models; default: server choice)
97
+ --class <name> run this turn on aegis|byok|local|pro. The one-shot
98
+ path had no way to state a class, so '-p' always ran
99
+ the pooled route (DEFAULT_CLASS) no matter what was
100
+ pinned — a headless turn could not use a BYOK key at
101
+ all. '--class byok' needs '--model <provider>:<model>'.
92
102
  --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)
93
103
  --key <key> API key for THIS RUN only — it is not saved. Use
94
104
  "aegiscode login" to store one for good.
@@ -123,6 +133,9 @@ function parseArgs(argv) {
123
133
  base: null,
124
134
  key: null,
125
135
  json: false,
136
+ // No `--class` flag given: `null` (not DEFAULT_CLASS) so the stored config
137
+ // pin still wins, exactly as it does for a launch with no `--model`.
138
+ class: null,
126
139
  stream: true,
127
140
  maxTokens: undefined,
128
141
  light: false,
@@ -202,6 +215,16 @@ function parseArgs(argv) {
202
215
  opts.commandArg = sub;
203
216
  opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
204
217
  argv = [];
218
+ } else if (head === 'connect') {
219
+ // Same position-0 rule and the same passthrough as `gate`/`fingerprint`:
220
+ // everything after `connect` is the subcommand's (`--status`, `--logout`,
221
+ // `--app`, `--base`), so the tail is handed over verbatim — and a bare
222
+ // `connect` means "sign this machine in", which is the thing a new user
223
+ // actually needs, not a help page.
224
+ opts.command = 'connect';
225
+ opts.commandArg = null;
226
+ opts.commandArgv = argv.slice(1);
227
+ argv = [];
205
228
  } else if (head === 'provenance') {
206
229
  // Same position-0 rule and the same reason as `gate`: it is a one-shot
207
230
  // question about THIS BINARY, not a prompt that happens to start with the
@@ -246,6 +269,9 @@ function parseArgs(argv) {
246
269
  case '--model':
247
270
  opts.model = next();
248
271
  break;
272
+ case '--class':
273
+ opts.class = next();
274
+ break;
249
275
  case '--base':
250
276
  opts.base = next();
251
277
  break;
@@ -632,6 +658,20 @@ async function main(argv = process.argv.slice(2)) {
632
658
  });
633
659
  }
634
660
 
661
+ // Signing this machine in (and registering it, on a fresh install). Before a
662
+ // session is built, for the same reason `fingerprint` is: it is a one-shot
663
+ // question with a scriptable answer, and it must work with no terminal at all
664
+ // — the first-run prompt, CI, and `aegiscode connect --status` in a health
665
+ // check all need it without a TUI.
666
+ if (opts.command === 'connect') {
667
+ const { runConnect } = require('../src/connect.js');
668
+ return runConnect(opts.commandArgv || [], {
669
+ json: opts.json,
670
+ stdout: process.stdout,
671
+ stderr: process.stderr,
672
+ });
673
+ }
674
+
635
675
  // The agent-key gate on aegiscodex-dev / aegiscode-plugin. Dispatched here,
636
676
  // before a session is built, for the same reason `fingerprint` is: it is a
637
677
  // one-shot administrative question ("can this machine edit that tree?"),
@@ -797,6 +837,7 @@ async function main(argv = process.argv.slice(2)) {
797
837
 
798
838
  const app = createApp({
799
839
  model: opts.model,
840
+ class: opts.class,
800
841
  stream: opts.stream,
801
842
  light: opts.light,
802
843
  maxTokens: opts.maxTokens,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "7.0.11",
4
+ "version": "7.0.13",
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",
@@ -26,6 +26,7 @@
26
26
  "scripts": {
27
27
  "start": "node bin/aegiscode.js",
28
28
  "predist": "node scripts/predist.mjs",
29
+ "prepack": "node scripts/predist.mjs --quiet",
29
30
  "prepublishOnly": "npm run predist",
30
31
  "precheck": "node scripts/predist.mjs",
31
32
  "check": "node scripts/check.mjs",
@@ -37,7 +37,10 @@ import { sealGate } from './seal-gate.mjs';
37
37
  const HERE = path.dirname(fileURLToPath(import.meta.url));
38
38
  const SHARED = path.join(HERE, '..', '..', 'one', 'scripts', 'predist.mjs');
39
39
 
40
- async function main() {
40
+ async function main(argv) {
41
+ // `--quiet` is forwarded, not swallowed: `prepack` passes it so these
42
+ // progress lines do not corrupt `npm pack --json`; publishing keeps them.
43
+ const args = Array.isArray(argv) ? argv : process.argv.slice(2), quiet = args.includes('--quiet') ? ['--quiet'] : [];
41
44
  const gate = sealGate();
42
45
  if (!gate.ok && !process.env.AEGIS_ALLOW_UNSEALED) {
43
46
  process.stderr.write(
@@ -65,11 +68,11 @@ async function main() {
65
68
  );
66
69
  return 1;
67
70
  }
68
- return shared.main(['--mirror-only']);
71
+ return shared.main(['--mirror-only', ...quiet]);
69
72
  }
70
73
 
71
74
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
72
- process.exitCode = await main();
75
+ process.exitCode = await main(process.argv.slice(2));
73
76
  }
74
77
 
75
78
  export { main, sealGate };
package/src/app.js CHANGED
@@ -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,
@@ -633,10 +710,49 @@ function createApp(options = {}) {
633
710
  // (the engine's splitByokModel), built from the server's provider catalog
634
711
  // plus the provider rows this machine actually holds a key for — so this list
635
712
  // is per-machine, not per-account, and cannot be served by the pooled catalog.
636
- 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
+ }
637
748
 
638
749
  async function loadByokModels({ force = false } = {}) {
639
- 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;
640
756
  if (!force && fresh) return byokCache.models;
641
757
  // An injected engine (tests, embedding) may predate the class surface; an
642
758
  // empty list is the honest answer then, not a fabricated one.
@@ -653,6 +769,7 @@ function createApp(options = {}) {
653
769
  note: m.configured ? 'key on this machine' : `no key — /byok-key ${m.provider}`,
654
770
  }));
655
771
  byokCache.at = Date.now();
772
+ byokCache.declared = declared;
656
773
  return byokCache.models;
657
774
  }
658
775
 
@@ -956,18 +1073,62 @@ function createApp(options = {}) {
956
1073
  // launch. There is no fetch on this path either — the list is a constant, so
957
1074
  // this is the one class whose validation cannot be defeated by being offline.
958
1075
  if (commandCtx.modelClass === 'pro') {
959
- if (proModelIds().has(String(pinned).toLowerCase())) return null;
960
- commandCtx.model = null;
961
- updateConfig({ model: null, currentModelId: null });
962
- emit(
963
- render.renderNotice(
964
- ctx(),
965
- 'warn',
966
- `pinned model "${pinned}" is not one the Claude Code CLI resolves — pin cleared, ` +
967
- `the CLI will choose; /models lists the aliases (${claudePro.PRO_MODELS.map((m) => m.id).join(', ')}).`
968
- )
969
- );
970
- 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;
971
1132
  }
972
1133
  let models;
973
1134
  try {
@@ -1937,6 +2098,15 @@ function createApp(options = {}) {
1937
2098
 
1938
2099
  /** Non-interactive: one prompt, plain output, exit code. */
1939
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();
1940
2110
  adoptLegacyKeyOnce();
1941
2111
  // Same self-service a fresh `aegiscode -p ...` deserves as a fresh
1942
2112
  // interactive session (runInteractive) or a fresh `/ask` (runPrompt):
@@ -1972,19 +2142,127 @@ function createApp(options = {}) {
1972
2142
  // and the reported charge would be whatever the account spent last rather
1973
2143
  // than what this call cost.
1974
2144
  await refreshSpend();
1975
- 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 } : {});
1976
2223
  await refreshSpend();
1977
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);
1978
2227
  if (json) {
1979
2228
  out.write(
1980
2229
  JSON.stringify(
1981
2230
  {
1982
2231
  text: res.text,
1983
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,
1984
2247
  usage: res.usage,
1985
2248
  tokens,
1986
2249
  ms: res.ms,
1987
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 } : {}),
1988
2266
  balance_eur: session.balance,
1989
2267
  },
1990
2268
  null,
@@ -1993,6 +2271,7 @@ function createApp(options = {}) {
1993
2271
  );
1994
2272
  } else {
1995
2273
  out.write(res.text + '\n');
2274
+ if (refusal) err.write(`aegiscode: the provider refused this turn — ${refusal}\n`);
1996
2275
  if (tokens != null) {
1997
2276
  const t = themeOf(ctx());
1998
2277
  out.write(
@@ -2002,7 +2281,7 @@ function createApp(options = {}) {
2002
2281
  );
2003
2282
  }
2004
2283
  }
2005
- return res.interrupted ? 130 : 0;
2284
+ return res.interrupted ? 130 : (refusal ? 1 : 0);
2006
2285
  }
2007
2286
 
2008
2287
  /** Fold one completed turn's usage into the session tallies.
@@ -2399,6 +2678,22 @@ function createApp(options = {}) {
2399
2678
  // it has been turned off, or where this install never opted in. Such a
2400
2679
  // stored value falls back to the live default rather than being trusted.
2401
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
+ }
2402
2697
  if (!opts.model && cfg.model) commandCtx.model = cfg.model;
2403
2698
  // Restored through effortRung(), so a config written by an older build is
2404
2699
  // never a value this one does not send: `null`, `''` and the retired
package/src/commands.js CHANGED
@@ -102,7 +102,9 @@ const { openUrl, URLS } = require('./system.js');
102
102
  // they exist and why they never mutate anything.
103
103
  const sysdiag = require('./sysdiag.js');
104
104
  const { sniffProject, buildAegisMd } = require('./init.js');
105
- const { upgradeAdvice, latestPublishedVersion } = require('./update.js');
105
+ const {
106
+ upgradeAdvice, latestPublishedVersion, applyUpgrade, installMethod,
107
+ } = require('./update.js');
106
108
  const {
107
109
  AGENT_PRESETS, agentRoles, composeAgentPrompt, composeResearchPrompt, composeDebatePrompt,
108
110
  } = require('./agents.js');
@@ -1986,9 +1988,19 @@ const COMMANDS = [
1986
1988
  },
1987
1989
  },
1988
1990
  {
1989
- name: 'upgrade', args: ['action'], hint: '[check]', category: 'support',
1990
- desc: 'Check for a newer published version',
1991
- handler: async (c) => {
1991
+ name: 'upgrade', args: ['action'], hint: '[check|apply]', category: 'support',
1992
+ desc: 'Check for a newer published version (apply: install it now)',
1993
+ handler: async (c, args) => {
1994
+ const action = String((args && args.action) || 'check').toLowerCase();
1995
+ if (!['check', 'apply'].includes(action)) {
1996
+ note(c, 'Usage: /upgrade [check|apply]');
1997
+ c.render();
1998
+ return true;
1999
+ }
2000
+ // The channel is what THIS process was installed from — npm, pip, npx or
2001
+ // a git checkout — so /upgrade never tells a pip install to run npm and
2002
+ // then report success for a second copy that nothing is running from.
2003
+ const method = installMethod();
1992
2004
  note(c, 'Checking the npm registry…');
1993
2005
  c.render();
1994
2006
  // The registry lookup is a blocking `npm view`, so it runs inside the
@@ -1996,7 +2008,35 @@ const COMMANDS = [
1996
2008
  // mode, where a network answer would be a lie).
1997
2009
  const run = c && c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
1998
2010
  const latest = c.ctx && c.ctx.demo ? null : await run(() => Promise.resolve(latestPublishedVersion()));
1999
- panel(c, upgradePanelLines(upgradeAdvice({ latest }).lines));
2011
+ const advice = upgradeAdvice({ latest, method });
2012
+ panel(c, upgradePanelLines(advice.lines));
2013
+ c.render();
2014
+ if (action !== 'apply') return true;
2015
+
2016
+ // Applying is opt-in and never inferred: it replaces the binaries under
2017
+ // a running process, which is a different promise from "a release
2018
+ // exists". A channel with nothing to install says so instead of running
2019
+ // a command that would be a no-op.
2020
+ if (!advice.plan || !advice.plan.apply) {
2021
+ note(c, advice.plan ? `Nothing to install: ${advice.plan.instruction}` : 'Nothing to install.');
2022
+ c.render();
2023
+ return true;
2024
+ }
2025
+ note(c, `Running: ${advice.plan.instruction}`);
2026
+ c.render();
2027
+ const res = applyUpgrade({ method, latest, current: advice.plan.current });
2028
+ if (res.ok && !res.skipped) {
2029
+ // A global install does not touch the process already running, so the
2030
+ // honest last line is "installed, restart to use it" — not "upgraded",
2031
+ // which would claim this session is now on the new version.
2032
+ note(c, `Installed ${advice.plan.latest}. Restart aegiscode to use it.`);
2033
+ if (res.output) for (const line of res.output.split('\n').slice(-6)) note(c, ` ${line}`);
2034
+ } else if (res.skipped) {
2035
+ note(c, `Not applied: ${res.instruction}`);
2036
+ } else {
2037
+ note(c, `Upgrade failed: ${res.error}`);
2038
+ note(c, `Run it yourself: ${res.command}`);
2039
+ }
2000
2040
  c.render();
2001
2041
  return true;
2002
2042
  },
package/src/config.js CHANGED
@@ -70,6 +70,13 @@ const DEFAULT_CONFIG = {
70
70
  // src/update.js). Persisted so a launch reports what the LAST run learned
71
71
  // and never waits on the network to draw its own welcome box.
72
72
  updateCheck: null,
73
+ // Cached `{ checkedAt, behind, required, latest, downloadUrl }` from the
74
+ // once-a-day SERVER check (/api/v1/version, see src/update.js). Separate
75
+ // from `updateCheck` because it answers a different question: the registry
76
+ // says what was published, the server says what it will still serve. A
77
+ // build can be merely superseded (a suggestion) or refused (an outage), and
78
+ // collapsing the two would report the wrong urgency.
79
+ updateCheckServer: null,
73
80
  // No pinned model. This host runs on AEGIS Cloud, whose pinnable ids are the
74
81
  // server's (`/models`) — a client-side default here would have to name one,
75
82
  // and the one it named (`sonnet`) is not advertised by the platform at all: