aegisone 1.0.5 → 1.0.8

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 (45) hide show
  1. package/README.md +2 -2
  2. package/bin/aegis.js +28 -3
  3. package/package.json +1 -1
  4. package/scripts/predist.mjs +230 -0
  5. package/src/permissions.js +134 -7
  6. package/src/release.js +14 -5
  7. package/vendor/cli/README.md +42 -3
  8. package/vendor/cli/bin/aegiscode.js +15 -3
  9. package/vendor/cli/package.json +1 -1
  10. package/vendor/cli/src/app.js +167 -37
  11. package/vendor/cli/src/chatflow.js +285 -39
  12. package/vendor/cli/src/commands.js +251 -30
  13. package/vendor/cli/src/config.js +41 -11
  14. package/vendor/cli/src/engine.js +33 -4
  15. package/vendor/cli/src/entitlement.js +30 -1
  16. package/vendor/cli/src/format.js +175 -3
  17. package/vendor/cli/src/overlays.js +13 -9
  18. package/vendor/cli/src/panels.js +19 -6
  19. package/vendor/cli/src/render.js +49 -14
  20. package/vendor/cli/src/screen.js +12 -1
  21. package/vendor/cli/src/screens.js +118 -25
  22. package/vendor/cli/src/todos.js +7 -4
  23. package/vendor/cli/src/tokens.js +31 -1
  24. package/vendor/cli/vendor/client/aegis.js +22 -0
  25. package/vendor/cli/vendor/client/byok-catalog.js +43 -8
  26. package/vendor/cli/vendor/client/user-models.js +378 -0
  27. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +81 -0
  28. package/vendor/cli/vendor/desktop/lib/local/engine.js +447 -14
  29. package/vendor/cli/vendor/desktop/renderer/usage.js +274 -21
  30. package/vendor/cli/vendor/mcp/tools.js +1 -1
  31. package/vendor/desktop/README.md +11 -0
  32. package/vendor/desktop/lib/deep-link.js +35 -1
  33. package/vendor/desktop/lib/local/autonomous.js +81 -0
  34. package/vendor/desktop/lib/local/engine.js +447 -14
  35. package/vendor/desktop/main.js +271 -6
  36. package/vendor/desktop/package.json +1 -1
  37. package/vendor/desktop/preload.js +18 -0
  38. package/vendor/desktop/renderer/app.js +631 -43
  39. package/vendor/desktop/renderer/index.html +4 -5
  40. package/vendor/desktop/renderer/stream-policy.js +24 -2
  41. package/vendor/desktop/renderer/style.css +81 -7
  42. package/vendor/desktop/renderer/usage.js +274 -21
  43. package/vendor/desktop/vendor/aegis.js +22 -0
  44. package/vendor/desktop/vendor/byok-catalog.js +43 -8
  45. package/vendor/desktop/vendor/user-models.js +378 -0
@@ -32,7 +32,7 @@ const path = require('node:path');
32
32
  const { resolveShared } = require('./sharedpaths.js');
33
33
  const shared = require(resolveShared(path.join('desktop', 'renderer', 'usage.js')));
34
34
 
35
- const { RATES, RATE_BASIS, UNPRICED_BY_DESIGN, isPeak, ratesFor, costBreakdown, cacheHitRate } = shared;
35
+ const { RATES, RATE_BASIS, UNPRICED_BY_DESIGN, isPeak, ratesFor, costBreakdown, cacheHitRate, usageBuckets } = shared;
36
36
 
37
37
  // System prompt + tool definitions overhead, roughly, in tokens.
38
38
  const SYSTEM_TOKENS = 18000;
@@ -94,6 +94,28 @@ function estimateTokens(text) {
94
94
  return Math.max(1, Math.ceil([...String(text)].length / 4));
95
95
  }
96
96
 
