aegiscode 7.0.11 → 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.11",
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
@@ -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,
@@ -633,10 +692,49 @@ function createApp(options = {}) {
633
692
  // (the engine's splitByokModel), built from the server's provider catalog
634
693
  // plus the provider rows this machine actually holds a key for — so this list
635
694
  // is per-machine, not per-account, and cannot be served by the pooled catalog.
636
- 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
+ }
637
730
 
638
731
  async function loadByokModels({ force = false } = {}) {
639
- 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;
640
738
  if (!force && fresh) return byokCache.models;
641
739
  // An injected engine (tests, embedding) may predate the class surface; an
642
740
  // empty list is the honest answer then, not a fabricated one.
@@ -653,6 +751,7 @@ function createApp(options = {}) {
653
751
  note: m.configured ? 'key on this machine' : `no key — /byok-key ${m.provider}`,
654
752
  }));
655
753
  byokCache.at = Date.now();
754
+ byokCache.declared = declared;
656
755
  return byokCache.models;
657
756
  }
658
757
 
@@ -956,18 +1055,62 @@ function createApp(options = {}) {
956
1055
  // launch. There is no fetch on this path either — the list is a constant, so
957
1056
  // this is the one class whose validation cannot be defeated by being offline.
958
1057
  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;
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;
971
1114
  }
972
1115
  let models;
973
1116
  try {
@@ -1937,6 +2080,15 @@ function createApp(options = {}) {
1937
2080
 
1938
2081
  /** Non-interactive: one prompt, plain output, exit code. */
1939
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();
1940
2092
  adoptLegacyKeyOnce();
1941
2093
  // Same self-service a fresh `aegiscode -p ...` deserves as a fresh
1942
2094
  // interactive session (runInteractive) or a fresh `/ask` (runPrompt):
@@ -1972,9 +2124,41 @@ function createApp(options = {}) {
1972
2124
  // and the reported charge would be whatever the account spent last rather
1973
2125
  // than what this call cost.
1974
2126
  await refreshSpend();
1975
- 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 } : {});
1976
2158
  await refreshSpend();
1977
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);
1978
2162
  if (json) {
1979
2163
  out.write(
1980
2164
  JSON.stringify(
@@ -1985,6 +2169,15 @@ function createApp(options = {}) {
1985
2169
  tokens,
1986
2170
  ms: res.ms,
1987
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 } : {}),
1988
2181
  balance_eur: session.balance,
1989
2182
  },
1990
2183
  null,
@@ -1993,6 +2186,7 @@ function createApp(options = {}) {
1993
2186
  );
1994
2187
  } else {
1995
2188
  out.write(res.text + '\n');
2189
+ if (refusal) err.write(`aegiscode: the provider refused this turn — ${refusal}\n`);
1996
2190
  if (tokens != null) {
1997
2191
  const t = themeOf(ctx());
1998
2192
  out.write(
@@ -2002,7 +2196,7 @@ function createApp(options = {}) {
2002
2196
  );
2003
2197
  }
2004
2198
  }
2005
- return res.interrupted ? 130 : 0;
2199
+ return res.interrupted ? 130 : (refusal ? 1 : 0);
2006
2200
  }
2007
2201
 
2008
2202
  /** Fold one completed turn's usage into the session tallies.
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: