aegiscode 6.8.30 → 6.8.33

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.
@@ -0,0 +1,294 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * topup.js — the shared token-bank top-up: what to ask for, how to read the
5
+ * answer, and how to know the money arrived.
6
+ *
7
+ * WHY THIS IS SHARED AND NOT HOST CODE. A top-up ends server-side: Stripe's
8
+ * webhook credits the bank (aegis1 `services/billing_service.py`,
9
+ * `add_funds()`), and the browser landing page is pure UI on top of that. But
10
+ * that page (`/topup`) is `@login_required` against a browser SESSION, and
11
+ * `POST /api/v1/auth/register-device` mints the account this product
12
+ * auto-provisions with a password that is never returned and an email at
13
+ * `@device.aegiscloud`. So the very account auto-provision creates cannot sign
14
+ * in to the page it was just sent to: following that link lands on a login
15
+ * wall, and the user concludes the payment failed while the money and the
16
+ * credit are both real.
17
+ *
18
+ * The key that STARTED the checkout is enough to READ the result —
19
+ * `login_required` accepts `X-API-Key`/Bearer, and the same credential
20
+ * authenticates `GET /api/token-bank/balance` — so each host confirms the
21
+ * credit itself. Three hosts need that: the desktop (`desktop/main.js`), the
22
+ * terminal (`aegiscode topup` / `/topup`), and whatever comes next.
23
+ *
24
+ * What must never differ between them, and therefore lives here:
25
+ *
26
+ * 1. the AMOUNT rule — aegis1 rejects anything outside 2..1000 EUR with 400,
27
+ * and a client that accepts 1 EUR is a round trip the user pays for with
28
+ * a rejection message;
29
+ * 2. the PAYLOAD reading (`bankAmount`) — aegis1 has shipped
30
+ * `balance_micros`, `balance_eur`, `balance` and a bare number, and two
31
+ * hosts guessing differently is how one screen shows a credit the other
32
+ * misses;
33
+ * 3. the UNKNOWN-vs-ZERO rule — an unreadable bank stays unknown. Reading it
34
+ * as zero would make the `{}` case look like a real baseline, so the FIRST
35
+ * credit would be silently swallowed as "no change", and elsewhere a zero
36
+ * manufactures a paywall out of a timeout;
37
+ * 4. the RISING-READ rule — announce on the first read strictly above the
38
+ * baseline, once, then stop.
39
+ *
40
+ * What is deliberately NOT here: the timer. The desktop's watch must live in
41
+ * the main process (test/auto.test.mjs asserts "neither renderer starts a timer
42
+ * of its own"), unref'd, because the window stays open and a payment may never
43
+ * complete. The terminal's must block, because the process exits and a
44
+ * detached timer would be killed before the credit lands. Those are two
45
+ * schedulers over one state machine — and the state machine (`createCreditWatch`)
46
+ * is the part that must not drift, so that is what this file owns.
47
+ *
48
+ * No I/O of its own and no host imports: it takes the client it is handed.
49
+ */
50
+
51
+ /** aegis1's own bounds (`app.py` token_bank_topup): outside these is a 400. */
52
+ const TOPUP_MIN_EUR = 2;
53
+ const TOPUP_MAX_EUR = 1000;
54
+ /** The server's default when the body omits the amount. */
55
+ const TOPUP_DEFAULT_EUR = 10;
56
+
57
+ /** Poll period and window for the credit watch: ~2 minutes, then stop asking. */
58
+ const TOPUP_POLL_MS = 4000;
59
+ const TOPUP_POLL_TRIES = 30;
60
+
61
+ /**
62
+ * Read a euro amount out of an aegis1 token-bank payload, across the shapes the
63
+ * server has used (`balance_micros`, `balance_eur`, `balance`, or a bare
64
+ * number). Returns null when nothing numeric is present — an unreadable bank
65
+ * must stay UNKNOWN rather than read as a zero.
66
+ */
67
+ function bankAmount(res) {
68
+ if (res == null) return null;
69
+ if (typeof res === 'number') return isFinite(res) ? res : null;
70
+ if (typeof res === 'string') {
71
+ const n = Number(res.trim());
72
+ return res.trim() !== '' && isFinite(n) ? n : null;
73
+ }
74
+ if (typeof res !== 'object') return null;
75
+ if (res.balance_micros != null) {
76
+ const n = Number(res.balance_micros);
77
+ return isFinite(n) ? n / 1e6 : null;
78
+ }
79
+ for (const key of ['balance_eur', 'balance', 'bank', 'balance_eur_cents']) {
80
+ if (!(key in res)) continue;
81
+ const n = Number(res[key]);
82
+ if (!isFinite(n)) continue;
83
+ return key === 'balance_eur_cents' ? n / 100 : n;
84
+ }
85
+ if (res.data) return bankAmount(res.data);
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * Parse a user-typed amount against the server's own bounds.
91
+ *
92
+ * Rejecting here rather than letting aegis1 answer 400 is not cosmetic: the
93
+ * whole point of `/topup 1` failing locally is that it says WHY in the same
94
+ * breath, instead of printing the server's "Amount must be between 2 and 1000
95
+ * EUR" after a round trip on a slow connection.
96
+ *
97
+ * @param {string|number} raw the typed argument ('' or undefined ⇒ the default)
98
+ * @param {number} [fallback] default when nothing was typed
99
+ * @returns {{ok:boolean, amount:number|null, message:string|null}}
100
+ */
101
+ function parseTopupAmount(raw, fallback) {
102
+ const str = String(raw == null ? '' : raw).trim();
103
+ if (!str) {
104
+ const d = fallback == null ? TOPUP_DEFAULT_EUR : Number(fallback);
105
+ return { ok: true, amount: d, message: null };
106
+ }
107
+ // A euro figure with the separators a person actually types: `$20`, `20 EUR`,
108
+ // `20eur`. No `\b` before the word — `25eur` has its boundary between the 5
109
+ // and the e, so a boundary-anchored pattern strips nothing and the figure is
110
+ // refused as "not an amount".
111
+ const cleaned = str.replace(/[€$]|eur(o|os)?\b/gi, '').trim();
112
+ const n = Number(cleaned);
113
+ if (!isFinite(n) || cleaned === '') {
114
+ return { ok: false, amount: null, message: `"${str}" is not an amount — give a number of euro, e.g. /topup 20` };
115
+ }
116
+ if (!Number.isInteger(n)) {
117
+ return { ok: false, amount: null, message: `${n} EUR is not whole — Stripe charges whole euro here (e.g. /topup 20)` };
118
+ }
119
+ if (n < TOPUP_MIN_EUR || n > TOPUP_MAX_EUR) {
120
+ return {
121
+ ok: false,
122
+ amount: null,
123
+ message: `${n} EUR is outside the accepted range — top-ups are ${TOPUP_MIN_EUR}..${TOPUP_MAX_EUR} EUR`,
124
+ };
125
+ }
126
+ return { ok: true, amount: n, message: null };
127
+ }
128
+
129
+ /**
130
+ * Classify a failed checkout the way a user needs to hear it. The shared client
131
+ * attaches `err.status` / `err.data` while the failure is still in the host, so
132
+ * the status is read here rather than string-matched out of a message later.
133
+ *
134
+ * `setupRequired` is aegis1's 503 `setup_required` — Stripe is not configured
135
+ * on the deployment, which is NOT the user's problem to fix and must not be
136
+ * reported as one.
137
+ *
138
+ * @returns {{status:number, message:string, hint:string|null, setupRequired:boolean}}
139
+ */
140
+ function classifyTopupError(err) {
141
+ const status = (err && (err.status || (err.response && err.response.status))) || 0;
142
+ const data = (err && err.data) || {};
143
+ const message = err && err.message ? err.message : String(err);
144
+ const setupRequired = Boolean(data.setup_required) || status === 503;
145
+ if (setupRequired) {
146
+ return {
147
+ status: status || 503,
148
+ message,
149
+ hint: 'this deployment has no payment provider configured — top-ups are unavailable here, not on your side',
150
+ setupRequired: true,
151
+ };
152
+ }
153
+ if (status === 400) {
154
+ return { status, message, hint: `pick an amount between ${TOPUP_MIN_EUR} and ${TOPUP_MAX_EUR} EUR`, setupRequired: false };
155
+ }
156
+ if (status === 401 || status === 403) {
157
+ return {
158
+ status,
159
+ message,
160
+ hint: 'the account key was refused — save a fresh one (aegiscode login) and try again',
161
+ setupRequired: false,
162
+ };
163
+ }
164
+ if (status === 402) {
165
+ return { status, message, hint: 'the server refused the checkout for this account — see /billing for the account state', setupRequired: false };
166
+ }
167
+ if (!status) {
168
+ return { status: 0, message, hint: 'the server could not be reached — check the connection and retry', setupRequired: false };
169
+ }
170
+ return { status, message, hint: null, setupRequired: false };
171
+ }
172
+
173
+ /**
174
+ * Create a token-bank checkout and hand back the Stripe-hosted URL.
175
+ *
176
+ * Never throws: a host that has to tell 401 from 400 from 503 must receive the
177
+ * fields, and an exception crossing an IPC boundary loses `status` and `data`.
178
+ *
179
+ * @param {object} aegis the client whose key pays
180
+ * @param {number} amount EUR, already validated by parseTopupAmount
181
+ * @returns {Promise<{ok:boolean, url:string|null, status:number, message:string|null,
182
+ * hint:string|null, setupRequired:boolean, amount:number}>}
183
+ */
184
+ async function startTopup(aegis, amount) {
185
+ const eur = amount == null ? TOPUP_DEFAULT_EUR : Number(amount);
186
+ if (!aegis || typeof aegis.tokenBankTopup !== 'function') {
187
+ return {
188
+ ok: false, url: null, status: 0, amount: eur, setupRequired: false,
189
+ message: 'this host has no billing client', hint: null,
190
+ };
191
+ }
192
+ try {
193
+ const data = await aegis.tokenBankTopup(eur);
194
+ const url = data && data.url ? String(data.url) : null;
195
+ if (!url) {
196
+ // A 2xx with no URL is a success shape we cannot act on. Saying so beats
197
+ // opening "undefined" in a browser and calling it a payment.
198
+ return {
199
+ ok: false, url: null, status: 0, amount: eur, setupRequired: false,
200
+ message: 'the server accepted the request but returned no checkout URL',
201
+ hint: 'check the account in the browser at /billing, then retry',
202
+ };
203
+ }
204
+ return { ok: true, url, status: 0, message: null, hint: null, setupRequired: false, amount: eur };
205
+ } catch (err) {
206
+ const info = classifyTopupError(err);
207
+ return { ok: false, url: null, amount: eur, ...info };
208
+ }
209
+ }
210
+
211
+ /**
212
+ * The credit watch, as a state machine a host drives.
213
+ *
214
+ * `tick()` reads the bank once and returns the next state; the HOST decides
215
+ * when to call it again (an unref'd interval in the desktop's main process, an
216
+ * awaited sleep loop in the terminal). One read per call, so a slow or failing
217
+ * balance call can never overlap itself and double-announce.
218
+ *
219
+ * States:
220
+ * `pending` — nothing conclusive yet; call again
221
+ * `credited` — the bank read strictly above the baseline: announce, then stop
222
+ * `expired` — the window ran out with no rising read
223
+ *
224
+ * A failed or unreadable read is `pending`, never a zero: offline is unknown,
225
+ * and unknown must not become a baseline (see the header).
226
+ *
227
+ * @param {object} aegis the client whose key read the balance
228
+ * @param {object} [opts]
229
+ * @param {number} [opts.maxTries] reads before giving up (default TOPUP_POLL_TRIES)
230
+ * @returns {{tick:function():Promise<{state:string,amount:number|null,baseline:number|null}>,
231
+ * stop:function():void, baseline:number|null, credited:number|null, tries:number}}
232
+ */
233
+ function createCreditWatch(aegis, opts) {
234
+ const options = opts || {};
235
+ const maxTries = options.maxTries || TOPUP_POLL_TRIES;
236
+ const state = { baseline: null, credited: null, tries: 0, stopped: false };
237
+ return {
238
+ get baseline() {
239
+ return state.baseline;
240
+ },
241
+ get credited() {
242
+ return state.credited;
243
+ },
244
+ get tries() {
245
+ return state.tries;
246
+ },
247
+ stop() {
248
+ state.stopped = true;
249
+ },
250
+ async tick() {
251
+ const answer = (s, amount) => ({ state: s, amount: amount == null ? null : amount, baseline: state.baseline });
252
+ if (state.stopped) return answer(state.credited != null ? 'credited' : 'stopped', state.credited);
253
+ state.tries += 1;
254
+ if (state.tries > maxTries) {
255
+ state.stopped = true;
256
+ return answer('expired', null);
257
+ }
258
+ let now = null;
259
+ try {
260
+ now = bankAmount(await aegis.tokenBankBalance());
261
+ } catch {
262
+ return answer('pending', null); // offline or restarting: the next read retries
263
+ }
264
+ if (now === null) return answer('pending', null);
265
+ if (state.baseline === null) {
266
+ // The first successful read is the pre-payment figure. Stripe checkout
267
+ // takes longer than one poll, so this is normally still the old balance
268
+ // — but if it is already higher we still announce on the NEXT read,
269
+ // because the baseline is what "higher" is measured against.
270
+ state.baseline = now;
271
+ return answer('pending', null);
272
+ }
273
+ if (now > state.baseline) {
274
+ state.stopped = true;
275
+ state.credited = now;
276
+ return answer('credited', now);
277
+ }
278
+ return answer('pending', null);
279
+ },
280
+ };
281
+ }
282
+
283
+ module.exports = {
284
+ TOPUP_MIN_EUR,
285
+ TOPUP_MAX_EUR,
286
+ TOPUP_DEFAULT_EUR,
287
+ TOPUP_POLL_MS,
288
+ TOPUP_POLL_TRIES,
289
+ bankAmount,
290
+ parseTopupAmount,
291
+ classifyTopupError,
292
+ startTopup,
293
+ createCreditWatch,
294
+ };
@@ -186,10 +186,146 @@ function updateNotice({
186
186
  return { latest, behind: !!(latest && isNewer(latest, current)) };
187
187
  }
188
188
 
189
- /** One line for the welcome box, or null when there is nothing to say. */
189
+ /**
190
+ * "What happens next", from a check result — the ONE verdict every applier
191
+ * consumes (AEGISONE, decision D7).
192
+ *
193
+ * There are two *mechanics* — `npm i -g` for the CLI's channel and
194
+ * `electron-updater` for the window's — and that is deliberate: they install
195
+ * different things. What must not be duplicated is the *decision*: whether
196
+ * there is anything to do, which version it is, which applier owns it and what
197
+ * the user is told to run. Both hosts ask this function, so the sentence a
198
+ * user reads in the terminal and the sentence the window shows cannot drift.
199
+ *
200
+ * Pure: no fetch, no clock, no cache. Feed it a result from `checkPublished`
201
+ * (or from the cached `updateNotice`) and it names the next action.
202
+ *
203
+ * @param {{current: string, latest: ?string, behind: boolean, channel?: 'npm'|'desktop', pkg?: string}} input
204
+ */
205
+ function updatePlan({ current, latest, behind, channel = 'npm', pkg = PKG } = {}) {
206
+ const currentText = String(current == null ? '' : current);
207
+ const latestText = latest ? String(latest) : null;
208
+ const pending = Boolean(behind) && Boolean(latestText);
209
+ if (!pending) {
210
+ return {
211
+ channel,
212
+ current: currentText,
213
+ latest: latestText,
214
+ behind: false,
215
+ action: 'none',
216
+ applier: 'none',
217
+ instruction: null,
218
+ };
219
+ }
220
+ if (channel === 'desktop') {
221
+ // The window installs its own build: there is nothing for the user to type,
222
+ // and offering `npm i -g aegis-desktop` here would install a *second* copy
223
+ // beside the running app. The applier is the app's own updater.
224
+ return {
225
+ channel,
226
+ current: currentText,
227
+ latest: latestText,
228
+ behind: true,
229
+ action: 'desktop-update',
230
+ applier: 'electron-updater',
231
+ instruction: 'Aegis Desktop → Check for Updates…',
232
+ };
233
+ }
234
+ return {
235
+ channel,
236
+ current: currentText,
237
+ latest: latestText,
238
+ behind: true,
239
+ action: 'npm-update',
240
+ applier: 'npm',
241
+ instruction: `npm i -g ${pkg}@latest`,
242
+ };
243
+ }
244
+
245
+ /**
246
+ * The same once-a-day check as `updateNotice`, but *awaited* and detailed.
247
+ *
248
+ * Why both exist: `updateNotice` answers immediately from cache and lets the
249
+ * refresh land later, which is right for a CLI that must never block a launch.
250
+ * A host that is *showing the user a banner about it* — the window, or
251
+ * `aegis doctor` — needs the full result (`.ok`, `.reason`, `.status`) and is
252
+ * willing to wait for it. So this is not a second check: it is the same probe
253
+ * (`fetchLatestDetailed`, same `TIMEOUT_MS`, same `REASONS` taxonomy) and the
254
+ * same `CHECK_INTERVAL_MS` cache rule, extracted so that the desktop applier
255
+ * stops carrying its own copy of the fetching logic (D7: the desktop keeps its
256
+ * applier and loses its version fetch).
257
+ *
258
+ * Never throws: a failure is a result with `ok: false` and a reason.
259
+ *
260
+ * @returns {Promise<{ok: boolean, latest: ?string, behind: boolean, reason: ?string,
261
+ * status: ?number, cached: boolean, checkedAt: ?number}>}
262
+ */
263
+ async function checkPublished({
264
+ current,
265
+ cache,
266
+ save,
267
+ now = Date.now(),
268
+ fetchImpl = fetchLatestDetailed,
269
+ intervalMs = CHECK_INTERVAL_MS,
270
+ timeoutMs = TIMEOUT_MS,
271
+ pkg = PKG,
272
+ } = {}) {
273
+ const c = cache || null;
274
+ const fresh = Boolean(c) && typeof c.checkedAt === 'number' && now - c.checkedAt < intervalMs;
275
+ if (fresh) {
276
+ const latest = c.latest || null;
277
+ return {
278
+ ok: Boolean(latest),
279
+ latest,
280
+ behind: !!(latest && isNewer(latest, current)),
281
+ reason: latest ? null : c.reason || null,
282
+ status: latest ? 200 : c.status == null ? null : c.status,
283
+ cached: true,
284
+ checkedAt: c.checkedAt,
285
+ };
286
+ }
287
+
288
+ let res;
289
+ try {
290
+ res = await fetchImpl({ pkg, timeoutMs });
291
+ } catch (err) {
292
+ res = { ok: false, latest: null, reason: REASONS.NETWORK, status: null, error: String((err && err.message) || err) };
293
+ }
294
+ const record = {
295
+ checkedAt: now,
296
+ latest: res && res.latest ? res.latest : null,
297
+ reason: (res && res.reason) || null,
298
+ status: res && res.status != null ? res.status : null,
299
+ };
300
+ if (typeof save === 'function') {
301
+ try {
302
+ save(record);
303
+ } catch {
304
+ /* failing to persist a notice is never worth failing the call */
305
+ }
306
+ }
307
+ return {
308
+ ok: Boolean(res && res.ok && res.latest),
309
+ latest: record.latest,
310
+ behind: !!(record.latest && isNewer(record.latest, current)),
311
+ reason: record.reason,
312
+ status: record.status,
313
+ cached: false,
314
+ checkedAt: now,
315
+ };
316
+ }
317
+
318
+ /**
319
+ * One line for the welcome box, or null when there is nothing to say.
320
+ *
321
+ * Rendered from `updatePlan`, not from a second copy of the sentence: the
322
+ * command the terminal tells the user to run and the command the window's
323
+ * banner offers are the same string produced by the same verdict.
324
+ */
190
325
  function updateLine({ current, latest, behind, pkg = PKG }) {
191
- if (!behind) return null;
192
- return `Update available: ${current} → ${latest} run: npm i -g ${pkg}@latest`;
326
+ const plan = updatePlan({ current, latest, behind, channel: 'npm', pkg });
327
+ if (plan.action !== 'npm-update') return null;
328
+ return `Update available: ${plan.current} → ${plan.latest} run: ${plan.instruction}`;
193
329
  }
194
330
 
195
331
  module.exports = {
@@ -198,6 +334,8 @@ module.exports = {
198
334
  fetchLatestDetailed,
199
335
  isTransientReason,
200
336
  updateNotice,
337
+ checkPublished,
338
+ updatePlan,
201
339
  updateLine,
202
340
  PKG,
203
341
  CHECK_INTERVAL_MS,
@@ -97,48 +97,100 @@ function writtenPath(tool) {
97
97
  const DEFAULT_MODEL = 'nexus-brain';
98
98
 
99
99
  /**
100
- * THE QUEUE RUNS ON AEGIS CLOUD, AND NOTHING ELSE.
100
+ * THE QUEUE RUNS ON WHATEVER CLASS THE TASK NAMES — aegis, byok, or local —
101
+ * the same three classes engine.js's interactive turns serve (engine.js's
102
+ * exported `CLASSES`). This module does not `require('./engine.js')` to read
103
+ * that list itself (same reason queue.js stays engine-free): duplicating the
104
+ * three names here keeps both modules testable with no Electron, no network,
105
+ * and no model.
101
106
  *
102
- * A queued task is billed to the AEGIS pool and every turn it makes goes out
103
- * with `class: 'aegis'` (see runTask below) — the pool is the only backend this
104
- * worker can reach. So a model id here has to be one the *pool* serves. A
105
- * direct-provider id is not a cheaper option the queue could fall back to; it
106
- * is a request the pool cannot honour, or worse, a per-provider spelling
107
- * (`anthropic`, `groq`, …) that quietly pins one upstream instead of letting
108
- * the pool auto-route across whichever providers hold a live key.
107
+ * This used to be Aegis Cloud only, because runTask sent every turn out with
108
+ * a hardcoded `class: 'aegis'` — a byok or local model id would have gone out
109
+ * under the wrong transport and failed at the server, or worse, silently
110
+ * picked up the wrong provider's key. Now `class` travels with the task
111
+ * (`item.class`, defaulted to 'aegis' for every task that predates this field
112
+ * — the CLI, a hand-written queue file, the old desktop card), and runTask
113
+ * forwards it verbatim instead of overwriting it.
109
114
  *
110
- * The accept-list is therefore the pooled-brain tier family — the one entry
111
- * engine.js's offerableCatalog offers for the Aegis Cloud class, plus the
112
- * `-smart`/`-neo` tier spellings the server still serves as aliases of it. This
113
- * mirrors selectBrainEntry() there rather than re-deriving "anything starting
114
- * with nexus-": `nexus-fast` is not a tier the catalog has ever served, and
115
- * accepting a made-up id means a queued task that fails at the server after
116
- * being picked up, or runs on a tier nobody chose.
115
+ * Each class validates differently, because each has a different notion of
116
+ * "no model stated is fine":
117
+ * - 'aegis' has a real default (the pooled brain), so a blank model is
118
+ * accepted and resolveModel fills it in. The accept-list is the
119
+ * pooled-brain tier family — the one entry engine.js's offerableCatalog
120
+ * offers for the Aegis Cloud class, plus the `-smart`/`-neo` tier
121
+ * spellings the server still serves as aliases of it (mirrors
122
+ * selectBrainEntry() there rather than re-deriving "anything starting
123
+ * with nexus-": `nexus-fast` is not a tier the catalog has ever served).
124
+ * - 'byok' and 'local' have no such default: a blank byok model cannot be
125
+ * "whichever provider the pool picks" (there is no pool), and a blank
126
+ * local model cannot be "whichever model is pulled" when the answer
127
+ * depends on what the user's own daemon happens to have. Both REQUIRE an
128
+ * explicit model, refused by name instead of silently resolving to
129
+ * something nobody chose.
117
130
  */
131
+ const MODEL_CLASSES = Object.freeze(['aegis', 'byok', 'local']);
132
+
118
133
  const AEGIS_MODEL_RE = /^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/;
119
134
  const AEGIS_MODEL_IDS = Object.freeze(['nexus-brain', 'aegis-brain']);
120
135
 
121
- /** True when `id` names an AEGIS Cloud pooled-brain tier (the queue's only models). */
136
+ /** True when `id` names an AEGIS Cloud pooled-brain tier. */
122
137
  function isAegisModel(id) {
123
138
  return AEGIS_MODEL_RE.test(String(id == null ? '' : id).trim());
124
139
  }
125
140
 
126
141
  /**
127
- * Why a STATED model id cannot be queued, or '' when it can. Blank is not a
128
- * refusal — "no pick" is the default model, which resolveModel supplies.
142
+ * Normalize a task's stated class to one this module (and engine.js) knows.
143
+ * Blank or absent — every task queued before this field existed — defaults to
144
+ * 'aegis', the only class the queue ever ran before today.
145
+ */
146
+ function normalizeClass(cls) {
147
+ const stated = String(cls == null ? '' : cls).trim().toLowerCase();
148
+ return stated || 'aegis';
149
+ }
150
+
151
+ /**
152
+ * Whether `id` is shaped "<provider>:<model>" — the only form engine.js's
153
+ * byok class accepts (splitByokModel). Not re-deriving the live provider list
154
+ * here (that is a catalog call, `listModels('byok')`, this module has no
155
+ * business caching) — just enough of a shape check that a malformed id is
156
+ * refused at the door instead of failing splitByokModel at the server with no
157
+ * context.
158
+ */
159
+ function looksLikeByokModel(id) {
160
+ const s = String(id == null ? '' : id).trim();
161
+ const i = s.indexOf(':');
162
+ return i > 0 && i < s.length - 1;
163
+ }
164
+
165
+ /**
166
+ * Why a STATED (model, class) pair cannot be queued, or '' when it can.
129
167
  *
130
- * The message names the pool, because the failure it prevents ("queued on
131
- * claude-sonnet-4, ran on — or was billed to — something else") is invisible
132
- * otherwise: `class: 'aegis'` would be sent with an id the server does not
133
- * serve, and the task would come back as an opaque error minutes later.
168
+ * `cls` defaults to 'aegis' when omitted, so every existing caller of
169
+ * `modelRefusal(id)` keeps its old behaviour verbatim.
134
170
  */
135
- function modelRefusal(id) {
171
+ function modelRefusal(id, cls) {
136
172
  const stated = String(id == null ? '' : id).trim();
137
- if (!stated || isAegisModel(stated)) return '';
138
- return (
139
- `the autonomous queue runs Aegis Cloud models only (${DEFAULT_MODEL}, ` +
140
- `${AEGIS_MODEL_IDS.join('/')} aliases); "${stated}" is not one`
141
- );
173
+ const normalized = normalizeClass(cls);
174
+ if (!MODEL_CLASSES.includes(normalized)) {
175
+ return `"${cls}" is not a model class the queue serves (${MODEL_CLASSES.join('/')})`;
176
+ }
177
+ if (normalized === 'aegis') {
178
+ if (!stated || isAegisModel(stated)) return '';
179
+ return (
180
+ `the autonomous queue's Aegis Cloud class runs pooled-brain models only (${DEFAULT_MODEL}, ` +
181
+ `${AEGIS_MODEL_IDS.join('/')} aliases); "${stated}" is not one`
182
+ );
183
+ }
184
+ if (normalized === 'byok') {
185
+ if (!stated) return 'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';
186
+ if (!looksLikeByokModel(stated)) {
187
+ return `"${stated}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`;
188
+ }
189
+ return '';
190
+ }
191
+ // normalized === 'local'
192
+ if (!stated) return 'a local task needs a model — the tag of whatever is pulled into the local daemon';
193
+ return '';
142
194
  }
143
195
 
144
196
  /** Phrase match for "work autonomously" in a prompt or a queued task. */
@@ -239,10 +291,14 @@ function withRoundHorizon(rounds, env, fn) {
239
291
  * task over it would break drains for a reason that is not the task's
240
292
  * fault; a fallback to the pooled brain keeps the drain honest and on-cloud.
241
293
  */
242
- function resolveModel({ model, env } = {}) {
243
- const e = env || process.env;
294
+ function resolveModel({ model, env, cls } = {}) {
244
295
  const picked = String(model || '').trim();
296
+ // byok/local have no cloud default to fall back to — modelRefusal already
297
+ // guaranteed a non-empty, shaped model at queue time, so the task's own pick
298
+ // is the only answer for either class.
299
+ if (normalizeClass(cls) !== 'aegis') return picked;
245
300
  if (picked) return picked;
301
+ const e = env || process.env;
246
302
  const fromEnv = String(e.AEGIS_AUTONOMOUS_MODEL || e.AEGIS_MODEL || '').trim();
247
303
  return isAegisModel(fromEnv) ? fromEnv : DEFAULT_MODEL;
248
304
  }
@@ -255,7 +311,8 @@ function resolveModel({ model, env } = {}) {
255
311
  * it: the queue falls back to the pool, and the one place that says so is this
256
312
  * string, which runTask emits as a note and the desktop card shows.
257
313
  */
258
- function ignoredEnvModel({ model, env } = {}) {
314
+ function ignoredEnvModel({ model, env, cls } = {}) {
315
+ if (normalizeClass(cls) !== 'aegis') return ''; // AEGIS_AUTONOMOUS_MODEL is an Aegis-only pin
259
316
  if (String(model || '').trim()) return ''; // the task's own pick is what counts
260
317
  const e = env || process.env;
261
318
  const fromEnv = String(e.AEGIS_AUTONOMOUS_MODEL || e.AEGIS_MODEL || '').trim();
@@ -462,16 +519,23 @@ function createQueueWorker({
462
519
  // pool does not serve: billed work if it happens to be a per-provider
463
520
  // spelling, an opaque server error otherwise. Failing here names the model
464
521
  // and the allowed ones, and costs nothing.
465
- const refusal = modelRefusal(item.model);
522
+ const cls = normalizeClass(item.class);
523
+ const refusal = modelRefusal(item.model, cls);
466
524
  if (refusal) {
467
- const failed = { ok: false, error: refusal, model: item.model, ms: 0 };
525
+ const failed = { ok: false, error: refusal, model: item.model, class: cls, ms: 0 };
468
526
  emit({ type: 'finish', taskId: item.id, ok: false, result: failed });
469
527
  return failed;
470
528
  }
471
- const model = resolveModel({ model: item.model, env });
472
- const ignored = ignoredEnvModel({ model: item.model, env });
529
+ const model = resolveModel({ model: item.model, env, cls });
530
+ const ignored = ignoredEnvModel({ model: item.model, env, cls });
473
531
  if (ignored) emit({ type: 'note', taskId: item.id, note: ignored });
474
- const fanoutAsked = resolveFanout(item, env);
532
+ // The pooled-brain fan-out is an Aegis Cloud mechanism (aegis1
533
+ // services/pool_brain.py) — engine.js itself only honours `autonomous`
534
+ // under `cls === 'aegis'` (engine.js:1524), so a byok/local task asking for
535
+ // it is forced to a plain single pass HERE rather than relying on that
536
+ // silent no-op, which would otherwise size the task's effort/round
537
+ // reporting as if a fan-out it never got had been granted.
538
+ const fanoutAsked = cls === 'aegis' && resolveFanout(item, env);
475
539
  // The clamp. `canFanOut()` is the entitlement answer (true everywhere
476
540
  // except a non-Pro desktop session), and it can only ever take a fan-out
477
541
  // AWAY: a task the session is not entitled to fan out runs as one plain
@@ -526,14 +590,14 @@ function createQueueWorker({
526
590
  const wantCommit = commit === undefined ? Boolean(item.commit) : Boolean(commit);
527
591
  const before = wantCommit ? safe(() => git.gitStatusSnapshot(cwd), null) : null;
528
592
 
529
- emit({ type: 'start', taskId: item.id, model, cwd, rounds, fanout, effort });
593
+ emit({ type: 'start', taskId: item.id, model, class: cls, cwd, rounds, fanout, effort });
530
594
  const started = now();
531
595
  let result;
532
596
  try {
533
597
  const res = await withRoundHorizon(rounds, env, () =>
534
598
  engine.chat(
535
599
  {
536
- class: 'aegis',
600
+ class: cls,
537
601
  model,
538
602
  prompt: taskPrompt(item, { carry, rounds }),
539
603
  // The pooled-brain fan-out ("fan out this turn" in the GUI chat
@@ -831,8 +895,11 @@ module.exports = {
831
895
  DEFAULT_MODEL,
832
896
  DEFAULT_ROUNDS,
833
897
  MAX_ROUND_STOPS,
898
+ MODEL_CLASSES,
834
899
  AEGIS_MODEL_IDS,
835
900
  isAegisModel,
901
+ normalizeClass,
902
+ looksLikeByokModel,
836
903
  modelRefusal,
837
904
  WRITE_TOOLS,
838
905
  writtenPath,