97
+ /**
98
+ * The same 4:1 rule, from a streamed LENGTH rather than from the text.
99
+ *
100
+ * The live tails count what has arrived as a display width, because they are
101
+ * painted from a counter on a timer rather than from a string — see app.js
102
+ * (`chars += w(chunk.delta)`) and chatflow.js (`streamedChars += w(delta)`).
103
+ * Both sites then label that number `tokens`, so the count form of the
104
+ * heuristic has to live beside the text form. Without it the two producers fed
105
+ * their raw cell count straight into `fmtTokens(...) tokens`, which printed the
106
+ * character count as a token count — the live spinner read ~4x high, and high
107
+ * against every settled figure for the same turn (the desktop meter included),
108
+ * which is exactly the "tokens spent" gap against the reference engine.
109
+ *
110
+ * Returns 0 for an empty stream so a caller can tell "nothing yet" from "some",
111
+ * rather than `estimateTokens`'s floor of 1.
112
+ */
113
+ function estimateTokensFromCells(cells) {
114
+ const n = Number(cells);
115
+ if (!(n > 0)) return 0;
116
+ return Math.ceil(n / 4);
117
+ }
118
+
97
119
  /**
98
120
  * Bucket the transcript's token usage.
99
121
  * input — user prompts + system + tools (per exchange)
@@ -220,7 +242,15 @@ module.exports = {
220
242
  ratesFor,
221
243
  costBreakdown,
222
244
  cacheHitRate,
245
+ // Re-exported so a caller that only needs the bucket shape (the per-turn
246
+ // in/out readout in chatflow.js and app.js) does not have to reach past this
247
+ // module into the desktop bundle itself — and, more importantly, so it has
248
+ // exactly ONE way to read a usage object rather than a hand-rolled
249
+ // `input_tokens ?? prompt_tokens`, which is how the two hosts came to
250
+ // disagree about the same turn's prompt size in the first place.
251
+ usageBuckets,
223
252
  estimateTokens,
253
+ estimateTokensFromCells,
224
254
  transcriptUsage,
225
255
  usageCost,
226
256
  sessionAccounting,
@@ -1440,7 +1440,29 @@ function createClient(opts = {}) {
1440
1440
  .sort((a, b) => a[0] - b[0])
1441
1441
  .map(([idx, c]) => ({ ...c, id: c.id || `call_${idx}` }));
1442
1442
 
1443
+ // The hidden chain-of-thought belongs on the RESULT, not only on the live
1444
+ // stream. `reasoningText` above is accumulated and forwarded to the caller's
1445
+ // `onReasoning`/`onStream` so the thinking can be shown while it happens —
1446
+ // but the resolved result carried only `content`, so every down-stream
1447
+ // diagnosis of "the model spent the whole budget thinking and never wrote a
1448
+ // word" read an empty reasoning channel on THIS lane and concluded there had
1449
+ // been no thinking at all.
1450
+ //
1451
+ // That is not a cosmetic loss. desktop/lib/local/engine.js decides its
1452
+ // reasoning-only recovery from exactly this field (`reasonedButSilent` →
1453
+ // `reasoningTextOf(res)`), so on byok the gate was dead code: DeepSeek
1454
+ // returns `finish_reason: 'stop'` with empty content and a full
1455
+ // `reasoning_content`, which matched neither `isTruncated` (the reason says
1456
+ // 'stop', not 'length') nor the reasoning retry (nothing to detect), and the
1457
+ // turn fell straight through to emptyTurnError — the "backend error: the
1458
+ // model returned no answer … max_tokens 16384" the user sees. Measured live
1459
+ // on byok/deepseek-v4-flash 2026-10-11.
1460
+ //
1461
+ // Kept out of `content` on purpose: deliberation is not an answer, and
1462
+ // folding it in would make a no-answer turn look answered to every caller's
1463
+ // empty-check (see the note at the `reasoningText` accumulation above).
1443
1464
  const message = { content: cleanText };
1465
+ if (reasoningText) message.reasoning_content = reasoningText;
1444
1466
  if (toolCalls.length) message.tool_calls = toolCalls;
1445
1467
  const result = {
1446
1468
  model: resultModel,
@@ -95,14 +95,49 @@ const BYOK_MODEL_ADDITIONS = Object.freeze({
95
95
  // catalog.py) pins exactly one default_model, `claude-sonnet-5`, and
96
96
  // `anthropic-haiku` pins `claude-haiku-4-5` as its own provider row — so
97
97
  // between them an Anthropic BYOK key could pin Sonnet or Haiku but never
98
- // Opus or Fable, the other two members of the current Claude 5 lineup the
99
- // vendor already serves. Both ids already have a priced rate row
100
- // (desktop/renderer/usage.js `opus`/`fable`, matched by family substring),
101
- // so the picker just had no way to offer them, not an unpriced gap. Listed
102
- // under the `anthropic` provider id because that is the row the server
103
- // advertises a configured Anthropic key against — the relay forwards
104
- // whichever of the two names the caller actually pins.
105
- anthropic: Object.freeze(['claude-opus-5', 'claude-fable-5']),
98
+ // Opus or Fable, the other two members of the Claude 5 lineup the vendor
99
+ // already serves. Listed under the `anthropic` provider id because that is
100
+ // the row the server advertises a configured Anthropic key against — the
101
+ // relay forwards whichever of these names the caller actually pins.
102
+ //
103
+ // Verified live 2026-10-11 against `GET https://api.anthropic.com/v1/models`
104
+ // (14 ids, `has_more: false`), which is where every id below is copied from
105
+ // rather than from memory:
106
+ //
107
+ // claude-haiku-5-5, claude-sonnet-5-5, claude-opus-5-5, claude-fable-5-1,
108
+ // claude-opus-5, claude-sonnet-5, claude-fable-5, claude-opus-4-8,
109
+ // claude-opus-4-7, claude-sonnet-4-6, claude-opus-4-6,
110
+ // claude-opus-4-5-20251101, claude-haiku-4-5-20251001,
111
+ // claude-sonnet-4-5-20250929
112
+ //
113
+ // The server's two defaults cover `claude-sonnet-5` and `claude-haiku-4-5`;
114
+ // the five below are the CURRENT members of the lineup it does not name —
115
+ // the 5.5 generation (Haiku, Sonnet, Opus) plus Fable 5.1, and the older
116
+ // Opus 5 / Fable 5 that were already listed. Every one has a priced rate row
117
+ // (desktop/renderer/usage.js, the Claude 5 block), so the picker was missing
118
+ // the ability to OFFER them, not a rate.
119
+ //
120
+ // What is deliberately NOT here, and why it matters more than what is:
121
+ // `claude-opus-4-1` (and its dated form `claude-opus-4-1-20250805`) is
122
+ // RETIRED upstream. Probed live 2026-10-11, `POST /v1/messages` with that
123
+ // model answers HTTP 404 `not_found_error` — the same probe answers
124
+ // `rate_limit_error` (i.e. the model resolved) for every id listed above,
125
+ // which is what makes 404 mean "no such model" rather than "no credit".
126
+ // The engine's own MODELS table still carries a legacy `claude-opus-4-1`
127
+ // row for saved configs, and that is fine — it is a local label that
128
+ // RESOLVES; a client-side catalog addition is a promise the picker will pin
129
+ // and the relay will forward, and this module's whole reason for existing is
130
+ // that a fabricated id "would pin, look accepted, and 404 on the first
131
+ // turn". So Opus 4.1 stays out of the offered list until Anthropic serves
132
+ // it again.
133
+ anthropic: Object.freeze([
134
+ 'claude-opus-5',
135
+ 'claude-fable-5',
136
+ 'claude-opus-5-5',
137
+ 'claude-sonnet-5-5',
138
+ 'claude-haiku-5-5',
139
+ 'claude-fable-5-1',
140
+ ]),
106
141
  // xAI's `grok` descriptor still pins `grok-4.5` as default_model — current
107
142
  // when that descriptor was written, but xAI has since shipped grok-4.6 and
108
143
  // grok-4.7 (flagship, Sept 2026) on the same `grok-4.5`-shaped id
@@ -0,0 +1,378 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * user-models.js — the models the USER declares, in one file every host reads.
5
+ *
6
+ * ── the problem this module removes ────────────────────────────────────────
7
+ *
8
+ * `client/byok-catalog.js` is the list of vendor ids the server's catalog does
9
+ * not name but the relay forwards. It is a *shipping* artifact: every entry is
10
+ * a code change, a review, a release, and a desktop rebuild — and the file's own
11
+ * doc says so ("the durable fix for any of them is the server's MODEL_CATALOG").
12
+ * That is the right shape for the ids AEGIS should be offering everybody. It is
13
+ * the wrong shape for an id one user can call today: a freshly shipped model, a
14
+ * fine-tune, a preview id behind their own vendor key, a Together/Groq/OpenRouter
15
+ * route the relay forwards and the catalog simply has not caught up with.
16
+ *
17
+ * The BYOK relay is a stateless pass-through (`services/byok_service.py`): the
18
+ * caller's own vendor key authenticates upstream and AEGIS forwards the model
19
+ * string it was handed. So for a provider the account holds a key for, an id the
20
+ * VENDOR serves is callable whether or not this repo has ever heard of it. The
21
+ * only thing missing was a way for the user to say so without waiting for us.
22
+ *
23
+ * ── what a user does now ───────────────────────────────────────────────────
24
+ *
25
+ * CLI `/model-add <provider> <model-id>` (and `/model-rm …`)
26
+ * Desktop Settings → "Add a model" → provider + id
27
+ * Either hand-edit `$AEGISCODE_HOME/models.json` (default `~/.aegiscode`)
28
+ *
29
+ * All three end up in the same file, and the file is the whole state:
30
+ * `{ "deepseek": ["deepseek-v4.2-preview"], "anthropic": ["claude-opus-9-1"] }`.
31
+ * Because the CLI and the desktop both read it at the moment they build the
32
+ * picker, a model added in the terminal is in the window's list on its next
33
+ * refresh, with no restart and no release. That is the whole point of putting
34
+ * it in the shared data dir rather than in each host's own config.
35
+ *
36
+ * ── the rules this module keeps (the same ones byok-catalog.js keeps) ──────
37
+ *
38
+ * - NEVER invent a provider. User models are applied only to a provider row
39
+ * the server's catalog already lists. A row this file fabricated would
40
+ * invite a key for a slug the relay may not accept, and the failure would
41
+ * land on the user's first turn — so a declaration naming an unknown
42
+ * provider is preserved in the file and REPORTED (`unmatchedUserProviders`),
43
+ * never rendered as a picker row.
44
+ * - ONE spelling per route. Declarations are de-duplicated on add and again
45
+ * when they are applied, so the same id added twice — or added while the
46
+ * server has started listing it itself — paints one row, not two.
47
+ * - Idempotent and non-mutating. `withUserModels` returns a NEW array, shares
48
+ * the provider objects that gained nothing, and appends after the server's
49
+ * own models so the server's `default_model` keeps its first position (the
50
+ * default is what a bare provider id runs).
51
+ * - Validated, not trusted. A model id is a string the relay forwards to a
52
+ * vendor: a typo does not error here, it 404s upstream on the user's first
53
+ * turn. So ids and provider slugs are shape-checked on write (and re-checked
54
+ * on read, because the file is hand-editable), and a bad row is dropped with
55
+ * a reason rather than silently stored.
56
+ * - Never secret. Only provider slugs and model ids belong here — the file is
57
+ * written 0600 anyway, next to the credential store, because provider/model
58
+ * choice is not the kind of thing another local account should be able to
59
+ * rewrite.
60
+ */
61
+
62
+ const fs = require('node:fs');
63
+ const path = require('node:path');
64
+
65
+ const credentials = require('./credentials.js');
66
+
67
+ /** The file the CLI, the desktop and the MCP host all read. */
68
+ const USER_MODELS_FILE = 'models.json';
69
+ const FILE_MODE = 0o600;
70
+ /** A ceiling, not a policy: enough for a real vendor lineup, small enough that
71
+ * a runaway script cannot turn the picker into a wall of rows. */
72
+ const MAX_MODELS_PER_PROVIDER = 32;
73
+ const MAX_PROVIDERS = 64;
74
+
75
+ /**
76
+ * The provider slug shape the relay addresses (`deepseek`, `together-ai`,
77
+ * `openai-gpt4o-mini`). Lowercase on purpose: `/byok-key OpenAI` resolves to
78
+ * `openai` through the server's catalog, and two spellings of one provider id
79
+ * is exactly how a stored user model comes to never match the row it was meant
80
+ * for.
81
+ */
82
+ const PROVIDER_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
83
+ /**
84
+ * The model id shape. Deliberately permissive across vendors (dots for Claude,
85
+ * dashes for DeepSeek, slashes for the org-prefixed routes OpenRouter and
86
+ * Together use) and deliberately exclusive of two things: whitespace, because a
87
+ * model id with a space in it is a paste accident, and `:`, because
88
+ * `provider:model` is the id the picker and the engine already speak — a model
89
+ * id containing a colon would make that split ambiguous.
90
+ */
91
+ const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;
92
+
93
+ /** The data dir (`$AEGISCODE_HOME` or `~/.aegiscode`), from the ONE definition. */
94
+ function userModelsDir(opts) {
95
+ return (opts && opts.dir) || credentials.aegisHome(opts && opts.env);
96
+ }
97
+
98
+ /** The absolute path of the shared user-model file. */
99
+ function userModelsPath(opts) {
100
+ return path.join(userModelsDir(opts), USER_MODELS_FILE);
101
+ }
102
+
103
+ /** Throw a message that says what to type instead. */
104
+ function badValue(what, raw, why) {
105
+ return new Error(
106
+ `aegiscode: ${what} ${JSON.stringify(String(raw))} is not usable — ${why}`
107
+ );
108
+ }
109
+
110
+ /** One provider slug, validated. Accepts the server's own spelling idempotently. */
111
+ function sanitizeProvider(raw) {
112
+ const s = String(raw == null ? '' : raw).trim().toLowerCase();
113
+ if (!s) throw badValue('provider', raw, 'the provider id is empty');
114
+ if (!PROVIDER_RE.test(s)) {
115
+ throw badValue(
116
+ 'provider',
117
+ raw,
118
+ 'a provider id is lowercase letters, digits, dot, dash or underscore ' +
119
+ '(the id `/byok` prints)'
120
+ );
121
+ }
122
+ return s;
123
+ }
124
+
125
+ /** One model id, validated. Ids are compared verbatim — never case-folded. */
126
+ function sanitizeModel(raw) {
127
+ const s = String(raw == null ? '' : raw).trim();
128
+ if (!s) throw badValue('model id', raw, 'the model id is empty');
129
+ if (/:/.test(s)) {
130
+ throw badValue(
131
+ 'model id',
132
+ raw,
133
+ "'provider:model' is how a picked model is addressed, so a model id cannot contain a colon"
134
+ );
135
+ }
136
+ if (!MODEL_RE.test(s)) {
137
+ throw badValue(
138
+ 'model id',
139
+ raw,
140
+ 'a model id has no spaces — it is the string sent to the vendor ' +
141
+ '(e.g. deepseek-v4.2-preview, claude-opus-9-1)'
142
+ );
143
+ }
144
+ return s;
145
+ }
146
+
147
+ /** True when `value` is a plain object (never an array, never null). */
148
+ function isPlainObject(value) {
149
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
150
+ }
151
+
152
+ /**
153
+ * Read the file and return BOTH the usable map and what was dropped.
154
+ *
155
+ * Never throws: a corrupt, unreadable or hand-mangled file reads as "no user
156
+ * models", because a declaration store must not be able to take the model
157
+ * picker down. But it does not lie about it either — `invalid` carries one
158
+ * `{ provider, model, reason }` per row that was skipped, which is what the
159
+ * hosts surface so a hand-edited typo is visible instead of looking like "the
160
+ * feature did nothing".
161
+ */
162
+ function load(opts) {
163
+ const file = userModelsPath(opts);
164
+ const invalid = [];
165
+ let raw;
166
+ try {
167
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
168
+ } catch (err) {
169
+ // ENOENT is the normal state of a fresh install, not a problem to report.
170
+ if (err && err.code === 'ENOENT') return { dir: userModelsDir(opts), file, map: {}, invalid };
171
+ invalid.push({ provider: null, model: null, reason: `unreadable: ${(err && err.message) || err}` });
172
+ return { dir: userModelsDir(opts), file, map: {}, invalid };
173
+ }
174
+ const map = {};
175
+ if (!isPlainObject(raw)) {
176
+ invalid.push({ provider: null, model: null, reason: 'the file must be an object of provider → [model ids]' });
177
+ return { dir: userModelsDir(opts), file, map, invalid };
178
+ }
179
+ for (const [providerRaw, modelsRaw] of Object.entries(raw)) {
180
+ if (providerRaw === 'version' || providerRaw === '$schema') continue;
181
+ let provider;
182
+ try {
183
+ provider = sanitizeProvider(providerRaw);
184
+ } catch (err) {
185
+ invalid.push({ provider: providerRaw, model: null, reason: err.message });
186
+ continue;
187
+ }
188
+ const list = Array.isArray(modelsRaw) ? modelsRaw : [modelsRaw];
189
+ const seen = new Set();
190
+ const keep = [];
191
+ for (const m of list) {
192
+ let model;
193
+ try {
194
+ model = sanitizeModel(m);
195
+ } catch (err) {
196
+ invalid.push({ provider, model: m, reason: err.message });
197
+ continue;
198
+ }
199
+ if (seen.has(model)) continue; // one spelling per route, in the file too
200
+ seen.add(model);
201
+ keep.push(model);
202
+ }
203
+ if (keep.length) map[provider] = keep;
204
+ }
205
+ return { dir: userModelsDir(opts), file, map, invalid };
206
+ }
207
+
208
+ /** Just the usable provider → [ids] map (`load()` without the report). */
209
+ function readUserModels(opts) {
210
+ return load(opts).map;
211
+ }
212
+
213
+ /** The ids declared for one provider (an empty array when there are none). */
214
+ function userModelIdsFor(provider, opts) {
215
+ let id;
216
+ try {
217
+ id = sanitizeProvider(provider);
218
+ } catch {
219
+ return [];
220
+ }
221
+ const map = readUserModels(opts);
222
+ return Array.isArray(map[id]) ? map[id].slice() : [];
223
+ }
224
+
225
+ /** Write the map atomically, 0600, pretty-printed so it stays hand-editable. */
226
+ function writeMap(map, opts) {
227
+ const file = userModelsPath(opts);
228
+ fs.mkdirSync(path.dirname(file), { recursive: true });
229
+ const tmp = `${file}.tmp-${process.pid}`;
230
+ fs.writeFileSync(tmp, JSON.stringify(map, null, 2) + '\n', { mode: FILE_MODE });
231
+ fs.renameSync(tmp, file);
232
+ try {
233
+ fs.chmodSync(file, FILE_MODE);
234
+ } catch {
235
+ /* Windows: POSIX modes are a no-op and ACLs are the OS's business */
236
+ }
237
+ return map;
238
+ }
239
+
240
+ /**
241
+ * Declare one model id for one provider.
242
+ *
243
+ * Returns `{ file, provider, model, added, models }` — `added: false` when the
244
+ * id was already declared, so the caller can say "already there" instead of
245
+ * claiming a change it did not make. Rejects a provider or id that fails the
246
+ * shape checks above, and refuses to grow a single provider past the ceiling.
247
+ */
248
+ function addUserModel(provider, model, opts) {
249
+ const id = sanitizeProvider(provider);
250
+ const modelId = sanitizeModel(model);
251
+ const map = readUserModels(opts);
252
+ const have = Array.isArray(map[id]) ? map[id].slice() : [];
253
+ if (have.includes(modelId)) {
254
+ return { file: userModelsPath(opts), provider: id, model: modelId, added: false, models: have };
255
+ }
256
+ if (have.length >= MAX_MODELS_PER_PROVIDER) {
257
+ throw new Error(
258
+ `aegiscode: ${id} already carries ${have.length} user models (the cap) — ` +
259
+ 'remove one with /model-rm before adding another.'
260
+ );
261
+ }
262
+ if (!map[id] && Object.keys(map).length >= MAX_PROVIDERS) {
263
+ throw new Error(
264
+ `aegiscode: ${Object.keys(map).length} providers already carry user models (the cap).`
265
+ );
266
+ }
267
+ const models = [...have, modelId];
268
+ const next = { ...map, [id]: models };
269
+ writeMap(next, opts);
270
+ return { file: userModelsPath(opts), provider: id, model: modelId, added: true, models };
271
+ }
272
+
273
+ /**
274
+ * Retire one declaration. Returns `{ …, removed }`; `removed: false` means it
275
+ * was not declared, which is a report and not an error (the file is shared, so
276
+ * another host may have removed it a moment ago).
277
+ */
278
+ function removeUserModel(provider, model, opts) {
279
+ const id = sanitizeProvider(provider);
280
+ const modelId = sanitizeModel(model);
281
+ const map = readUserModels(opts);
282
+ const have = Array.isArray(map[id]) ? map[id].slice() : [];
283
+ if (!have.includes(modelId)) {
284
+ return { file: userModelsPath(opts), provider: id, model: modelId, removed: false, models: have };
285
+ }
286
+ const models = have.filter((m) => m !== modelId);
287
+ const next = { ...map };
288
+ if (models.length) next[id] = models;
289
+ else delete next[id];
290
+ writeMap(next, opts);
291
+ return { file: userModelsPath(opts), provider: id, model: modelId, removed: true, models };
292
+ }
293
+
294
+ /** The model ids an entry names, tolerating the server's two shapes. */
295
+ function modelIdsOf(provider) {
296
+ return (Array.isArray(provider && provider.models) ? provider.models : [])
297
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
298
+ .map((m) => (typeof m === 'string' ? m.trim() : ''))
299
+ .filter(Boolean);
300
+ }
301
+
302
+ /** The provider array out of either shape the server sends (or `[]`). */
303
+ function providerArray(providers) {
304
+ if (Array.isArray(providers)) return providers;
305
+ if (Array.isArray(providers && providers.providers)) return providers.providers;
306
+ return null;
307
+ }
308
+
309
+ /**
310
+ * The server's BYOK catalog with the USER's declared models applied.
311
+ *
312
+ * @param {Array<object>|object} providers the payload (array, or `{providers}`)
313
+ * @param {object} [extra] an explicit provider → [ids] map. Omitted by every
314
+ * host (they want the file); passing it is what makes this function pure and
315
+ * therefore testable without touching a real data dir.
316
+ * @returns {Array<object>} a NEW array. Providers that gained nothing come back
317
+ * as the SAME objects, an unknown provider is never fabricated, and an
318
+ * empty/absent payload returns `[]` rather than a list invented from the file.
319
+ */
320
+ function withUserModels(providers, extra) {
321
+ const raw = providerArray(providers);
322
+ if (!raw) return [];
323
+ const map = extra === undefined ? readUserModels() : isPlainObject(extra) ? extra : {};
324
+ const out = [];
325
+ for (const p of raw) {
326
+ if (!p || typeof p !== 'object') continue;
327
+ const id = typeof p.id === 'string' ? p.id.trim() : '';
328
+ const declared = id && Array.isArray(map[id]) ? map[id] : null;
329
+ if (!declared || !declared.length) {
330
+ out.push(p);
331
+ continue;
332
+ }
333
+ const have = new Set(modelIdsOf(p));
334
+ const missing = declared
335
+ .map((m) => String(m).trim())
336
+ .filter((m) => m && !have.has(m));
337
+ // Nothing to add — hand back the SAME object, so a complete payload is
338
+ // byte-identical after this pass and a caller cannot tell it ran.
339
+ if (!missing.length) {
340
+ out.push(p);
341
+ continue;
342
+ }
343
+ const models = Array.isArray(p.models) ? p.models : [];
344
+ out.push({ ...p, models: [...models, ...missing] });
345
+ }
346
+ return out;
347
+ }
348
+
349
+ /**
350
+ * Declared providers the payload does NOT list — the honest half of the rules
351
+ * above. A host reports these ("no provider row for `foo` — the relay takes
352
+ * keys for: …") instead of either hiding the declaration or showing a row that
353
+ * would 401 on its first turn.
354
+ */
355
+ function unmatchedUserProviders(providers, extra) {
356
+ const raw = providerArray(providers) || [];
357
+ const map = extra === undefined ? readUserModels() : isPlainObject(extra) ? extra : {};
358
+ const known = new Set(
359
+ raw.map((p) => (p && typeof p.id === 'string' ? p.id.trim() : '')).filter(Boolean)
360
+ );
361
+ return Object.keys(map).filter((id) => !known.has(id));
362
+ }
363
+
364
+ module.exports = {
365
+ USER_MODELS_FILE,
366
+ MAX_MODELS_PER_PROVIDER,
367
+ userModelsDir,
368
+ userModelsPath,
369
+ sanitizeProvider,
370
+ sanitizeModel,
371
+ load,
372
+ readUserModels,
373
+ userModelIdsFor,
374
+ addUserModel,
375
+ removeUserModel,
376
+ withUserModels,
377
+ unmatchedUserProviders,
378
+ };
@@ -73,6 +73,83 @@ const MAX_ROUND_STOPS = 3;
73
73
  */
