aegiscode 7.0.9 → 7.0.11

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/src/commands.js CHANGED
@@ -3004,7 +3004,11 @@ const COMMANDS = [
3004
3004
  [span(C.gray, '─'.repeat(34))],
3005
3005
  [
3006
3006
  span(set ? C.green : C.gray, ` ${set} of ${providers.length} providers set`),
3007
- span(C.gray, ' — /byok-key <provider>'),
3007
+ // Name the PICKER first: the id is the one thing this screen was
3008
+ // asking the reader to copy by eye, and `/byok-list` removes that
3009
+ // step. The typed form stays beside it for scripts and for anyone who
3010
+ // already knows the id.
3011
+ span(C.gray, ' — /byok-list picks one, or /byok-key <provider>'),
3008
3012
  ],
3009
3013
  '',
3010
3014
  ...byokProviderLines(providers),
@@ -3057,6 +3061,7 @@ const COMMANDS = [
3057
3061
  return {
3058
3062
  note: `${p.id} already has a key${p.masked ? ` (${p.masked})` : ''} — pasting a new one replaces it.`,
3059
3063
  prompt: `new ${p.label || p.id} key: `,
3064
+ provider: p.id,
3060
3065
  };
3061
3066
  }
3062
3067
  const bits = [`${p.label || p.id}`];
@@ -3066,7 +3071,7 @@ const COMMANDS = [
3066
3071
  if (models.length) bits.push(`unlocks ${models.join(', ')}`);
3067
3072
  if (p.key_prefix) bits.push(`key starts with ${p.key_prefix}`);
3068
3073
  if (p.key_url) bits.push(`create one at ${p.key_url}`);
3069
- return { note: bits.join(' · '), prompt: `${p.id} key: ` };
3074
+ return { note: bits.join(' · '), prompt: `${p.id} key: `, provider: p.id };
3070
3075
  },
3071
3076
  },
