aegiscode 7.0.10 → 7.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/connect.js ADDED
@@ -0,0 +1,351 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * `aegiscode connect` — this machine, signed in, in one step.
10
+ *
11
+ * ## Why this exists next to `login`
12
+ *
13
+ * `login` saves a key the user already has. That is the right command for
14
+ * someone who has been to the dashboard, and the wrong one for a fresh
15
+ * install: at that point there is no key to paste, so the first thing the user
16
+ * meets is a prompt for something they cannot produce yet, and every cloud
17
+ * feature (memory sync, conversation sync, the record vault) answers "no key"
18
+ * until they work out where one comes from.
19
+ *
20
+ * `connect` is the other door. **By default it signs in with Google**
21
+ * (`client/google-signin.js`, driving aegis1's existing `/auth/google`
22
+ * desktop round-trip): a browser opens, and the key this machine saves is
23
+ * tied to that real identity rather than to the machine itself — the same
24
+ * account comes back on a second machine signed in with the same Google
25
+ * account, which an anonymous per-machine key can never do.
26
+ *
27
+ * `--anonymous` (or `--device`) keeps the original door for anyone who wants
28
+ * no Google identity involved at all: `POST /api/v1/auth/register-device`
29
+ * (client/aegis.js's `registerDevice`, driven by client/auto-provision.js's
30
+ * `autoProvisionApiKey`). That call is idempotent per machine fingerprint, so:
31
+ *
32
+ * - on a NEW machine it mints the account (and aegis1's one-time welcome
33
+ * trial), saves the key, and the vault/memory now work;
34
+ * - on a machine that has registered before it returns the SAME account
35
+ * rather than a second, unfunded one, which is why this command is safe to
36
+ * re-run after a wiped credential store.
37
+ *
38
+ * Both outcomes are reported in the caller's own words — `trialOutcomeNote`
39
+ * from the shared module, so this cannot describe a reused machine as a clean
40
+ * install (the exact bug that clause exists for).
41
+ *
42
+ * ## Not a second credential
43
+ *
44
+ * There is no token of its own here. What it writes is the ordinary saved key
45
+ * in client/credentials.js, so `login`, `/key`, the desktop's Settings pane and
46
+ * every other host read the same one afterwards. A "connect" that invented its
47
+ * own store would be a second thing to go stale.
48
+ *
49
+ * ## `--status`
50
+ *
51
+ * The question a script and a first-run prompt both need answered without a
52
+ * side effect. Exit 0 when connected, 1 when not, 2 when it could not be
53
+ * established at all (no network, server refused) — the same 0/1/2 contract
54
+ * `fingerprint` uses, and for the same reason: "not connected" and "could not
55
+ * ask" are different events.
56
+ */
57
+
58
+ const { resolveClientModule } = require('./shared.js');
59
+ const { maskKey } = require('./format.js');
60
+ const { openUrl: defaultOpenUrl } = require('./system.js');
61
+
62
+ function load() {
63
+ return {
64
+ credentials: require(resolveClientModule('credentials.js')),
65
+ autoProvision: require(resolveClientModule('auto-provision.js')),
66
+ client: require(resolveClientModule('aegis.js')),
67
+ vault: require(resolveClientModule('record-vault.js')),
68
+ googleSignIn: require(resolveClientModule('google-signin.js')),
69
+ };
70
+ }
71
+
72
+ const HELP = `aegiscode connect — sign this machine in (and register it, if it is new).
73
+
74
+ Usage:
75
+ aegiscode connect sign in with Google (default) — opens a
76
+ browser; the key this machine saves is
77
+ tied to that account, so the same account
78
+ comes back on any machine signed in with it
79
+ aegiscode connect --anonymous sign in with an anonymous per-machine key
80
+ instead (no Google identity involved);
81
+ registers this device if it has no account
82
+ yet (one request, idempotent per machine —
83
+ a machine that registered before gets the
84
+ same account back)
85
+ aegiscode connect --status is this machine connected? (--json; exit 1
86
+ when it is not)
87
+ aegiscode connect --logout forget the saved key on this machine
88
+ aegiscode connect --help
89
+
90
+ What it gives you, with no further setup:
91
+ cloud memory sync, conversation sync, and the DEFAULT RECORD VAULT
92
+ (aegiscode fingerprint publish goes to your account vault).
93
+
94
+ It writes the same key \`aegiscode login\` writes, so a key you already saved is
95
+ used as-is: this never replaces a working credential.
96
+
97
+ Options:
98
+ --status report only; changes nothing
99
+ --anonymous, --device sign in with the anonymous per-machine key, not Google
100
+ --google sign in with Google (the default — accepted explicitly too)
101
+ --logout remove the saved key from this machine
102
+ --json machine-readable output
103
+ --app NAME the host name sent to the server (default: cli)
104
+ --base URL API base (same as $AEGIS_API_BASE)`;
105
+
106
+ /** `--flag value`, tolerating `--flag=value`. */
107
+ function flag(argv, name) {
108
+ for (let i = 0; i < argv.length; i += 1) {
109
+ const a = String(argv[i]);
110
+ if (a === name && argv[i + 1] !== undefined && !String(argv[i + 1]).startsWith('--')) return argv[i + 1];
111
+ if (a.startsWith(`${name}=`)) return a.slice(name.length + 1);
112
+ }
113
+ return null;
114
+ }
115
+
116
+ function has(argv, name) {
117
+ return (Array.isArray(argv) ? argv : []).some((a) => a === name || String(a).startsWith(`${name}=`));
118
+ }
119
+
120
+ /**
121
+ * The credential store, scoped to the environment this run was given.
122
+ *
123
+ * `credentials` resolves its directory from `AEGISCODE_HOME`, and an injected
124
+ * env is the whole reason this module takes one (the tests, a hosted agent, a
125
+ * `--base` against a staging account). Calling the store without the dir left
126
+ * every one of those reading the ambient `~/.aegiscode` instead — so a run
127
+ * meant for a scratch home reported the real user's account as "already
128
+ * connected" and skipped the registration it was asked for. Two variables, and
129
+ * both are needed: AEGIS_HOME holds the φ(α) keys, AEGISCODE_HOME the account
130
+ * key.
131
+ */
132
+ function storeFor(credentials, env) {
133
+ const dir = credentials.aegisHome(env);
134
+ return {
135
+ dir,
136
+ keyStatus: () => credentials.keyStatus({ env, dir }),
137
+ clearApiKey: () => credentials.clearApiKey(dir),
138
+ // autoProvisionApiKey calls exactly this one method on the store object.
139
+ saveApiKey: (key) => credentials.saveApiKey(key, dir),
140
+ };
141
+ }
142
+
143
+ /** The four fields a caller can act on, and nothing derived from the key. */
144
+ function report(credentials, vault, env) {
145
+ const st = credentials.keyStatus({ env, dir: credentials.aegisHome(env) });
146
+ let backend = null;
147
+ try {
148
+ backend = vault.vaultTarget(env, []).backend;
149
+ } catch {
150
+ backend = null;
151
+ }
152
+ return {
153
+ connected: Boolean(st.configured),
154
+ source: st.source || 'none',
155
+ path: st.path || null,
156
+ file_mode: st.fileMode || null,
157
+ // Only meaningful WITH a key: a memory token without an account key is a
158
+ // leftover in the env, and reporting "cloud sync ready" beside
159
+ // "connected: no" is the sort of contradiction that makes a status report
160
+ // untrustworthy.
161
+ memory_token: Boolean(st.configured && st.memoryToken),
162
+ vault_backend: backend,
163
+ // Never the key: this output is the one a user pastes into a bug report.
164
+ masked: st.configured ? maskKey(st.key) : null,
165
+ };
166
+ }
167
+
168
+ /**
169
+ * Run one subcommand. Returns the process exit code; never throws.
170
+ *
171
+ * @param {string[]} argv flags after `connect`
172
+ * @param {{stdout?:object, stderr?:object, env?:object, json?:boolean, fetch?:Function}} io
173
+ */
174
+ async function runConnect(argv = [], io = {}) {
175
+ const out = {
176
+ stdout: process.stdout,
177
+ stderr: process.stderr,
178
+ env: process.env,
179
+ json: false,
180
+ ...io,
181
+ json: Boolean(io.json) || has(argv, '--json'),
182
+ };
183
+ const fail = (code, message) => {
184
+ if (out.json) out.stdout.write(JSON.stringify({ connected: false, error: message }, null, 2) + '\n');
185
+ else out.stderr.write(`aegiscode: ${message}\n`);
186
+ return code;
187
+ };
188
+
189
+ try {
190
+ if (has(argv, '--help') || has(argv, '-h')) {
191
+ out.stdout.write(HELP + '\n');
192
+ return 0;
193
+ }
194
+
195
+ const { credentials, autoProvision, client, vault, googleSignIn } = load();
196
+ const base = flag(argv, '--base');
197
+ if (base) out.env.AEGIS_API_BASE = base;
198
+
199
+ const store = storeFor(credentials, out.env);
200
+
201
+ if (has(argv, '--logout')) {
202
+ const res = store.clearApiKey();
203
+ if (out.json) out.stdout.write(JSON.stringify({ connected: false, cleared: res.cleared }, null, 2) + '\n');
204
+ else {
205
+ out.stdout.write(
206
+ res.cleared
207
+ ? `aegiscode: key removed from ${res.path} — this machine is signed out\n`
208
+ : 'aegiscode: this machine had no saved key\n',
209
+ );
210
+ }
211
+ return 0;
212
+ }
213
+
214
+ if (has(argv, '--status')) {
215
+ const r = report(credentials, vault, out.env);
216
+ if (out.json) out.stdout.write(JSON.stringify(r, null, 2) + '\n');
217
+ else {
218
+ out.stdout.write(
219
+ [
220
+ `connected: ${r.connected ? 'yes' : 'no'}`,
221
+ `key: ${r.masked || 'not set'}${r.file_mode ? ` (${r.file_mode})` : ''}`,
222
+ `source: ${r.source}`,
223
+ `file: ${r.path || '-'}`,
224
+ `memory: ${r.memory_token ? 'token held (cloud sync ready)' : 'no token yet'}`,
225
+ `vault: ${r.vault_backend || 'unknown'} (record publishing)`,
226
+ r.connected ? '' : 'Sign in with: aegiscode connect',
227
+ ]
228
+ .filter((l) => l !== '')
229
+ .join('\n') + '\n',
230
+ );
231
+ }
232
+ return r.connected ? 0 : 1;
233
+ }
234
+
235
+ // Already connected: say so and stop. Re-registering to "make sure" would
236
+ // spend the server's per-IP registration budget for no gain, and this
237
+ // command must be safe to run twice.
238
+ const before = report(credentials, vault, out.env);
239
+ if (before.connected) {
240
+ if (out.json) out.stdout.write(JSON.stringify({ ...before, already: true }, null, 2) + '\n');
241
+ else {
242
+ out.stdout.write(
243
+ [
244
+ `already connected — ${before.masked} (${before.source})`,
245
+ `vault: ${before.vault_backend}`,
246
+ '',
247
+ 'Nothing changed. Sign out first (`aegiscode connect --logout`) to switch accounts.',
248
+ ].join('\n') + '\n',
249
+ );
250
+ }
251
+ return 0;
252
+ }
253
+
254
+ if (!has(argv, '--anonymous') && !has(argv, '--device')) {
255
+ const aegisForBase = client.createClient(credentials.clientOptions({ channel: 'cli', env: out.env, dir: store.dir }));
256
+ let session;
257
+ try {
258
+ session = await googleSignIn.startGoogleSignIn({ apiBase: aegisForBase.apiBase });
259
+ } catch (e) {
260
+ return fail(2, `could not start the local sign-in server — ${(e && e.message) || e}`);
261
+ }
262
+
263
+ if (!out.json) out.stdout.write(`aegiscode: opening a browser to sign in with Google…\n`);
264
+ const opener = io.openUrl || defaultOpenUrl;
265
+ if (!opener(session.url) && !out.json) {
266
+ out.stdout.write(`aegiscode: could not open a browser automatically — open this URL:\n ${session.url}\n`);
267
+ }
268
+
269
+ let googleResult;
270
+ try {
271
+ googleResult = await session.wait();
272
+ } catch (e) {
273
+ return fail(2, `google sign-in did not complete — ${(e && e.message) || e}`);
274
+ }
275
+
276
+ const saved = store.saveApiKey(googleResult.apiKey);
277
+ if (!saved.ok) {
278
+ return fail(2, saved.message || `could not save the key to ${saved.path}`);
279
+ }
280
+ if (googleResult.memoryToken) credentials.saveMemoryToken(googleResult.memoryToken, {}, store.dir);
281
+
282
+ const afterGoogle = report(credentials, vault, out.env);
283
+ if (out.json) {
284
+ out.stdout.write(
285
+ JSON.stringify({ ...afterGoogle, registered: true, provider: 'google', username: googleResult.username }, null, 2) + '\n',
286
+ );
287
+ return 0;
288
+ }
289
+ out.stdout.write(
290
+ [
291
+ `connected — ${afterGoogle.masked}${googleResult.username ? ` (signed in as ${googleResult.username})` : ''}`,
292
+ `key saved to ${afterGoogle.path}`,
293
+ `vault ${afterGoogle.vault_backend} — \`aegiscode fingerprint publish\` lands here`,
294
+ afterGoogle.memory_token ? 'Cloud memory sync is ready on this account.' : 'Cloud sync takes a moment to provision; the key is already valid.',
295
+ ].join('\n') + '\n',
296
+ );
297
+ return 0;
298
+ }
299
+
300
+ // --anonymous (or --device): the original door, kept for a user who wants
301
+ // no Google identity involved at all. The registration itself: the shared
302
+ // helper every host uses, so the account this mints is the one the
303
+ // desktop and the MCP plugin will find.
304
+ const aegis = client.createClient(credentials.clientOptions({ channel: 'cli', env: out.env, dir: store.dir }));
305
+ const result = await autoProvision.autoProvisionApiKey(aegis, store, {
306
+ app: flag(argv, '--app') || 'cli',
307
+ });
308
+
309
+ if (!result.key) {
310
+ return fail(2, `could not register this device — ${autoProvision.provisionFailureText(result)}`);
311
+ }
312
+
313
+ const after = report(credentials, vault, out.env);
314
+ const note = autoProvision.trialOutcomeNote(result);
315
+ if (out.json) {
316
+ out.stdout.write(
317
+ JSON.stringify(
318
+ {
319
+ ...after,
320
+ registered: true,
321
+ trial_granted: result.trialGranted,
322
+ reused_account: Boolean(result.reusedAccount),
323
+ saved: Boolean(result.ok),
324
+ },
325
+ null,
326
+ 2,
327
+ ) + '\n',
328
+ );
329
+ return result.ok ? 0 : 2;
330
+ }
331
+
332
+ out.stdout.write(
333
+ [
334
+ `${result.reusedAccount ? 'welcome back' : 'connected'} — ${after.masked}`,
335
+ `registered this machine${note}`,
336
+ `key ${result.ok ? `saved to ${after.path}` : 'COULD NOT SAVE — re-run `aegiscode connect`'}`,
337
+ `vault ${after.vault_backend} — \`aegiscode fingerprint publish\` lands here`,
338
+ '',
339
+ after.memory_token ? 'Cloud memory sync is ready on this account.' : 'Cloud sync takes a moment to provision; the key is already valid.',
340
+ result.reusedAccount ? '' : `Fund or inspect the account: ${aegis.promptUrl('topup', 'welcome_cloud')}`,
341
+ ]
342
+ .filter(Boolean)
343
+ .join('\n') + '\n',
344
+ );
345
+ return result.ok ? 0 : 2;
346
+ } catch (e) {
347
+ return fail(2, (e && e.message) || String(e));
348
+ }
349
+ }
350
+
351
+ module.exports = { runConnect, HELP, report };
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,10 +136,17 @@ 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) {
@@ -141,9 +175,14 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
141
175
  // payload's own class through, and then only one this host can run.
142
176
  const live = typeof getClass === 'function' ? getClass() : null;
143
177
  const stated = payload && payload.class;
144
- const cls = HOST_CLASSES.includes(live)
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)
145
184
  ? live