74
74
  const WRITE_TOOLS = new Set(['writeFile', 'editFile']);
75
75
 
76
+ // ── Auto mode and the round horizon ─────────────────────────────────────────
77
+ //
78
+ // The two halves of "auto mode" the upstream engine (aegiscodex-dev) defines
79
+ // are independent, and a host that wires only one of them is *not* running auto
80
+ // mode — it is running "no approval cards", which is half the feature and all
81
+ // the friction:
82
+ //
83
+ // 1. no approval keystroke per mutating tool call;
84
+ // 2. a turn that hits its round horizon is EXTENDED silently a few times
85
+ // before a human is asked.
86
+ //
87
+ // (1) is the posture (the desktop's Tool-approvals switch, the CLI's
88
+ // /automode); (2) needs the arithmetic below, and the plugin's Electron host
89
+ // had none of it — with auto mode ON, every horizon hit still raised the
90
+ // blocking round card, which is precisely the question auto mode exists to stop
91
+ // asking ("12 rounds — keep going?" answered the same way every time).
92
+ //
93
+ // Ported verbatim from the engine's src/autonomous.js (DEFAULT_AUTO_CONTINUES,
94
+ // autoContinueLimit, autoRoundsDefault, autoContinuePlan) rather than vendored,
95
+ // because this repo hosts no build of that ESM module — but with the SAME
96
+ // numbers and the SAME env knobs, so a turn behaves identically in either
97
+ // client. cli/src/chatflow.js carries the third copy, which is what the CLI
98
+ // presenter uses to answer the ask.
99
+
100
+ /** Automatic continuations an attended turn may take while auto mode is on. */
101
+ const DEFAULT_AUTO_CONTINUES = 3;
102
+
103
+ /**
104
+ * The auto-continue allowance, honouring AEGIS_AUTO_CONTINUE_MAX.
105
+ *
106
+ * Bounded and pure, and a garbage value falls back to the default rather than
107
+ * to 0: an unparseable env var must not silently switch auto mode off, because
108
+ * the visible symptom of that ("why is it asking me again?") points nowhere
109
+ * near the environment.
110
+ */
111
+ function autoContinueLimit(env = process.env) {
112
+ const n = Number.parseInt(env && env.AEGIS_AUTO_CONTINUE_MAX, 10);
113
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_AUTO_CONTINUES;
114
+ }
115
+
116
+ /**
117
+ * Values of AEGIS_AUTO_ROUNDS that mean "start in manual mode". Anything else —
118
+ * unset, empty, a typo like `flase` — leaves auto mode's default in place, so a
119
+ * misspelt opt-out cannot silently disable the mode the operator asked for.
120
+ * Same set, same reasoning, as the engine's AUTO_ROUNDS_OFF.
121
+ */
122
+ const AUTO_ROUNDS_OFF = new Set(['0', 'false', 'off', 'no']);
123
+
124
+ /** False only when AEGIS_AUTO_ROUNDS explicitly says so. */
125
+ function autoRoundsDefault(env = process.env) {
126
+ const raw = env && env.AEGIS_AUTO_ROUNDS;
127
+ if (raw === undefined || raw === null) return true;
128
+ const val = String(raw).trim().toLowerCase();
129
+ if (!val) return true;
130
+ return !AUTO_ROUNDS_OFF.has(val);
131
+ }
132
+
133
+ /**
134
+ * Decide what one round-horizon ask becomes while auto mode is on.
135
+ *
136
+ * Pure, because this is budget arithmetic on a keystroke-less path: the caller
137
+ * only renders the answer and must not be trusted to keep the count. `used` is
138
+ * the running tally the caller holds and echoes back, so an ask that IS shown
139
+ * to the human resets it — the human was asked, so the next block of automatic
140
+ * continuations starts clean.
141
+ *
142
+ * { auto: true, used: n } → answer the ask "yes" without a dialog
143
+ * { auto: false, used: n } → show the real ask (allowance spent, or off)
144
+ */
145
+ function autoContinuePlan({ on = false, used = 0, limit = DEFAULT_AUTO_CONTINUES } = {}) {
146
+ const cap = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_AUTO_CONTINUES;
147
+ const spent = Number.isFinite(used) && used > 0 ? Math.floor(used) : 0;
148
+ if (!on) return { auto: false, used: spent, cap };
149
+ if (spent >= cap) return { auto: false, used: 0, cap };
150
+ return { auto: true, used: spent + 1, cap };
151
+ }
152
+
76
153
  /** The path a file-writing tool call names, in either spelling the engine uses. */
77
154
  function writtenPath(tool) {
78
155
  const args = (tool && tool.args) || {};
@@ -906,6 +983,10 @@ module.exports = {
906
983
  isAutonomousRequest,
907
984
  maxRounds,
908
985
  withRoundHorizon,
986
+ DEFAULT_AUTO_CONTINUES,
987
+ autoContinueLimit,
988
+ autoRoundsDefault,
989
+ autoContinuePlan,
909
990
  resolveModel,
910
991
  ignoredEnvModel,
911
992
  resolveEffort,