3072
3077
  {
@@ -3076,43 +3081,60 @@ const COMMANDS = [
3076
3081
  build: (arg) => ({ provider: String(arg || '').trim() }),
3077
3082
  },
3078
3083
  {
3079
- name: 'class', args: ['class'], hint: '[aegis|byok]', category: 'model',
3080
- desc: 'Show or switch which class turns run on: pooled AEGIS Cloud, or your own key',
3084
+ name: 'class', args: ['class', 'mode'], hint: '[aegis|byok|local|pro [on|off]]', category: 'model',
3085
+ desc: 'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',
3081
3086
  handler: async (c, a) => {
3082
3087
  const args = a || {};
3083
3088
  const cur = (c.ctx && c.ctx.modelClass) || 'aegis';
3084
3089
  const label = (id) => (c.classLabel ? c.classLabel(id) : id);
3085
3090
  const want = String(args.class || '').trim().toLowerCase();
3091
+ // `/class pro on|off` — the one-time opt-in for the subscription class.
3092
+ //
3093
+ // `pro` spends a real Claude Code Pro/Max subscription by spawning the
3094
+ // `claude` CLI, and an account whose organization has disabled Claude
3095
+ // Code answers every such turn with `oauth_org_not_allowed`, which this
3096
+ // repo cannot fix. So `pro` ships DISABLED (config.js `proEnabled: false`)
3097
+ // and this is the only way in: an explicit, deliberate word from the
3098
+ // user. Written through saveConfig so it survives a restart — an opt-in
3099
+ // that reverted on the next launch would put the class back out of reach
3100
+ // with no way to tell why.
3101
+ if (want === 'pro' && args.mode) {
3102
+ const mode = String(args.mode).trim().toLowerCase();
3103
+ if (mode !== 'on' && mode !== 'off') {
3104
+ c.push({ role: 'error', text: `usage: /class pro [on|off] — got "${args.mode}"` });
3105
+ return true;
3106
+ }
3107
+ const on = mode === 'on';
3108
+ c.saveConfig({ proEnabled: on });
3109
+ c.push({
3110
+ role: on ? 'done' : 'note',
3111
+ text: on
3112
+ ? 'pro class enabled — /class pro switches to your Claude Code subscription. ' +
3113
+ 'It runs only if that subscription has Claude Code access.'
3114
+ : 'pro class disabled — it is no longer offered by /class or the model picker.',
3115
+ });
3116
+ // Turning it off while sitting on it would leave the session pointing
3117
+ // at a class that can no longer run: fall back to the default class
3118
+ // through the same path `/class aegis` takes, so the pin rules and the
3119
+ // stored config are updated rather than only the panel.
3120
+ if (!on && cur === 'pro') {
3121
+ const back = c.switchClass('aegis');
3122
+ if (back.ok) c.push({ role: 'note', text: `class: ${back.class} — ${label(back.class)}` });
3123
+ }
3124
+ return true;
3125
+ }
3086
3126
  if (!want) {
3087
3127
  // Awaited: the engine's listClasses() is async (it probes for a local
3088
3128
  // Ollama before answering), and a context that offers no class surface
3089
3129
  // at all falls back to the two static rows below.
3090
3130
  const classes = await Promise.resolve(c.classes ? c.classes() : []).catch(() => []);
3091
3131
  const rows = classes.length ? classes : [{ class: 'aegis' }, { class: 'byok' }];
3092
- const lines = [
3093
- [span(C.gold + BOLD, 'Class'), span(BOLD_OFF, ' — which route the next turn takes')],
3094
- [span(C.gray, '─'.repeat(52))],
3095
- ];
3096
- for (const k of rows) {
3097
- const id = k.class;
3098
- const on = id === cur;
3099
- // The distinction that matters to a user: who pays, and with which
3100
- // credential. Stated per class rather than in a footnote.
3101
- const note =
3102
- id === 'byok'
3103
- ? k.configured
3104
- ? 'your key, relayed by AEGIS — billed a handling fee'
3105
- : 'needs a provider key: /byok-key <provider>'
3106
- : 'the pool — your AEGIS account key pays for it';
3107
- lines.push([
3108
- span(on ? C.green : C.gray, ` ${on ? '●' : '○'} ${String(id).padEnd(6)}`),
3109
- span(on ? C.green : C.gray, label(id)),
3110
- span(C.gray, ` ${note}`),
3111
- ]);
3112
- }
3113
- lines.push('', [span(C.gray, ' switch with /class byok or /class aegis')]);
3114
- panel(c, lines);
3115
- c.render();
3132
+ const sel = rows.findIndex((k) => k.class === cur);
3133
+ // An interactive picker, not a static panel — the same tab/arrow/enter
3134
+ // overlay machinery /model already uses (chatflow.js handleOverlayKey),
3135
+ // so a class is switched by moving the highlight and hitting enter
3136
+ // rather than retyping its name after reading it off this list.
3137
+ c.openOverlay({ type: 'class', items: rows, sel: sel < 0 ? 0 : sel, current: cur });
3116
3138
  return true;
3117
3139
  }
3118
3140
  const res = c.switchClass(want);
@@ -3163,45 +3185,72 @@ const COMMANDS = [
3163
3185
  },
3164
3186
  {
3165
3187
  name: 'models', aliases: ['model-list'], hint: '', category: 'model',
3166
- desc: 'List the model ids you can pin with /model, for the class you are on',
3188
+ desc: 'Pick a model to pin, for the class you are on — opens the same picker as /model',
3167
3189
  handler: async (c) => {
3168
3190
  const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
3169
3191
  const models = (await c.listModelsFor(cls)) || [];
3170
- const lines = [
3171
- [span(C.gold + BOLD, 'Models'), span(BOLD_OFF, ` — ${c.classLabel ? c.classLabel(cls) : cls}`)],
3172
- [span(C.gray, '─'.repeat(52))],
3173
- ];
3174
3192
  if (!models.length) {
3175
- lines.push('', [
3176
- span(
3177
- C.gray,
3178
- cls === 'byok'
3179
- ? ' nothing to relay yet — save a provider key with /byok-key <provider>'
3180
- : ' no models advertised — check the account with /status, then retry'
3181
- ),
3182
- ]);
3183
- } else {
3184
- const pinned = c.ctx && c.ctx.model;
3185
- for (const m of models) {
3186
- const on = pinned === m.id;
3187
- // A row from the OTHER class rides on this list on purpose — the
3188
- // pooled Nexus row is what makes the byok list able to show a way
3189
- // back to the pooled lane (app.js classScopedModels). It is not
3190
- // pinnable here, so it says which class it runs on instead of
3191
- // looking like a byok id that would 400 at the relay.
3192
- const other = m.cls && m.cls !== cls;
3193
- lines.push([
3194
- span(on ? C.green : C.gray, ` ${on ? '●' : '○'} `),
3195
- span(on ? C.green : C.gray, String(m.id).padEnd(30)),
3196
- span(C.gray, other
3197
- ? `${m.note || m.label || ''} · pooled lane — /class ${m.cls}`
3198
- : m.note || m.label || ''),
3199
- ]);
3200
- }
3201
- lines.push('', [span(C.gray, ' pin one with /model <id> — /model alone opens the picker')]);
3193
+ note(c, cls === 'byok'
3194
+ ? 'nothing to relay yet — save a provider key with /byok-key <provider>'
3195
+ : 'no models advertised — check the account with /status, then retry');
3196
+ c.render();
3197
+ return true;
3202
3198
  }
3203
- panel(c, lines);
3204
- c.render();
3199
+ const pinned = c.ctx && c.ctx.model;
3200
+ // A row from the OTHER class rides on this list on purpose — the pooled
3201
+ // Nexus row is what makes the byok list able to show a way back to the
3202
+ // pooled lane (app.js classScopedModels). It is not a row of THIS
3203
+ // class's own ids, so its note says which class it actually runs on
3204
+ // instead of looking like a byok id that would 400 at the relay.
3205
+ const items = models.map((m) => (m.cls && m.cls !== cls
3206
+ ? { ...m, note: `${m.note || m.label || ''} · pooled lane — /class ${m.cls}` }
3207
+ : m));
3208
+ const sel = items.findIndex((m) => m.id === pinned);
3209
+ // Same overlay /model opens (tab/arrow to move, enter to pin — see
3210
+ // chatflow.js handleOverlayKey), just scoped to this class's own rows
3211
+ // rather than /model's merged cross-class catalog. Picking the other
3212
+ // class's row switches class first, the same cross-class pin
3213
+ // applyModelRow already does for /model's own rows.
3214
+ c.openOverlay({ type: 'model', items, sel: sel < 0 ? 0 : sel, current: pinned, cls });
3215
+ return true;
3216
+ },
3217
+ },
3218
+ {
3219
+ // `/byok-list` — pick a provider from the catalog and store its key on THIS
3220
+ // machine, the same route `/byok-key` takes once a provider is named. The
3221
+ // picker is the point: the provider id was the one thing this flow asked
3222
+ // the user to recall and retype, and a retyped or alias-matched id either
3223
+ // matched nothing or matched another vendor. Arrow or Tab moves the
3224
+ // highlight, Enter picks, and the id dispatched is the catalog's own — so
3225
+ // the key lands under the id the relay will be asked for, and that
3226
+ // provider's models then show up in `/model`.
3227
+ name: 'byok-list', aliases: ['byok-pick'], hint: '', category: 'auth',
3228
+ desc: 'Pick a provider to set a key for, then its models appear in /model',
3229
+ handler: async (c) => {
3230
+ const providers = await byokCatalog(c.client);
3231
+ if (!providers || !providers.length) {
3232
+ c.push({
3233
+ role: 'error',
3234
+ text: 'Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known.',
3235
+ });
3236
+ return true;
3237
+ }
3238
+ if (typeof c.openOverlay !== 'function') {
3239
+ // No interactive host: fall back to the printable list rather than a
3240
+ // picker nothing can draw.
3241
+ c.push({ role: 'note', text: '/byok-key <provider> — /byok lists the providers.' });
3242
+ return true;
3243
+ }
3244
+ const cur = (providers.find((p) => p.configured) || {}).id || null;
3245
+ const sel = Math.max(0, providers.findIndex((p) => p.configured));
3246
+ c.openOverlay({
3247
+ type: 'provider',
3248
+ command: 'byok-key',
3249
+ items: providers,
3250
+ sel,
3251
+ current: cur,
3252
+ hint: '↑↓ or tab move · enter picks · the key is stored on this machine',
3253
+ });
3205
3254
  return true;
3206
3255
  },
3207
3256
  },
@@ -3212,7 +3261,33 @@ const COMMANDS = [
3212
3261
  const args = a || {};
3213
3262
  const typed = String(args.provider || '').trim().toLowerCase();
3214
3263
  if (!typed) {
3215
- c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
3264
+ // No provider typed: open the picker instead of printing a usage line.
3265
+ // The id was the one thing this flow asked the user to RECALL, and a
3266
+ // mistyped or alias-matched id either matched nothing or — worse —
3267
+ // matched another vendor's row. Arrow or Tab moves, Enter picks, and
3268
+ // the id Enter dispatches is the catalog's own, so the key lands under
3269
+ // the id the relay will actually be asked for.
3270
+ const providers = await byokCatalog(c.client);
3271
+ if (!providers || !providers.length) {
3272
+ c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
3273
+ return true;
3274
+ }
3275
+ if (typeof c.openOverlay !== 'function') {
3276
+ // No interactive host (a piped run): the old usage line, which at
3277
+ // least names the command that lists the ids.
3278
+ c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
3279
+ return true;
3280
+ }
3281
+ const cur = (providers.find((p) => p.configured) || {}).id || null;
3282
+ const sel = Math.max(0, providers.findIndex((p) => p.configured));
3283
+ c.openOverlay({
3284
+ type: 'provider',
3285
+ command: 'byok-key',
3286
+ items: providers,
3287
+ sel,
3288
+ current: cur,
3289
+ hint: '↑↓ or tab move · enter picks · the key is stored on this machine',
3290
+ });
3216
3291
  return true;
3217
3292
  }
3218
3293
  const store = c.settings && c.settings();
@@ -3229,6 +3304,24 @@ const COMMANDS = [
3229
3304
  c.push({ role: 'error', text: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id.` });
3230
3305
  return true;
3231
3306
  }
3307
+ // A key written under a provider the relay does not serve is unusable and
3308
+ // invisible: the catalog never lists the row it created, so the user sees
3309
+ // "saved" and then no models, with nothing naming the typo. `byok-set`
3310
+ // already refuses this; the command it redirects users TO must refuse it
3311
+ // too, or the redirect trades one silent failure for another.
3312
+ //
3313
+ // Only refused when the catalog actually answered. `byokCatalog` returns
3314
+ // null on an unreachable server, and refusing on null would turn a
3315
+ // network blip into "unknown provider" — a wrong reason for a right-looking
3316
+ // stop. With no catalog the typed id is trusted, as before.
3317
+ if (providers && !match?.provider) {
3318
+ const ids = providers.map((x) => x.id).join(', ');
3319
+ c.push({
3320
+ role: 'error',
3321
+ text: `unknown provider "${typed}". Known ids: ${ids} — nothing was saved.`,
3322
+ });
3323
+ return true;
3324
+ }
3232
3325
  const p = match && match.provider;
3233
3326
  const id = (p && p.id) || typed;
3234
3327
  // A second token is the scriptable path (`/byok-key openai sk-…`); with
@@ -3248,9 +3341,75 @@ const COMMANDS = [
3248
3341
  c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
3249
3342
  }
3250
3343
  store.set(c.byokNamespace(id), { key });
3344
+
3345
+ // MIRROR IT INTO ~/.aegiscode/.env — the file every host (this CLI, the
3346
+ // desktop, the MCP plugin) loads at start-up, and the one the shared
3347
+ // engine's `providerKeyFromEnv` reads. The settings store alone made the
3348
+ // key a private fact of this process's data dir: the next launch of the
3349
+ // SAME host found it, but nothing else did, and the byok model list is
3350
+ // built from a key the engine resolves through both. `/model-add` writes
3351
+ // both stores for this exact reason (see its `setEnvValue` call), and a
3352
+ // key entered here must not be the one row that behaves differently.
3353
+ // Best-effort: the store row above is the row of record, so a failure to
3354
+ // write the file is reported and never undoes the save.
3355
+ let envWritten = '';
3356
+ try {
3357
+ const { envVarFor, setEnvValue } = require(resolveShared(path.join('client', 'env-file.js')));
3358
+ const name = envVarFor(id);
3359
+ if (name) {
3360
+ const res = setEnvValue(name, key);
3361
+ if (res.ok) envWritten = name;
3362
+ else c.push({ role: 'note', text: `heads up: could not write ${name} to ~/.aegiscode/.env (${res.error}).` });
3363
+ }
3364
+ } catch {
3365
+ /* the settings-store save is the row of record; this mirror is best-effort */
3366
+ }
3367
+
3368
+ // Then make the models it unlocks VISIBLE where the user asked for them:
3369
+ // the byok model list is cached for five minutes (app.js MODEL_CACHE_MS),
3370
+ // so without this the key is saved and `/model` keeps offering the list
3371
+ // computed before it existed — the "I set a key and nothing new appeared"
3372
+ // report. The refresh is forced, and its rows are what get pinned below.
3373
+ let rows = [];
3374
+ if (typeof c.refreshByokModels === 'function') {
3375
+ try { rows = (await c.refreshByokModels()) || []; } catch { rows = []; }
3376
+ }
3377
+ if (!rows.length && typeof c.listModelsFor === 'function') {
3378
+ // Hosts that expose the class surface but not the cache invalidation
3379
+ // (an embedding) still get an answer: ask for the byok class directly.
3380
+ try {
3381
+ rows = ((await c.listModelsFor('byok')) || []).filter((m) => !m.cls || m.cls === 'byok');
3382
+ } catch { rows = []; }
3383
+ }
3384
+ const mine = rows.filter((m) => m && (m.provider === id || String(m.id || '').startsWith(`${id}:`)));
3385
+
3386
+ // Move onto the byok class — the key just saved can only be spent there,
3387
+ // and a session sitting on `aegis` would show these rows in /model and
3388
+ // then send the pinned `provider:model` id to the pool. Before the pin,
3389
+ // so switchClass's own pin rules run on the id we are about to store.
3390
+ let onByok = ((c.ctx && c.ctx.modelClass) || '') === 'byok';
3391
+ if (!onByok && typeof c.switchClass === 'function') {
3392
+ const sw = c.switchClass('byok');
3393
+ if (sw && sw.ok) {
3394
+ onByok = true;
3395
+ c.push({ role: 'note', text: `class: byok — ${c.classLabel ? c.classLabel('byok') : 'your own key'}` });
3396
+ }
3397
+ }
3398
+
3399
+ // Pin it and PERSIST it, which is what makes the pick survive a restart:
3400
+ // app.js's restorePrefs() reads config.model/modelClass back. Only on
3401
+ // success — this whole block is the success path, after the key landed.
3402
+ const pickId = mine.length ? String(mine[0].id) : '';
3403
+ if (pickId && c.ctx) {
3404
+ c.ctx.model = pickId;
3405
+ c.saveConfig({ model: pickId, currentModelId: pickId, ...(onByok ? { modelClass: 'byok' } : {}) });
3406
+ }
3407
+
3251
3408
  c.push({
3252
3409
  role: 'done',
3253
- text: `saved a ${id} key on this machine — /models lists its models, /class byok runs on it.`,
3410
+ text: pickId
3411
+ ? `saved a ${id} key on this machine${envWritten ? ` (${envWritten} in ~/.aegiscode/.env, so it is there next time)` : ''} — model ${pickId} pinned, /model lists the rest.`
3412
+ : `saved a ${id} key on this machine${envWritten ? ` (${envWritten} in ~/.aegiscode/.env, so it is there next time)` : ''} — /models lists its models, /class byok runs on it.`,
3254
3413
  });
3255
3414
  return true;
3256
3415
  },
package/src/config.js CHANGED
@@ -89,6 +89,20 @@ const DEFAULT_CONFIG = {
89
89
  // back to. Defaulted to the pooled class, which is the only one an account
90
90
  // key alone can run.
91
91
  modelClass: 'aegis',
92
+ // Whether the `pro` class may be selected at all. OFF by default, and it
93
+ // takes a deliberate `/class pro on` to turn it on — this is a one-time
94
+ // opt-in, not a preference that drifts back.
95
+ //
96
+ // The reason is the failure this flag exists to prevent: `pro` spends a real
97
+ // Claude Code Pro/Max subscription by spawning the `claude` CLI, and an
98
+ // account whose organization has disabled Claude Code access answers every
99
+ // such turn with `oauth_org_not_allowed` ("Your organization has disabled
100
+ // Claude subscription access"). Nothing in this repo can re-enable that, so
101
+ // a default of "offered" meant the Class picker, the `/model` list and the
102
+ // anthropic→pro override all steered users into turns that could only fail.
103
+ // Off by default means a machine that never asked for the subscription route
104
+ // never lands on it; `/class pro on` is the single, explicit way in.
105
+ proEnabled: false,
92
106
  // The full model table (seeded from src/models.js MODELS on first
93
107
  // read by pickerModels()). 'currentModelId' mirrors `model` under the
94
108
  // aegiscode- name so /model add/remove/switch stay compatible both ways.
package/src/deps.js CHANGED
@@ -93,7 +93,103 @@ const { buildSystemPrompt } = require(promptPath);
93
93
  const claudePro = require(claudeProPath);
94
94
  const updater = require(updatePath);
95
95
  const queue = require(queuePath);
96
- const autonomous = require(autonomousPath);
96
+ const autonomousModule = require(autonomousPath);
97
+
98
+ /**
99
+ * The shared worker factory, wrapped so a drain closes the model it warmed.
100
+ *
101
+ * ## Why the wrapper lives here and not at the call site
102
+ *
103
+ * The desktop's rule is "closing this host closes the model" (`main.js`
104
+ * before-quit -> `engine.unloadLocalModels` -> `local.js unloadAll`). The chat
105
+ * surfaces on this host have it since `app.js` `releaseLocalModel`, but the
106
+ * unattended drain did not: `aegiscode autonomous proceed` builds the same
107
+ * engine, runs N turns on the local lane and then exits, leaving whatever it
108
+ * warmed resident for the rest of the pin the FIRST turn paid for
109
+ * (`DEFAULT_WARM_SECS` = 1800 in local.js, i.e. up to thirty minutes). A queue
110
+ * drained from a systemd timer is the worst case, not an edge case: nothing is
111
+ * watching the tray, and the timer re-arms every few minutes, so the weights can
112
+ * be kept hot indefinitely by a process that exited long ago. The local class
113
+ * bills nobody because the compute is already bought — a loaded model with no
114
+ * user is the one cost it was meant never to have.
115
+ *
116
+ * The fix belongs here because `createQueueWorker` does not hand its engine
117
+ * back: it returns `{ runTask, runOne, proceed, reconcile, cancel,
118
+ * sessionIdFor, resolveModel }` and nothing else, so the caller holds no handle
119
+ * to unload. This module is the seam that SUPPLIES that engine (it is built
120
+ * from `cli/src/engine.js`, which now carries `unloadLocalModels`), and it is
121
+ * the one place on the drain path that is not a sealed unit — `bin/aegiscode.js`
122
+ * is provenance p1 and `src/autonomous.js` is p6, both of which a real fix
123
+ * there would require resealing deliberately, with a version bump.
124
+ *
125
+ * ## What is wrapped, and why exactly those
126
+ *
127
+ * Only the two calls that are a whole DRAIN: `proceed` (which `run` and `retry`
128
+ * reach, since `src/autonomous.js` routes `run` to `proceed({ max: 1 })`) and
129
+ * `reconcile` (which queues a plan and then drains it in the same call —
130
+ * `await proceed(...)` inside the shared worker — so it warms a model exactly
131
+ * like `proceed` does).
132
+ *
133
+ * `runOne` is deliberately NOT wrapped, even though it also runs a turn. A
134
+ * drain calls it once per task, so a release there would evict the model
135
+ * between tasks of the SAME drain and make every task after the first pay the
136
+ * cold prefill the pin exists to avoid. The release belongs at the boundary of
137
+ * the drain, not at each turn inside it.
138
+ *
139
+ * Both wrappers release in a `finally`, so a WARMED-BUT-FAILED drain still
140
+ * closes its model — the case most likely to leave weights behind, since the
141
+ * successful path at least had a user watching it.
142
+ *
143
+ * A fire-and-forget `process.on('exit')` would NOT work here and is not used:
144
+ * that callback cannot await, and the bin hard-exits (`process.exit(code)` in
145
+ * `bin/aegiscode.js`), which skips `beforeExit` entirely — a handler registered
146
+ * for it would never run for the drain. Awaiting in a `finally` before the exit
147
+ * code is returned is the only ordering that actually issues the request.
148
+ *
149
+ * Best-effort by construction: a release that throws must never turn a drain
150
+ * that did its work into a failed one, and a worker built against a much older
151
+ * engine simply has nothing to release.
152
+ */
153
+ function withModelRelease(worker, engine) {
154
+ const release = async () => {
155
+ try {
156
+ if (engine && typeof engine.unloadLocalModels === 'function') {
157
+ await engine.unloadLocalModels();
158
+ }
159
+ } catch {
160
+ // A teardown that crashes is worse than a residency window that lapses on
161
+ // its own (see cli/src/engine.js's `unloadLocalModels` note).
162
+ }
163
+ };
164
+
165
+ const wrapDrain = (name) => {
166
+ const original = worker[name];
167
+ if (typeof original !== 'function') return original;
168
+ return async (...args) => {
169
+ try {
170
+ return await original.apply(worker, args);
171
+ } finally {
172
+ await release();
173
+ }
174
+ };
175
+ };
176
+
177
+ return {
178
+ ...worker,
179
+ proceed: wrapDrain('proceed'),
180
+ reconcile: wrapDrain('reconcile'),
181
+ };
182
+ }
183
+
184
+ const autonomous = {
185
+ ...autonomousModule,
186
+ createQueueWorker: (opts = {}) =>
187
+ autonomousModule.createQueueWorker
188
+ ? withModelRelease(autonomousModule.createQueueWorker(opts), opts && opts.engine)
189
+ // A staged/vendored shared module older than the worker factory itself:
190
+ // degrade to whatever it exports rather than throwing on the drain path.
191
+ : autonomousModule.createQueueWorker,
192
+ };
97
193
  const { autoProvisionApiKey, provisionFailureText, trialOutcomeNote } = require(autoProvisionPath);
98
194
 
99
195
  // The trial clause is shared so the CLI's two notice sites and the desktop
package/src/engine.js CHANGED
@@ -60,6 +60,29 @@ const VERSION = require('../package.json').version;
60
60
  */
61
61
  const HOST_CLASSES = Object.freeze(['aegis', 'byok', 'local', 'pro']);
62
62
 
63
+ /**
64
+ * The classes this host will actually OFFER, given the `proEnabled` gate.
65
+ *
66
+ * `pro` is in HOST_CLASSES because this host can run it; it is NOT offered
67
+ * unless the user opted in with `/class pro on` (config.js `proEnabled`,
68
+ * default false). Every surface that lists, validates or auto-selects a class
69
+ * goes through this list, so the gate cannot be honoured by `/class` while the
70
+ * `/model` picker and the anthropic→pro override still route turns onto a
71
+ * subscription the user never enabled.
72
+ *
73
+ * @param {boolean|{proEnabled?: boolean}} [want] `true`, or a config object.
74
+ * @returns {ReadonlyArray<string>}
75
+ */
76
+ function offeredClasses(want) {
77
+ const on = want === true || (want && want.proEnabled === true);
78
+ return on ? HOST_CLASSES : HOST_CLASSES.filter((c) => c !== 'pro');
79
+ }
80
+
81
+ /** Whether the `pro` class may be selected on this host. */
82
+ function proEnabled(cfg) {
83
+ return cfg === true || (!!cfg && cfg.proEnabled === true);
84
+ }
85
+
63
86
  /** The class a turn runs on when nothing else is said. */
64
87
  const DEFAULT_CLASS = 'aegis';
65
88
 
@@ -79,15 +102,19 @@ const CLASS_LABELS = Object.freeze({
79
102
  * @param {() => string} getClass Which class the next turn runs on — read per
80
103
  * call for the same reason getConfirmMode is: /class must take effect on the
81
104
  * very next turn, not on the next launch.
105
+ * @param {() => boolean} [getProEnabled] Whether the `pro` class is enabled for
106
+ * this install (config.js `proEnabled`, `/class pro on`). Read per call, like
107
+ * getClass, so turning it off takes effect on the very next turn rather than
108
+ * on the next launch — a stale `pro` session state must not survive it.
82
109
  * @param {object} [settings] The provider-config store. Injected by tests
83
110
  * (and by app.js, so one store serves both the engine and the commands);
84
111
  * otherwise created against the CLI's data dir.
85
112
  * @returns {{chat: Function, cancel: Function, respondApproval: Function,
86
113
  * respondRoundsAsk: Function, clearSessionApprovals: Function, listClasses: Function,
87
114
  * listModels: Function, classLabel: Function, getClass: Function, setClass: Function,
88
- * settings: object}}
115
+ * unloadLocalModels: () => Promise<void>, settings: object}}
89
116
  */
90
- function createEngine({ client, getConfirmMode, getClass, settings: injectedSettings } = {}) {
117
+ function createEngine({ client, getConfirmMode, getClass, getProEnabled, settings: injectedSettings } = {}) {
91
118
  const settings = injectedSettings || createSettingsStore({ dir: credentials.aegisHome() });
92
119
 
93
120
  const local = createLocalEngine({
@@ -109,17 +136,55 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
109
136
  getConfirmMode,
110
137
  });
111
138
 
112
- /** The live class, clamped to what this host can run. */
139
+ /** The classes this host offers right now — `pro` only once enabled. */
140
+ function liveClasses() {
141
+ const on = typeof getProEnabled === 'function' ? !!getProEnabled() : false;
142
+ return offeredClasses(on);
143
+ }
144
+
145
+ /** The live class, clamped to what this host can run AND offers. */
113
146
  function currentClass() {
114
147
  const asked = typeof getClass === 'function' ? getClass() : null;
115
- return HOST_CLASSES.includes(asked) ? asked : DEFAULT_CLASS;
148
+ const allowed = liveClasses();
149
+ return allowed.includes(asked) ? asked : DEFAULT_CLASS;
116
150
  }
117
151
 
118
152
  function chat(payload, onDelta) {
119
- const cls = currentClass();
120
153
  // `class` is stamped here rather than sent by every caller, so the class a
121
154
  // turn runs on has exactly one source of truth (the live session state) and
122
155
  // a caller cannot accidentally pin a stale one.
156
+ //
157
+ // …WHEN THERE IS A LIVE SESSION TO STAMP FROM. `getClass` is the
158
+ // interactive surface's `/class` state; a payload that NAMES a class is
159
+ // stating its own, and the only such caller is the autonomous queue, whose
160
+ // tasks each carry the class they were queued on (autonomous.js runTask).
161
+ // The drain builds this engine through buildEngine() below, which supplies
162
+ // no `getClass` at all — deliberately, because a drain has no interactive
163
+ // session to read.
164
+ //
165
+ // Reading `currentClass()` unconditionally was therefore not a clamp but an
166
+ // OVERWRITE: every queued task went out as `class: 'aegis'` regardless of
167
+ // what it was queued as, so a byok or local task (feature from 9eeef09) was
168
+ // billed to the pooled route it did not ask for, on a model id the pool
169
+ // does not serve. Verified against this tree: a payload `{class:'pro'}` was
170
+ // observed arriving at the shared engine as `{class:'aegis'}`.
171
+ //
172
+ // Precedence is unchanged for the interactive path, which always supplies
173
+ // `getClass`: a live class wins over anything a payload carries, so a stale
174
+ // value still cannot pin a turn. Only an ABSENT live class lets the
175
+ // payload's own class through, and then only one this host can run.
176
+ const live = typeof getClass === 'function' ? getClass() : null;
177
+ const stated = payload && payload.class;
178
+ // The offered set, not HOST_CLASSES: a `pro` turn must not run through the
179
+ // subscription unless it was explicitly enabled, and that holds for a
180
+ // payload that names its own class too (the queue stamps the class a task
181
+ // was queued on, which may predate the gate).
182
+ const allowed = liveClasses();
183
+ const cls = allowed.includes(live)
184
+ ? live
185
+ : allowed.includes(stated)
186
+ ? stated
187
+ : DEFAULT_CLASS;
123
188
  return local.chat({ ...payload, class: cls }, onDelta);
124
189
  }
125
190
 
@@ -129,15 +194,43 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
129
194
  respondApproval: local.respondApproval,
130
195
  respondRoundsAsk: local.respondRoundsAsk,
131
196
  clearSessionApprovals: local.clearSessionApprovals,
197
+ // "Closing this host closes the model", the rule the desktop has enforced
198
+ // on its quit path (`main.js` before-quit -> engine.unloadLocalModels ->
199
+ // local.js unloadAll) since the lane shipped — and the one the CLI was
200
+ // missing entirely. Without this passthrough a local turn left the weights
201
+ // resident on the user's own hardware for the full length of the pin
202
+ // (local.js DEFAULT_WARM_SECS = 1800, i.e. 30 minutes) after the process
203
+ // was gone: the local lane exists to bill nothing because the compute is
204
+ // already paid for, and a model nobody is using anymore is the one cost it
205
+ // was supposed never to have.
206
+ //
207
+ // Wrapped rather than forwarded bare because this host is also built
208
+ // against a VENDORED copy of the shared engine (cli/scripts/predist.mjs
209
+ // stages desktop/lib/local/* into cli/vendor), so an install staged from a
210
+ // tree that predates `unloadLocalModels` must degrade to a no-op instead of
211
+ // throwing on the exit path — a teardown that crashes is worse than a
212
+ // residency window that lapses on its own.
213
+ unloadLocalModels: () =>
214
+ typeof local.unloadLocalModels === 'function'
215
+ ? local.unloadLocalModels()
216
+ : Promise.resolve(),
132
217
  // The engine's own class table, narrowed to the ones this host runs — so a
133
218
  // UI built from listClasses() can never offer a class that would throw.
134
219
  // Async, like the local engine's: listClasses() probes Ollama (a live
135
220
  // HTTP round-trip) before it can answer, so returning the raw promise made
136
221
  // `/class` throw "filter is not a function". The caller awaits it.
137
- listClasses: async () => (await local.listClasses()).filter((c) => HOST_CLASSES.includes(c.class)),
222
+ // The offered set, not HOST_CLASSES: `/class`, `/models` and the pickers are
223
+ // built from this, so a disabled `pro` cannot be listed or entered.
224
+ listClasses: async () => {
225
+ const allowed = liveClasses();
226
+ return (await local.listClasses()).filter((c) => allowed.includes(c.class));
227
+ },
138
228
  listModels: (cls) => local.listModels(cls || currentClass()),
139
229
  classLabel: (cls) => CLASS_LABELS[cls] || CLASS_LABELS[DEFAULT_CLASS],
140
230
  getClass: currentClass,
231
+ /** The classes selectable right now (see offeredClasses) — for surfaces
232
+ * that validate a class without instantiating a turn. */
233
+ offeredClasses: () => liveClasses(),
141
234
  settings,
142
235
  };
143
236
  }
@@ -180,4 +273,13 @@ function effortRung(effort) {
180
273
  return effort === 'low' || effort === 'medium' ? effort : 'high';
181
274
  }
182
275
 
183
- module.exports = { createEngine, HOST_CLASSES, DEFAULT_CLASS, CLASS_LABELS, byokNamespace, effortRung };
276
+ module.exports = {
277
+ createEngine,
278
+ HOST_CLASSES,
279
+ DEFAULT_CLASS,
280
+ CLASS_LABELS,
281
+ offeredClasses,
282
+ proEnabled,
283
+ byokNamespace,
284
+ effortRung,
285
+ };