146
- : HOST_CLASSES.includes(stated)
185
+ : allowed.includes(stated)
147
186
  ? stated
148
187
  : DEFAULT_CLASS;
149
188
  return local.chat({ ...payload, class: cls }, onDelta);
@@ -155,15 +194,57 @@ function createEngine({ client, getConfirmMode, getClass, settings: injectedSett
155
194
  respondApproval: local.respondApproval,
156
195
  respondRoundsAsk: local.respondRoundsAsk,
157
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(),
158
217
  // The engine's own class table, narrowed to the ones this host runs — so a
159
218
  // UI built from listClasses() can never offer a class that would throw.
160
219
  // Async, like the local engine's: listClasses() probes Ollama (a live
161
220
  // HTTP round-trip) before it can answer, so returning the raw promise made
162
221
  // `/class` throw "filter is not a function". The caller awaits it.
163
- 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
+ },
164
228
  listModels: (cls) => local.listModels(cls || currentClass()),
229
+ // The user's own model declarations (`$AEGISCODE_HOME/models.json`), read
230
+ // through the shared store (`client/user-models.js`) this host's engine
231
+ // already applies to every `listModels('byok')` call. Exposed on the
232
+ // surface because a caller outside the engine needs to know WHEN that list
233
+ // changed: the picker's cache (`app.js` byokCache) is keyed on this file's
234
+ // content as well as on time, since a declaration written by the desktop's
235
+ // Custom provider card, by `/model-add` in another terminal, or by the
236
+ // user's editor cannot notify this process. Degrades to an empty map on a
237
+ // vendored tree that predates the reader (`local.userModels`), so a cache
238
+ // key can never throw on the path that paints a picker.
239
+ userModels: () =>
240
+ typeof local.userModels === 'function'
241
+ ? local.userModels()
242
+ : { dir: '', file: '', map: {}, invalid: [] },
165
243
  classLabel: (cls) => CLASS_LABELS[cls] || CLASS_LABELS[DEFAULT_CLASS],
166
244
  getClass: currentClass,
245
+ /** The classes selectable right now (see offeredClasses) — for surfaces
246
+ * that validate a class without instantiating a turn. */
247
+ offeredClasses: () => liveClasses(),
167
248
  settings,
168
249
  };
169
250
  }
@@ -206,4 +287,13 @@ function effortRung(effort) {
206
287
  return effort === 'low' || effort === 'medium' ? effort : 'high';
207
288
  }
208
289
 
209
- module.exports = { createEngine, HOST_CLASSES, DEFAULT_CLASS, CLASS_LABELS, byokNamespace, effortRung };
290
+ module.exports = {
291
+ createEngine,
292
+ HOST_CLASSES,
293
+ DEFAULT_CLASS,
294
+ CLASS_LABELS,
295
+ offeredClasses,
296
+ proEnabled,
297
+ byokNamespace,
298
+ effortRung,
299
+ };