aegiscode 6.8.5 → 6.8.6

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.5",
4
+ "version": "6.8.6",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
@@ -116,6 +116,13 @@ const FILES = [
116
116
  // both sit above; `queue.js` requires only node builtins.
117
117
  'desktop/lib/local/queue.js',
118
118
  'desktop/lib/local/autonomous.js',
119
+ // The shared Pro gate. `autonomous.js` requires `src/entitlement.js` at load
120
+ // time, and that module locates this file by EXISTENCE through
121
+ // `resolveShared` — never by a fallback copy — so a vendor tree missing it
122
+ // throws before the CLI can print its usage, the same failure class as 6.5.6.
123
+ // The module requires nothing at all: the account probe is injected by the
124
+ // caller, which is why staging it alone is enough.
125
+ 'desktop/lib/local/entitlement.js',
119
126
  ];
120
127
 
121
128
  function main() {
package/src/app.js CHANGED
@@ -112,7 +112,7 @@ function createApp(options = {}) {
112
112
  // survive a new shell, and until it is *stored* every one of those launches
113
113
  // is "no key" with no in-band way to set one. An injected client keeps
114
114
  // whatever key it was built with.
115
- const client = options.client || createClient(credentials.clientOptions());
115
+ const client = options.client || createClient(credentials.clientOptions({ channel: 'cli' }));
116
116
  const { TOOLS, toolList } = options.tools || createTools(client);
117
117
 
118
118
  // Tool-approval gate (exec/writeFile/editFile confirm before running).
package/src/autonomous.js CHANGED
@@ -136,12 +136,26 @@ function printRunReport(ran, io) {
136
136
  */
137
137
  function buildEngine({ io, quiet = false }) {
138
138
  const credentials = require('./credentials.js');
139
- const client = require('./deps.js').createClient(credentials.clientOptions());
139
+ const client = require('./deps.js').createClient(credentials.clientOptions({ channel: 'cli' }));
140
140
  if (!client.apiKey) {
141
- return { error: `no AEGIS account key — ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}` };
141
+ return { error: `no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV}` };
142
142
  }
143
143
  const engine = createEngine({ client, getConfirmMode: () => false });
144
- return { client, engine };
144
+ // The Pro gate (Phase 7). Built from the SAME shared decision the desktop
145
+ // uses, bound to this host's channel so a refusal links `?s=cli` and not
146
+ // `?s=desktop` — see cli/src/entitlement.js. Passed to the worker below as
147
+ // `canFanOut`, which is the seam the shared worker already had and this host
148
+ // never supplied (so it defaulted to "yes" and the fan-out was free here).
149
+ let entitlement = null;
150
+ try {
151
+ entitlement = require('./entitlement.js').createCliEntitlement({ aegis: client });
152
+ } catch {
153
+ // A gate that cannot be built must not be a gate that says yes. The worker
154
+ // fails closed on a missing predicate (`safeCanFanOut`), so leaving this
155
+ // null clamps the drain to single passes rather than spending the fan-out.
156
+ entitlement = null;
157
+ }
158
+ return { client, engine, entitlement };
145
159
  }
146
160
 
147
161
  /** A progress sink for a headless drain: one line per step, never a chat delta. */
@@ -169,6 +183,14 @@ function progressSink(io, { json }) {
169
183
  io.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${event.phases.join(', ')}\n`);
170
184
  return;
171
185
  }
186
+ // `note` is how the shared worker reports the fan-out clamp ("this task ran
187
+ // as a single pass"). It was emitted and then dropped on the floor here,
188
+ // which made the gate invisible from the terminal: a drain that silently
189
+ // ran one worker looked identical to one that was entitled to eight.
190
+ if (event.type === 'note' && event.note) {
191
+ io.stderr.write(` ⓘ ${event.note}\n`);
192
+ return;
193
+ }
172
194
  if (event.type === 'recovered') {
173
195
  io.stdout.write(`aegiscode: re-queued task(s) ${event.ids.join(', ')} from a dead worker\n`);
174
196
  }
@@ -277,11 +299,79 @@ async function runQueueCommand(command, argv, io = {}) {
277
299
  stderr.write(`aegiscode autonomous: ${built.error}\n`);
278
300
  return 2;
279
301
  }
302
+ // Read the gate BEFORE the first task, not lazily per task. A snapshot that
303
+ // was never refreshed reads as `unresolved`, which `current()` reports as
304
+ // free — so a PRO account would have its fan-out quietly clamped to a single
305
+ // pass for the whole drain. That is the gate failing in the direction that
306
+ // takes the paid feature away from the paying customer, so one awaited read
307
+ // happens up front and the rest of the drain answers from the cached
308
+ // snapshot (TTL a minute — see DEFAULT_TTL_MS; a drain must not probe per
309
+ // task).
310
+ if (built.entitlement) {
311
+ try {
312
+ await built.entitlement.refresh();
313
+ } catch {
314
+ // Unreachable leaves the snapshot unresolved, i.e. free. Fail-closed is
315
+ // the right direction: the alternative lets a network blip hand out the
316
+ // paid fan-out.
317
+ }
318
+ }
280
319
  const worker = autonomous.createQueueWorker({
281
320
  engine: built.engine,
282
321
  env: process.env,
283
322
  log: progressSink(out, { json }),
323
+ // THE SEAM THIS HOST NEVER SUPPLIED. `createQueueWorker` defaults this to
324
+ // `() => true`, so until now a fan-out asked for in the terminal — or
325
+ // written into queue.jsonl by hand, or left there by another host's older
326
+ // build — spent the multiplier the gate exists to withhold, with no window
327
+ // and nobody to ask. The shared worker already clamps it (`safeCanFanOut`),
328
+ // and a throwing predicate already fails closed; a gate that could not be
329
+ // BUILT at all must read the same way, hence the explicit null → false.
330
+ canFanOut: () => {
331
+ if (!built.entitlement) return false;
332
+ try {
333
+ const snap = built.entitlement.current();
334
+ return Boolean(snap && snap.entitled === true);
335
+ } catch {
336
+ return false;
337
+ }
338
+ },
284
339
  });
340
+ // One promotion per drain, not one per task: the clamp note fires for every
341
+ // fanned-out task, and repeating a checkout link eight times in a log is
342
+ // spam, not promotion. Printed only for a READ WE ACTUALLY TRUST —
343
+ // `degraded` is the module's flag for "we did not get a real answer"
344
+ // (timeout, unparseable body, missing plan field), and an upsell printed on
345
+ // the strength of a timeout is a guess wearing a price tag. `unresolved` is
346
+ // the same rule one level up: the boot snapshot, which nobody asked.
347
+ if (built.entitlement) {
348
+ try {
349
+ const snap = built.entitlement.current();
350
+ if (snap && snap.entitled === false && snap.degraded === false && snap.refusal) {
351
+ stderr.write(`aegiscode autonomous: ${snap.refusal}\n`);
352
+ // The ask, in the message, as an example to write — not as a feature
353
+ // name to decode. `autonomously` is the word the drain actually reads
354
+ // (queue.js stores the inverse as `singlePass`), so the terminal shows
355
+ // the sentence to type.
356
+ stderr.write(' ↳ write tasks like: Do X autonomously\n');
357
+ // HOW to unlock, and it names BOTH routes because there are two:
358
+ // `entitlement.js` sets `entitled = pro || banked`, where the bank is
359
+ // the operator's own lever (aegis1 admin `add_funds`). Printing only
360
+ // "upgrade" would send a user with an empty bank to the plan page when
361
+ // topping up is the action that clears their wall — `snap.wall` is the
362
+ // module's own word for which wall this is, so the line follows it
363
+ // instead of guessing.
364
+ stderr.write(
365
+ snap.wall === 'balance'
366
+ ? ' ↳ unlock: top up the Token Bank, or upgrade to Pro\n'
367
+ : ' ↳ unlock: Pro, or any Token Bank balance\n'
368
+ );
369
+ if (snap.upgradeUrl) stderr.write(` ${snap.upgradeUrl}\n`);
370
+ }
371
+ } catch {
372
+ // A snapshot that cannot be read prints nothing — same rule as above.
373
+ }
374
+ }
285
375
  const commit = args.flags.commit ? true : undefined;
286
376
  const onSigint = () => {
287
377
  // Ctrl-C stops the RUNNING turn, not the process: the task is settled back
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * entitlement.js — the terminal host's binding to the SHARED Pro gate.
5
+ *
6
+ * WHY THIS FILE EXISTS (and why it is six lines of real work). The gate that
7
+ * decides who may spend the fan-out lives in
8
+ * `desktop/lib/local/entitlement.js`, and the CLI has been the leak since the
9
+ * day it landed: `autonomous.js` drives the SAME queue file through the SAME
10
+ * worker, `createWorker` takes a `canFanOut` predicate, and the CLI simply
11
+ * never passed one — so it defaulted to `() => true`. A task queued with
12
+ * `--workers 8` or written into queue.jsonl by hand fans out on the free tier
13
+ * from `ssh box 'aegiscode autonomous proceed'`, costing the multiplier the
14
+ * gate exists to withhold, with no window and nobody to ask.
15
+ *
16
+ * The desktop's own comment named this as a known gap ("the CLI's own drain is
17
+ * a different host with no session to ask"). It had a session — it has the same
18
+ * account key in the same 0600 store, read through the same shared client. It
19
+ * was a wiring omission, not an architectural one.
20
+ *
21
+ * TWO THINGS ARE HOST-SPECIFIC, and both are handled by the shared module's own
22
+ * seams rather than reimplemented here:
23
+ *
24
+ * 1. THE CHANNEL. `host: 'cli'` makes every refusal link
25
+ * `/go/upgrade?s=cli&…`, so a terminal click is filed as a CLI conversion
26
+ * instead of a desktop one. The desktop's literals hardcode `s=desktop`;
27
+ * printing one from the terminal would have quietly moved every CLI
28
+ * conversion into the desktop's column.
29
+ * 2. THE PROBE. The CLI has no Electron session, so it builds the same
30
+ * reading the desktop builds — `verifyApiKey()` for the plan plus
31
+ * `tokenBankBalance()` for the operator's balance — from the shared client
32
+ * directly.
33
+ *
34
+ * Not reimplemented, deliberately: the plan vocabulary, the balance
35
+ * interpretation, the fail-closed rules, the refusal copy, the campaign ids.
36
+ * Two implementations of "is this account paid" is exactly how the terminal and
37
+ * the GUI would come to disagree about who owes money — and the disagreement
38
+ * would spend real money, in whichever host had the looser copy.
39
+ *
40
+ * Wired through `sharedpaths.js` (paths, no eager requires) rather than
41
+ * `deps.js`, because `deps.js` eagerly loads `autonomous.js`, which loads THIS
42
+ * file back: requiring deps.js here would be a require cycle handing one side a
43
+ * half-built exports object. Same reason `sharedpaths.js` was split out.
44
+ */
45
+
46
+ const { resolveShared } = require('./sharedpaths.js');
47
+
48
+ /** The shared decision, resolved by existence (repo checkout or staged tree). */
49
+ function loadModule() {
50
+ // eslint-disable-next-line global-require
51
+ return require(resolveShared('desktop/lib/local/entitlement.js'));
52
+ }
53
+
54
+ /** The shared thin transport, same two-layout resolution as deps.js. */
55
+ function loadClient() {
56
+ // eslint-disable-next-line global-require
57
+ const { createClient } = require(resolveShared('client/aegis.js'));
58
+ const credentials = require('./credentials.js');
59
+ return createClient(credentials.clientOptions({ channel: 'cli' }));
60
+ }
61
+
62
+ /**
63
+ * The account probe, shaped exactly as the desktop builds it.
64
+ *
65
+ * A failed balance call leaves the balance UNKNOWN rather than inventing a
66
+ * zero: an unreadable bank must never manufacture a top-up prompt, and
67
+ * `classifyProbe` fails closed on the unknown anyway. Both calls are read-only
68
+ * and neither writes server-side — the gate observes the operator's number, it
69
+ * never sets one.
70
+ */
71
+ function buildProbe(aegis) {
72
+ if (!aegis || typeof aegis.verifyApiKey !== 'function') return undefined;
73
+ return async () => {
74
+ const verify = await aegis.verifyApiKey();
75
+ const body = verify && typeof verify === 'object' ? { ...verify } : {};
76
+ if (typeof aegis.tokenBankBalance === 'function') {
77
+ try {
78
+ const bank = await aegis.tokenBankBalance();
79
+ if (bank && typeof bank === 'object') {
80
+ if (bank.balance_micros != null) body.balance_micros = bank.balance_micros;
81
+ else if (bank.balance_eur != null) body.balance_eur = bank.balance_eur;
82
+ }
83
+ } catch {
84
+ // Unknown stays unknown — see the docstring above.
85
+ }
86
+ }
87
+ return body;
88
+ };
89
+ }
90
+
91
+ /**
92
+ * The gate for one CLI process, reading the SAME account the desktop reads.
93
+ *
94
+ * `host: 'cli'` is the whole reason campaign links can be trusted from here.
95
+ * Returns the shared gate object: `{ refresh, current, gateFanout }`.
96
+ */
97
+ function createCliEntitlement({ aegis, now, ttlMs } = {}) {
98
+ const mod = loadModule();
99
+ const client = aegis || loadClient();
100
+ return mod.createEntitlement({
101
+ probe: buildProbe(client),
102
+ host: 'cli',
103
+ ...(now ? { now } : {}),
104
+ ...(ttlMs ? { ttlMs } : {}),
105
+ });
106
+ }
107
+
108
+ module.exports = { createCliEntitlement, buildProbe, loadModule };
@@ -134,9 +134,41 @@ function createClient(opts = {}) {
134
134
  const memoryToken =
135
135
  opts.memoryToken !== undefined ? opts.memoryToken : envVar('AEGIS_MEMORY_TOKEN');
136
136
  const clientVersion = opts.clientVersion || CLIENT_VERSION;
137
+ // Which host is asking, purely so an upgrade prompt raised from inside this
138
+ // shared client is filed against the right product. aegis1 stores an
139
+ // unrecognised source as NULL and reports it as `direct`, so an unknown
140
+ // value here is a silently destroyed datapoint rather than a visible error —
141
+ // hence the allowlist rather than trusting the caller.
142
+ const channel = opts.channel === 'cli' ? 'cli' : 'desktop';
137
143
 
138
144
  let memoryTokenCache = null;
139
145
 
146
+ /**
147
+ * A campaign-tagged upgrade link. Never hand-build a `/subscribe` URL in a
148
+ * prompt: the bare form carries no attribution, so the click arrives as
149
+ * `direct` and the surface that produced it can never be credited.
150
+ * The campaign must be one of the ids fixed in `docs/upgrade-conversion-plan.md`
151
+ * §1 (`welcome_cloud`, `queue_cap`, `memory_quota`, `status_card`,
152
+ * `topup_bank`) — a sixth id invented here is a row no report or allowlist
153
+ * knows about, which is the same destroyed datapoint as an untagged link.
154
+ * The slug is checked against aegis1's `_sanitize_signup_slug` shape rather
155
+ * than an allowlist, because this module is shared by every host and cannot
156
+ * know the server's current list.
157
+ * Returns '' if the base is not a parseable absolute URL, so a caller can
158
+ * fall back to plain text instead of rendering "undefined" at a user.
159
+ */
160
+ function promptUrl(page, campaign) {
161
+ try {
162
+ const url = new URL(`/go/${String(page || 'upgrade').replace(/^\/+|\/+$/g, '')}`, apiBase);
163
+ url.searchParams.set('s', channel);
164
+ const c = String(campaign || '').trim().toLowerCase();
165
+ if (/^[a-z0-9][a-z0-9_-]{0,63}$/.test(c)) url.searchParams.set('c', c);
166
+ return url.toString();
167
+ } catch (e) {
168
+ return '';
169
+ }
170
+ }
171
+
140
172
  // -------------------------------------------------------------------------
141
173
  // HTTP helpers
142
174
  // -------------------------------------------------------------------------
@@ -174,6 +206,63 @@ function createClient(opts = {}) {
174
206
  return parseResponse(res);
175
207
  }
176
208
 
209
+ /**
210
+ * A 426 `version_mismatch` from either server gate: this client is too old
211
+ * to be served. The body carries the minimum it failed (`required`), the
212
+ * npm dist-tags to move to (`latest_cli`/`latest_desktop`) and where to get
213
+ * them, so a host can show an upgrade prompt naming a target instead of a
214
+ * bare "connection refused".
215
+ *
216
+ * Surfaced as a typed error (`code` + `upgrade`) rather than only a message
217
+ * so hosts can branch on it without parsing prose, and so the desktop/MCP
218
+ * shells can open the upgrade panel with a version already filled in.
219
+ *
220
+ * The upgrade link is rebuilt through promptUrl() rather than trusting
221
+ * `update_url` verbatim: a server-supplied bare URL carries no `?s=`/`?c=`,
222
+ * so the click is filed as `direct` and the surface that hit the gate can
223
+ * never be credited for the conversion it caused. The server value is kept
224
+ * as a fallback for hosts reaching a base we cannot parse.
225
+ */
226
+ function versionGateError(data, status) {
227
+ const body = data || {};
228
+ const latestCli = body.latest_cli || '';
229
+ const latestDesktop = body.latest_desktop || '';
230
+ // Prefer a real published version; fall back to the minimum so the
231
+ // message always names something the user can act on.
232
+ const target = latestCli || latestDesktop || body.required || '';
233
+ const err = new Error(
234
+ target
235
+ ? `This client (v${clientVersion}) is out of date — upgrade to v${target}.`
236
+ : `This client (v${clientVersion}) is out of date.`
237
+ );
238
+ err.status = status;
239
+ err.code = 'version_mismatch';
240
+ err.data = body;
241
+ err.upgrade = {
242
+ required: body.required || '',
243
+ latestCli,
244
+ latestDesktop,
245
+ // Campaign is `version_gate`: a refusal to serve is its own reason to
246
+ // pay, distinct from a quota wall, and summing them hides which lever
247
+ // the upgrade prompt is actually pulling.
248
+ //
249
+ // Guarded on typeof, not called directly: the attribution helper is a
250
+ // separate concern from the gate, and a gate that throws because the
251
+ // campaign tagger is absent would turn "your client is old" into
252
+ // "undefined is not a function" on the one path whose whole job is to
253
+ // tell the user what to do. Falls back to the server's own update_url.
254
+ url: (typeof promptUrl === 'function' ? promptUrl('upgrade', 'version_gate') : '')
255
+ || body.update_url
256
+ || '',
257
+ };
258
+ return err;
259
+ }
260
+
261
+ /** Is this error body the version gate rather than a normal failure? */
262
+ function isVersionGate(status, data) {
263
+ return status === 426 || (data && data.code === 'version_mismatch');
264
+ }
265
+
177
266
  async function parseResponse(res) {
178
267
  const text = await res.text();
179
268
  let data;
@@ -183,6 +272,9 @@ function createClient(opts = {}) {
183
272
  data = { raw: text };
184
273
  }
185
274
  if (!res.ok) {
275
+ if (isVersionGate(res.status, data)) {
276
+ throw versionGateError(data, res.status);
277
+ }
186
278
  const msg =
187
279
  (data && (data.error?.message || data.error || data.message)) ||
188
280
  `HTTP ${res.status}`;
@@ -191,6 +283,12 @@ function createClient(opts = {}) {
191
283
  err.data = data;
192
284
  throw err;
193
285
  }
286
+ // A 2xx carrying a version gate body: some streaming endpoints answer
287
+ // JSON with a real status mid-stream. Without this the gate would be
288
+ // invisible on exactly those paths.
289
+ if (data && data.code === 'version_mismatch') {
290
+ throw versionGateError(data, res.status);
291
+ }
194
292
  return data;
195
293
  }
196
294
 
@@ -209,6 +307,12 @@ function createClient(opts = {}) {
209
307
  /** Throw an Error carrying status/data from a 2xx body that still has an
210
308
  * error field (seen on streaming endpoints that answer JSON mid-stream). */
211
309
  function throwErrorFrom(data, status) {
310
+ // Keep the gate typed on this path too: it is the one that carries JSON
311
+ // errors inside an otherwise-successful stream, which is where a gate
312
+ // response would otherwise be flattened into a generic message.
313
+ if (data && data.code === 'version_mismatch') {
314
+ throw versionGateError(data, status || 426);
315
+ }
212
316
  const msg = errorMessageOf(data);
213
317
  if (!msg) return;
214
318
  const err = new Error(msg);
@@ -223,8 +327,16 @@ function createClient(opts = {}) {
223
327
  if (memoryTokenCache) return memoryTokenCache;
224
328
  const info = await apiPost('/api/verify-api-key', { api_key: apiKey });
225
329
  if (!info || !info.memory_token) {
330
+ // The campaign is Phase 1's `memory_quota`, not a new `memory_token`: the
331
+ // prompt family (memory cap notice, memory list, memory view) files under
332
+ // one id so the funnel keeps one row per prompt intent, and the plan's
333
+ // five ids are what the telemetry allowlist and the baseline table carry.
334
+ const link = promptUrl('upgrade', 'memory_quota');
226
335
  throw new Error(
227
- 'This AEGIS account has no memory token. Enable cloud memory at https://aegiscloud.org/subscribe.'
336
+ 'This AEGIS account has no memory token. '
337
+ + (link
338
+ ? `Enable cloud memory at ${link}`
339
+ : 'Enable cloud memory in your AEGIS account settings.')
228
340
  );
229
341
  }
230
342
  memoryTokenCache = info.memory_token;
@@ -464,6 +576,23 @@ function createClient(opts = {}) {
464
576
  throw err; // network-level failure; nothing to fall back to
465
577
  }
466
578
 
579
+ // A version gate is a pre-flight refusal, not a schema complaint: the
580
+ // server rejects *every* shape of this request with 426, so the
581
+ // `stream_options` retry below and the `stream: false` fallback after it
582
+ // each buy a wasted round-trip and then report an opaque status. Fail on
583
+ // the first one. Checked by status alone (no body read) so the happy path
584
+ // pays nothing for this.
585
+ if (!res.ok && res.status === 426) {
586
+ let gateData = {};
587
+ try {
588
+ const t = await res.text();
589
+ gateData = t ? JSON.parse(t) : {};
590
+ } catch {
591
+ gateData = {}; // a gate with an unreadable body is still a gate
592
+ }
593
+ throw versionGateError(gateData, res.status);
594
+ }
595
+
467
596
  // Ask for the token count, but never at the cost of the stream: a server
468
597
  // that predates `stream_options` rejects the request outright, so drop that
469
598
  // one hint and put it back on the wire before falling back to a non-stream
@@ -860,6 +989,10 @@ function createClient(opts = {}) {
860
989
  get clientVersion() {
861
990
  return clientVersion;
862
991
  },
992
+ get channel() {
993
+ return channel;
994
+ },
995
+ promptUrl,
863
996
  verifyApiKey,
864
997
  chatCompletion,
865
998
  byokChatCompletion,
@@ -951,7 +1084,18 @@ function idleBudgetFor(res, requestedMs) {
951
1084
  return header && String(header).trim() ? Math.max(base, brainFloor) : base;
952
1085
  }
953
1086
 
954
- const api = { createClient, envVar, randomUUID, DEFAULT_API_BASE, CLIENT_VERSION, idleBudgetFor, SSE_IDLE_TIMEOUT_MS, BRAIN_IDLE_TIMEOUT_MS };
1087
+ /**
1088
+ * Host-facing predicate: does a thrown error mean "upgrade this client"?
1089
+ *
1090
+ * Hosts catch from a shared client, and a bare `err.status === 426` check
1091
+ * misses the gate bodies that arrive inside an otherwise-200 stream. Matched
1092
+ * on the typed `code` the client sets, so a host never has to parse prose.
1093
+ */
1094
+ function isVersionGateError(err) {
1095
+ return !!(err && err.code === 'version_mismatch');
1096
+ }
1097
+
1098
+ const api = { createClient, envVar, randomUUID, DEFAULT_API_BASE, CLIENT_VERSION, isVersionGateError, idleBudgetFor, SSE_IDLE_TIMEOUT_MS, BRAIN_IDLE_TIMEOUT_MS };
955
1099
 
956
1100
  // Node / Electron (CommonJS): the MCP plugin and desktop shell require() this.
957
1101
  if (typeof module !== 'undefined' && module.exports) {
@@ -307,6 +307,10 @@ function clientOptions(o = {}) {
307
307
  const opts = {};
308
308
  if (key) opts.apiKey = key;
309
309
  if (token) opts.memoryToken = token;
310
+ // The host names itself so upgrade prompts raised inside the shared client
311
+ // are attributed to the right product. Unset means desktop, which matches
312
+ // createClient's own default.
313
+ if (o.channel) opts.channel = o.channel;
310
314
  return opts;
311
315
  }
312
316
 
@@ -402,7 +402,28 @@ function errorText(err) {
402
402
  * @param {object} [opts.git] Injectable git-scope (tests).
403
403
  * @param {function} [opts.now] Clock.
404
404
  */
405
- function createQueueWorker({ engine, env = process.env, log = () => {}, git = gitScope, now = Date.now } = {}) {
405
+ function createQueueWorker({
406
+ engine,
407
+ env = process.env,
408
+ log = () => {},
409
+ git = gitScope,
410
+ now = Date.now,
411
+ // May a task fan out AT ALL this session? The default preserves every host's
412
+ // behaviour (a CLI drain, a systemd timer: no entitlement, no clamp), and
413
+ // main.js passes the queue's entitlement gate — see
414
+ // desktop/lib/local/entitlement.js and Phase 4 of
415
+ // docs/upgrade-conversion-plan.md.
416
+ //
417
+ // This exists because the fan-out is otherwise reachable around the desktop's
418
+ // IPC gate: a task queued by the CLI or written into queue.jsonl by hand
419
+ // carries `singlePass: false`, and main.js had already accepted it long
420
+ // before anyone asked about entitlement. Refusing the whole task would be
421
+ // worse than the leak (the free tier keeps working — that is a promise), so
422
+ // the request is honoured as a SINGLE PASS and said out loud via a `note`
423
+ // frame: the run is clamped, never silently different from what the card
424
+ // shows.
425
+ canFanOut = () => true,
426
+ } = {}) {
406
427
  if (!engine || typeof engine.chat !== 'function') {
407
428
  throw new Error('autonomous: a local engine with chat() is required');
408
429
  }
@@ -415,6 +436,18 @@ function createQueueWorker({ engine, env = process.env, log = () => {}, git = gi
415
436
  }
416
437
  };
417
438
 
439
+ /** `canFanOut` is host-supplied, so it is treated like any other injected
440
+ * seam: a predicate that throws must not abort a drain — it fails CLOSED
441
+ * (no fan-out), because the alternative is spending the multiplier the gate
442
+ * exists to withhold. */
443
+ const safeCanFanOut = () => {
444
+ try {
445
+ return canFanOut() !== false;
446
+ } catch {
447
+ return false;
448
+ }
449
+ };
450
+
418
451
  /**
419
452
  * Run ONE queued task. Never throws: a failed task is data (so the drain can
420
453
  * decide whether to continue), not an exception that aborts the queue.
@@ -437,7 +470,21 @@ function createQueueWorker({ engine, env = process.env, log = () => {}, git = gi
437
470
  const model = resolveModel({ model: item.model, env });
438
471
  const ignored = ignoredEnvModel({ model: item.model, env });
439
472
  if (ignored) emit({ type: 'note', taskId: item.id, note: ignored });
440
- const fanout = resolveFanout(item, env);
473
+ const fanoutAsked = resolveFanout(item, env);
474
+ // The clamp. `canFanOut()` is the entitlement answer (true everywhere
475
+ // except a non-Pro desktop session), and it can only ever take a fan-out
476
+ // AWAY: a task the session is not entitled to fan out runs as one plain
477
+ // turn on the same tier, exactly like a `singlePass` task.
478
+ const fanout = fanoutAsked && safeCanFanOut();
479
+ if (fanoutAsked && !fanout) {
480
+ emit({
481
+ type: 'note',
482
+ taskId: item.id,
483
+ note:
484
+ 'fan-out needs Pro (the cloud drain that keeps running after you close ' +
485
+ 'the laptop) — this task ran as a single pass',
486
+ });
487
+ }
441
488
  const effort = resolveEffort({ effort: item.effort, env, fanout });
442
489
  const rounds = maxRounds(env, item.maxRounds);
443
490
  // Approval requests have no one to answer them here; see the header.
@@ -496,6 +543,26 @@ function createQueueWorker({ engine, env = process.env, log = () => {}, git = gi
496
543
  // the default for exactly that reason; the retry/write-up passes in
497
544
  // the engine send `brain: false` for the same one-call reason.
498
545
  autonomous: fanout,
546
+ // THE OPT-OUT HAS TO BE SAID OUT LOUD, or the clamp above is
547
+ // decoration. `autonomous: false` does NOT reach the wire as a
548
+ // "no fan-out": engine.js derives its brain flag as
549
+ // `opts.singlePass ? false : opts.autonomous ? true : undefined`, so
550
+ // false-and-not-singlePass evaluates to `undefined`, and an absent
551
+ // `brain` means "leave the model id's own default alone". The model
552
+ // here IS `nexus-brain`, and aegis1 services/pool_brain.py
553
+ // parse_brain_request enables the fan-out when
554
+ // `is_brain_model(spec)` — no flag or worker count required:
555
+ //
556
+ // enabled = not flag_off and (is_brain_model(spec) or flag_on or ...)
557
+ //
558
+ // So a clamped task went out asking for the full workers+1
559
+ // fan-out and got it, while the log said it ran as a single pass.
560
+ // `brain: false` is the only instruction that outranks the model id
561
+ // (pool_brain's own docstring: "the only way to ask for one provider
562
+ // call on a brain id"), and `singlePass: true` is how a caller
563
+ // produces it. This also fixes the plain `--single-pass` task, which
564
+ // never reached the wire as one for the same reason.
565
+ singlePass: !fanout,
499
566
  effort,
500
567
  workers: fanout ? item.workers || undefined : undefined,
501
568
  // The turn's working directory rides on `env`: engine.js reads the
@@ -1296,6 +1296,16 @@ function createLocalEngine({
1296
1296
  // field is off, which is what keeps every existing caller (the
1297
1297
  // renderer's IPC payloads included) on the cheap read.
1298
1298
  recallDeep: payload && payload.recallDeep === true,
1299
+ // The fan-out opt-out, and it must be an explicit `true` for the same
1300
+ // reason `recallDeep` is. `undefined` is NOT an opt-out: the wire flag
1301
+ // below is `singlePass ? false : autonomous ? true : undefined`, and an
1302
+ // absent `brain` flag lets the *model id* turn the fan-out on by itself
1303
+ // (aegis1 pool_brain.parse_brain_request: `is_brain_model(spec)` alone
1304
+ // enables it). So a clamped task on a brain model fanned out anyway
1305
+ // while the log claimed a single pass — the caller's intent never
1306
+ // reached the wire. Forwarding it here is what lets the refusal be real
1307
+ // rather than a local boolean nobody downstream could see.
1308
+ singlePass: payload && payload.singlePass === true,
1299
1309
  onReasoning,
1300
1310
  idleTimeoutMs: autonomous ? AUTONOMOUS_IDLE_TIMEOUT_MS : undefined,
1301
1311
  // A caller with no live streaming surface (a `--no-stream` CLI flag, a
@@ -0,0 +1,487 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * entitlement.js — the Pro boundary for the autonomous queue.
5
+ *
6
+ * Phase 4 of docs/upgrade-conversion-plan.md. The queue is the feature people
7
+ * actually pay for, and until this file existed it was 100% free and ungated:
8
+ * `registerQueueIpc` in main.js checked no key, no plan and no quota, so the
9
+ * single most expensive thing this app can do (an unattended task, optionally
10
+ * fanned out across pooled workers) ran forever on the free tier.
11
+ *
12
+ * WHAT IS GATED, AND WHY IT IS THE FAN-OUT. Free keeps everything local: the
13
+ * drain runs on the user's own key, in this process, while the window is open.
14
+ * The *fan-out* is the multiplier — aegis1's pool_brain spawns up to `workers`
15
+ * reasoning workers plus a synthesis pass and re-sends the task context to each
16
+ * (see autonomous.js resolveFanout) — so that is the worker ceiling this module
17
+ * enforces: free = 1 worker (a plain single-pass turn), Pro = the fan-out plus
18
+ * the cloud drain it belongs to. Nothing here changes price, the memory cap or
19
+ * the free-tier definition; it only stops the free tier from spending the Pro
20
+ * tier's multiplier.
21
+ *
22
+ * WHERE THE GATE LIVES. This module is the DECISION; main.js is the DOOR.
23
+ * `registerQueueIpc` consults it, so a renderer that never renders the fan-out
24
+ * control cannot get a fan-out anyway — renderer-side gating is cosmetic and
25
+ * trivially bypassed (any devtools console can call `window.queue.enqueue`).
26
+ * Nothing in the renderer decides entitlement; it displays what main tells it.
27
+ *
28
+ * THE SIGNAL (see the report / the module's `probe`): main injects a probe that
29
+ * calls `aegis.verifyApiKey()` — aegis1 `/api/verify-api-key`, which its own
30
+ * docstring describes as "Verify a shared api_key and return plan/email/
31
+ * memory_token". The plan field is the account's stored plan, and aegis1 owns
32
+ * the vocabulary for it (`services/billing_service.py`: `PAID_PLANS = ("pro",)`
33
+ * plus the legacy aliases that normalize onto it). This module MIRRORS that
34
+ * vocabulary rather than inventing one; there is no new billing anything here,
35
+ * no new endpoint, and no write to the server.
36
+ *
37
+ * PHASE 6 — THE SECOND SIGNAL, THE BALANCE. The plan is only half of how this
38
+ * product charges. aegis1's actual paywall is the Token Bank running dry: the
39
+ * balance is prepaid EUR the OPERATOR credits by hand, and `app.py` states the
40
+ * consequence plainly — "Pool-key users with token bank balance skip legacy
41
+ * credit checks." So entitlement here is `pro || balance > 0`, and when the
42
+ * bank reads zero the wall names the fix that exists (a top-up, campaign
43
+ * `topup_bank`) instead of a plan checkout the user may already own. Nothing in
44
+ * this module grants a balance, expires one, or auto-charges: the operator
45
+ * decides when an account pays, and this file only reads the number they set.
46
+ * An unreadable balance is UNKNOWN, not zero — a network blip must never
47
+ * manufacture a paywall, and only a balance we actually read can be "empty".
48
+ *
49
+ * FAIL CLOSED, AND SAY SO. Every way of not knowing — no key on the machine, an
50
+ * offline/500 probe, a plan string outside the vocabulary — resolves to the
51
+ * free boundary, and the snapshot carries `degraded: true` plus the reason so
52
+ * the UI and the report can be honest about it. The fan-out is real money; an
53
+ * unknown entitlement must not hand it out. The cost is the opposite error (a
54
+ * paying customer offline at that instant is held to one worker for the length
55
+ * of one TTL), which is bounded, visible in the note, and recoverable by
56
+ * re-probing — the next `refresh()` after the TTL flips it back.
57
+ *
58
+ * Pure Node on purpose: no Electron, no network of its own (the probe is
59
+ * injected), and `now` is a seam, so the whole thing is unit-testable —
60
+ * including the bypass path (a renderer asking for workers > 1 while free must
61
+ * be refused HERE, not merely hidden in the UI).
62
+ */
63
+
64
+ /** The free-tier fan-out ceiling: one worker per task, i.e. a plain turn. */
65
+ const FREE_MAX_WORKERS = 1;
66
+
67
+ /** Aegis1's paid tier. MIRROR of services/billing_service.py `PAID_PLANS`. */
68
+ const PAID_PLANS = Object.freeze(['pro']);
69
+
70
+ /**
71
+ * MIRROR of services/billing_service.py `LEGACY_PLAN_ALIASES`: every stored
72
+ * plan string that normalizes onto a tier. `starter` is free-equivalent by
73
+ * aegis1's own definition — reading it as paid here would hand the fan-out to
74
+ * the one account the server itself treats as free.
75
+ */
76
+ const LEGACY_PLAN_ALIASES = Object.freeze({
77
+ cloud: 'pro',
78
+ memory: 'pro',
79
+ s: 'pro',
80
+ heavy: 'pro',
81
+ team: 'pro',
82
+ starter: 'free',
83
+ });
84
+
85
+ /**
86
+ * The Pro value, in the words every surface repeats (Phase 3's PAID_PROMISE is
87
+ * the same claim). A refusal that only stated the limit ("max 1 worker") reads
88
+ * as a bug; naming what Pro buys is the whole point of the wall.
89
+ */
90
+ const PRO_VALUE =
91
+ 'Pro puts the drain in the cloud, so the job keeps running after you close the laptop';
92
+
93
+ /** Campaign id for this prompt (Phase 1's fixed ids; aegis1 keeps the slug). */
94
+ const CAMPAIGN = 'queue_cap';
95
+
96
+ /**
97
+ * Where a refusal sends someone. A single-quoted literal so
98
+ * desktop/test/renderer-attribution.test.mjs can see it, and on aegis1's
99
+ * `/go/` route rather than the raw /subscribe path: `/go/` owns utm_source and
100
+ * utm_medium and maps `s`/`c` onto them, and `c=queue_cap` is what makes this
101
+ * click attributable to the refusal that produced it. Appending utm_* here
102
+ * would be a silent zero (aegis1 go_short_link() documents it) — the route
103
+ * finds no `s`, files the click as 'direct', and the link still works.
104
+ */
105
+ const UPGRADE_URL = 'https://aegiscloud.org/go/upgrade?s=desktop&c=queue_cap';
106
+
107
+ /**
108
+ * The BALANCE wall (Phase 6). Aegis1's paywall is not a feature tier — it is
109
+ * the Token Bank running dry. `balance_micros` is a prepaid EUR balance
110
+ * (db.py), the operator credits it by hand, and aegis1 says the consequence
111
+ * out loud in app.py: "Pool-key users with token bank balance skip legacy
112
+ * credit checks." So the truthful trigger is balance == 0, and the money path
113
+ * that fixes it is a TOP-UP, not a plan checkout.
114
+ *
115
+ * Campaign is `topup_bank` — the id Phase 1 already reserved for
116
+ * "top-up / bank / balance surfaces" (desktop/renderer/app.js). Reusing it
117
+ * rather than minting a sixth id keeps the documented list in the plan and the
118
+ * code-level list in the renderer from drifting; a new id in one place and not
119
+ * the other is exactly the silent-zero failure this project keeps hitting.
120
+ */
121
+ const BALANCE_CAMPAIGN = 'topup_bank';
122
+
123
+ /** Where the balance wall sends someone: `/go/topup` (aegis1's `/go/<page>`
124
+ * route handles both pages), same `s=desktop` requirement as UPGRADE_URL. */
125
+ const BALANCE_URL = 'https://aegiscloud.org/go/topup?s=desktop&c=topup_bank';
126
+
127
+ /**
128
+ * HOST SEAM — the one thing that had to change for the terminal to reuse this
129
+ * module (Phase 7).
130
+ *
131
+ * This file is no longer desktop-only: `cli/src/autonomous.js` gates the SAME
132
+ * fan-out through the SAME decision, because the paid multiplier must not cost
133
+ * money in one host and be free in another. But the two hosts are not the same
134
+ * channel: a click from the terminal is a `cli` conversion and a click from the
135
+ * GUI is a `desktop` one, and aegis1 files whatever `s` it is given.
136
+ *
137
+ * The URLs above are literals (`s=desktop`), so a CLI refusal printing one
138
+ * would file every terminal click as a desktop one — silently, in the worst
139
+ * available way, since the link still works and the only thing it destroys is
140
+ * the number. That is the same failure `/go/` exists to prevent, so it gets the
141
+ * same treatment: the channel is a parameter, and `host` (NOT `source`, which
142
+ * already means "where this verdict came from" in the snapshot) is what
143
+ * selects it.
144
+ *
145
+ * `SIGNUP_SOURCES` mirrors aegis1's accepted set. An unknown host is not sent:
146
+ * it falls back to the desktop default rather than minting a source the server
147
+ * will file as 'direct' — a wrong datapoint is worse than a missing one.
148
+ */
149
+ const SIGNUP_SOURCES = Object.freeze(['desktop', 'cli', 'mcp']);
150
+ const DEFAULT_HOST = 'desktop';
151
+
152
+ /** aegis1's `/go/<page>` short form, for a DIFFERENT channel than the literals
153
+ * above. `page` is `upgrade` or `topup`; the wire names (utm_*) are never sent
154
+ * here — `/go/` reads `s`/`c` and re-emits them itself (signup.js documents the
155
+ * measured difference). */
156
+ function goUrl(page, campaign, host) {
157
+ const slug = String(host == null ? '' : host).trim().toLowerCase();
158
+ const s = SIGNUP_SOURCES.includes(slug) ? slug : DEFAULT_HOST;
159
+ return `https://aegiscloud.org/go/${String(page).trim().toLowerCase()}?s=${s}&c=${campaign}`;
160
+ }
161
+
162
+ /** The campaign-tagged prompt URL for one host: the same page and campaign as
163
+ * the literals, filed under `host`'s channel. */
164
+ function promptUrlFor(host) {
165
+ return {
166
+ upgrade: goUrl('upgrade', CAMPAIGN, host),
167
+ balance: goUrl('topup', BALANCE_CAMPAIGN, host),
168
+ };
169
+ }
170
+
171
+ /** How long a resolved snapshot is trusted before the next probe. The probe is
172
+ * one small POST; a minute is short enough that a fresh purchase unlocks the
173
+ * card on the next refresh and long enough that a drain never probes per task. */
174
+ const DEFAULT_TTL_MS = 60 * 1000;
175
+
176
+ /** Collapse any stored/alias plan string onto a tier, exactly as aegis1 does. */
177
+ function normalizePlan(plan) {
178
+ const raw = String(plan == null ? '' : plan).trim().toLowerCase();
179
+ if (!raw) return 'free';
180
+ if (PAID_PLANS.includes(raw)) return 'pro';
181
+ const aliased = LEGACY_PLAN_ALIASES[raw];
182
+ return aliased || 'free';
183
+ }
184
+
185
+ /** The sentence a user types to route a task to the drain — quoted verbatim in
186
+ * every refusal and in the CLI's promotion block, so the two hosts cannot
187
+ * drift into two different instructions. */
188
+ const ASK_EXAMPLE = 'Do X autonomously';
189
+
190
+ /** True only for a tier aegis1 itself would call paid. */
191
+ function isPaidPlan(plan) {
192
+ return normalizePlan(plan) === 'pro';
193
+ }
194
+
195
+ /**
196
+ * The refusal, as the sentence a user reads. Names the Pro value (the cloud
197
+ * drain surviving app close), not just the ceiling, and carries the campaign
198
+ * id in the link it is paired with (see `gateFanout`'s `upgradeUrl`).
199
+ */
200
+ function fanoutRefusal() {
201
+ return (
202
+ `Fan-out needs Pro: ${PRO_VALUE}. ` +
203
+ // The ask, in the message, as the sentence to write — the CLI prints the
204
+ // same two lines (`cli/src/autonomous.js`), so a user who meets this wall
205
+ // in either host reads one instruction, not two vocabularies. `autonomously`
206
+ // is the word the queue actually routes on (queue.js stores the inverse as
207
+ // `singlePass`), which is why the example quotes it verbatim instead of
208
+ // naming the feature.
209
+ `Write it in the message: "${ASK_EXAMPLE}". ` +
210
+ 'Unlock: Pro, or any Token Bank balance. ' +
211
+ 'Free keeps the local drain on your own key — one worker per task, while this window is open.'
212
+ );
213
+ }
214
+
215
+ /**
216
+ * The refusal when the account's BANK is empty rather than its plan being
217
+ * free. Still exactly one reason to pay (PRO_VALUE — Phase 3's rule: a refusal
218
+ * that pitches something else is a second, competing offer at the moment the
219
+ * first is declined), and it names the fix that actually exists: top the bank
220
+ * up. "Your AEGIS balance is empty." is already aegis1's own string for this
221
+ * state (translations.py), so the two surfaces say the same sentence.
222
+ */
223
+ function balanceRefusal() {
224
+ return (
225
+ 'Your AEGIS balance is empty — ' +
226
+ `${PRO_VALUE}. ` +
227
+ // Same ask as the plan wall, but the unlock line follows THIS wall: the
228
+ // bank is empty, so topping it up is the action that clears it. Naming only
229
+ // "upgrade to Pro" would send a user who already owns Pro (and simply spent
230
+ // the bank) to a checkout for a plan they have — the exact confusion this
231
+ // module exists to remove. Kept symmetric with `fanoutRefusal` otherwise.
232
+ `Write it in the message: "${ASK_EXAMPLE}". ` +
233
+ 'Unlock: top up the Token Bank, or upgrade to Pro. ' +
234
+ 'Local drains stay free: one worker per task, on your own key, while this window is open.'
235
+ );
236
+ }
237
+
238
+ /**
239
+ * The account's bank, from whatever shape the probe answered.
240
+ *
241
+ * aegis1's `/api/token-bank/balance` returns `balance_eur` (micros stay
242
+ * internal — its own docstring says so), and that value is ROUNDED to cents
243
+ * before it is sent. 0.004 EUR therefore arrives as 0 and reads as empty;
244
+ * that is the server's rounding, not this module's, and it is the safe
245
+ * direction for a wall (it charges nothing, it only withholds the multiplier).
246
+ *
247
+ * `balanceKnown: false` is the important state: a probe that did not report a
248
+ * balance has NOT proven the bank is funded, so it must not unlock anything.
249
+ * Fail closed, same as the plan signal.
250
+ *
251
+ * The returned keys are `balanceKnown` / `balanceMicros` — deliberately the
252
+ * SAME names `fromProbe` destructures, because these are spread straight into
253
+ * `classifyProbe`'s result (`...bal`). They were once `known` / `micros`, and
254
+ * the mismatch made every funded bank read as `undefined` → not banked, so the
255
+ * operator's lever silently did nothing. Keep these names in lockstep with the
256
+ * `...bal` spreads below; the test asserts the exact shape.
257
+ */
258
+ function balanceOf(body) {
259
+ if (!body || typeof body !== 'object') return { balanceKnown: false, balanceMicros: null };
260
+ let raw = null;
261
+ if (body.balance_micros != null) raw = Number(body.balance_micros);
262
+ else if (body.balance_eur != null) raw = Number(body.balance_eur) * 1_000_000;
263
+ if (raw == null || !Number.isFinite(raw)) return { balanceKnown: false, balanceMicros: null };
264
+ return { balanceKnown: true, balanceMicros: Math.trunc(raw) };
265
+ }
266
+
267
+ /**
268
+ * Coerce a probe's answer into the three states this module cares about.
269
+ *
270
+ * The probe resolves aegis1's `{ valid, plan }` for a good key. A missing key
271
+ * comes back as HTTP 400 `api_key required` (or resolves `valid: false`), which
272
+ * is not a failure — it is the definitive "this install is free". Everything
273
+ * else that did not produce a plan is `unreachable`, which also lands on the
274
+ * free boundary but is a different FACT and must stay distinguishable in the
275
+ * snapshot (a report that cannot tell "free" from "could not ask" is guessing).
276
+ */
277
+ function classifyProbe(result, error) {
278
+ if (error) {
279
+ const bal = balanceOf(error && error.data);
280
+ const status = error.status;
281
+ const data = (error && error.data) || {};
282
+ const code = String(data.error || data.code || '');
283
+ const message = String((error && error.message) || '');
284
+ if (status === 400 || status === 401 || /api_key required|invalid api key|unauthor/i.test(`${code} ${message}`)) {
285
+ return { source: 'no-key', plan: 'free', degraded: false, ...bal };
286
+ }
287
+ return { source: 'unreachable', plan: 'free', degraded: true, ...bal };
288
+ }
289
+ const body = result && typeof result === 'object' ? result : {};
290
+ const bal = balanceOf(body);
291
+ if (body.valid === false) return { source: 'no-key', plan: 'free', degraded: false, ...bal };
292
+ const stated = String(body.plan == null ? '' : body.plan).trim();
293
+ if (!stated) {
294
+ // A key that verified but carried no plan: aegis1's own default for such an
295
+ // account is `free` (the column default), and a missing field is not proof
296
+ // of payment — so this is the free boundary, marked as not proven.
297
+ return { source: 'no-plan-field', plan: 'free', degraded: true, ...bal };
298
+ }
299
+ // The server STATED a plan, so the verdict is proven — free or paid.
300
+ // `degraded` means "no real answer" (timeout, no plan field, no key); a stated
301
+ // `free` IS an answer. This was once `degraded: !known`, where `known` meant
302
+ // "is this a PAID plan" — so every honestly-free account was marked degraded,
303
+ // and every promotion path that requires `degraded === false` (the CLI's
304
+ // per-drain upsell, the desktop's refusal link) went silent. The gate then
305
+ // withheld the fan-out and never said how to pay for it: it charged nothing
306
+ // and converted nobody. Unknown plan strings still normalize to `free`, so the
307
+ // money direction stays fail-closed.
308
+ return { source: 'server-plan', plan: normalizePlan(stated), degraded: false, ...bal };
309
+ }
310
+
311
+ /**
312
+ * The gate. `probe` is injected (main.js passes the shared client's
313
+ * verifyApiKey; tests pass a stub), so this module never touches the network
314
+ * itself and every branch below is reachable in a unit test.
315
+ */
316
+ function createEntitlement({
317
+ probe,
318
+ now = Date.now,
319
+ ttlMs = DEFAULT_TTL_MS,
320
+ // The CHANNEL the prompts in this instance link to. 'desktop' by default so
321
+ // every existing caller is unchanged; `cli/src/entitlement.js` passes 'cli'.
322
+ host = DEFAULT_HOST,
323
+ } = {}) {
324
+ const urls = promptUrlFor(host);
325
+ // Start at the free boundary, not at Pro. Until a probe has answered, nothing
326
+ // has been paid for — and `current()` (the sync read the drain clamp uses) is
327
+ // never allowed to be optimistic.
328
+ let snapshot = Object.freeze({
329
+ pro: false,
330
+ entitled: false,
331
+ balanceKnown: false,
332
+ balanceMicros: null,
333
+ balanceZero: false,
334
+ wall: 'plan',
335
+ plan: 'free',
336
+ planRaw: null,
337
+ maxWorkers: FREE_MAX_WORKERS,
338
+ source: 'unresolved',
339
+ degraded: true,
340
+ checkedAt: null,
341
+ campaign: CAMPAIGN,
342
+ host: SIGNUP_SOURCES.includes(String(host).toLowerCase()) ? String(host).toLowerCase() : DEFAULT_HOST,
343
+ upgradeUrl: urls.upgrade,
344
+ refusal: null,
345
+ });
346
+ let inflight = null;
347
+
348
+ function fromProbe({ source, plan, degraded, planRaw, balanceKnown = false, balanceMicros = null }) {
349
+ const pro = isPaidPlan(plan);
350
+ const banked = balanceKnown && Number.isFinite(balanceMicros) && balanceMicros > 0;
351
+ // TWO independent ways to be paid for: a paid plan, or a funded bank. The
352
+ // operator controls the second by hand (aegis1 admin `add_funds`), which is
353
+ // the lever this wall is built around — nothing here grants, times out or
354
+ // auto-charges; it only reads the number the operator set.
355
+ const entitled = pro || banked;
356
+ // The bank was READABLE and EMPTY — the operator's own signal that this
357
+ // account is now paying, not the absence of a plan.
358
+ const balanceZero = balanceKnown && !banked;
359
+ // Which wall to print. Entitled accounts get none. An account whose bank we
360
+ // read and found empty gets the TOP-UP wall, because topping up is the
361
+ // action that actually clears it. Everything else — unknown balance, no
362
+ // key, unreachable probe — gets the PLAN wall: we have not proven the bank
363
+ // is the problem, and a top-up prompt we cannot justify is a dark pattern.
364
+ const wall = entitled ? null : (balanceZero ? 'balance' : 'plan');
365
+ return Object.freeze({
366
+ pro,
367
+ entitled,
368
+ balanceKnown: Boolean(balanceKnown),
369
+ balanceMicros: balanceKnown ? balanceMicros : null,
370
+ balanceZero,
371
+ wall,
372
+ plan: pro ? 'pro' : 'free',
373
+ planRaw: planRaw == null ? null : String(planRaw),
374
+ // A paid session has no ceiling of its own here: main.js still clamps the
375
+ // renderer's number to QUEUE_MAX_WORKERS, which stays the only upper bound.
376
+ maxWorkers: entitled ? null : FREE_MAX_WORKERS,
377
+ source,
378
+ // `degraded` means "this verdict was not proven by the server" — for a
379
+ // paid verdict that is impossible (a plan string or a funded bank is what
380
+ // proves it), so it only ever marks a free boundary we could not confirm.
381
+ degraded: Boolean(degraded),
382
+ checkedAt: now(),
383
+ campaign: wall === 'balance' ? BALANCE_CAMPAIGN : CAMPAIGN,
384
+ upgradeUrl: wall === 'balance' ? urls.balance : urls.upgrade,
385
+ refusal: entitled ? null : (wall === 'balance' ? balanceRefusal() : fanoutRefusal()),
386
+ });
387
+ }
388
+
389
+ /**
390
+ * Re-probe (or return the cached verdict while it is fresh). Never throws:
391
+ * a probe that fails IS an answer here (`unreachable` → free boundary).
392
+ */
393
+ async function refresh({ force = false } = {}) {
394
+ const fresh = snapshot.checkedAt != null && now() - snapshot.checkedAt < ttlMs;
395
+ if (fresh && !force) return snapshot;
396
+ if (inflight) return inflight;
397
+ inflight = (async () => {
398
+ if (typeof probe !== 'function') {
399
+ snapshot = fromProbe({ source: 'no-probe', plan: 'free', degraded: true });
400
+ return snapshot;
401
+ }
402
+ try {
403
+ const answer = await probe();
404
+ const c = classifyProbe(answer, null);
405
+ snapshot = fromProbe({ ...c, planRaw: answer && answer.plan });
406
+ } catch (err) {
407
+ const c = classifyProbe(null, err);
408
+ snapshot = fromProbe(c);
409
+ }
410
+ return snapshot;
411
+ })();
412
+ try {
413
+ return await inflight;
414
+ } finally {
415
+ inflight = null;
416
+ }
417
+ }
418
+
419
+ /** The cached verdict, synchronously. Never probes — this is the read the
420
+ * drain clamp makes on the hot path, and an optimistic answer would be a
421
+ * free fan-out. */
422
+ function current() {
423
+ return snapshot;
424
+ }
425
+
426
+ /**
427
+ * THE GATE. Decide what a renderer's enqueue payload may do.
428
+ *
429
+ * `workers` is the number the renderer asked for (`null` = "no pick"), and
430
+ * `fanout` is its explicit fan-me-out flag. Either one naming more than one
431
+ * worker is a fan-out request, and a fan-out request from a non-Pro session
432
+ * is REFUSED — not silently clamped, because the request came from a control
433
+ * that is supposed to mean something, and a silent downgrade reads as a bug
434
+ * while teaching the user nothing. (A fan-out already sitting in the queue
435
+ * file — the CLI, a hand-edited queue.jsonl — is the other case: that one is
436
+ * clamped to a single pass at drain time, see main.js's `canFanOut`.)
437
+ */
438
+ function gateFanout({ workers, fanout } = {}) {
439
+ const requested = Number.isInteger(workers) ? workers : null;
440
+ const wantsFanout = fanout === true || (requested != null && requested > FREE_MAX_WORKERS);
441
+ if (!wantsFanout) return { ok: true, workers: requested, fanout: Boolean(fanout) };
442
+ if (snapshot.entitled) return { ok: true, workers: requested, fanout: true };
443
+ return {
444
+ ok: false,
445
+ // The code names WHICH wall, because the two have different fixes: an
446
+ // empty bank is topped up, a free plan is upgraded. A caller that showed
447
+ // the same message for both would be sending half its users to the wrong
448
+ // checkout, which is the exact confusion this phase exists to remove.
449
+ code: snapshot.wall === 'balance' ? 'fanout_requires_balance' : 'fanout_requires_pro',
450
+ reason: snapshot.refusal || fanoutRefusal(),
451
+ campaign: snapshot.campaign,
452
+ upgradeUrl: snapshot.upgradeUrl,
453
+ wall: snapshot.wall,
454
+ pro: false,
455
+ entitled: false,
456
+ maxWorkers: FREE_MAX_WORKERS,
457
+ entitlement: snapshot,
458
+ };
459
+ }
460
+
461
+ return { refresh, current, gateFanout };
462
+ }
463
+
464
+ module.exports = {
465
+ createEntitlement,
466
+ normalizePlan,
467
+ isPaidPlan,
468
+ classifyProbe,
469
+ fanoutRefusal,
470
+ balanceRefusal,
471
+ ASK_EXAMPLE,
472
+ balanceOf,
473
+ FREE_MAX_WORKERS,
474
+ PAID_PLANS,
475
+ LEGACY_PLAN_ALIASES,
476
+ CAMPAIGN,
477
+ UPGRADE_URL,
478
+ BALANCE_CAMPAIGN,
479
+ BALANCE_URL,
480
+ PRO_VALUE,
481
+ DEFAULT_TTL_MS,
482
+ // Phase 7: the host seam + the builder the CLI binds itself to.
483
+ SIGNUP_SOURCES,
484
+ DEFAULT_HOST,
485
+ goUrl,
486
+ promptUrlFor,
487
+ };
@@ -85,6 +85,13 @@ const MEMORY_PERSIST_NAMESPACE = '__memoryPersist';
85
85
  * shown, and motion follows the OS `prefers-reduced-motion` setting. */
86
86
  const AVATAR_NAMESPACE = '__avatar';
87
87
 
88
+ /** Reserved namespace for the funnel-instrumentation opt-in: `{ enabled }` —
89
+ * app-level, not a provider. DEFAULT OFF (an absent namespace means nothing is
90
+ * recorded), which is the opposite of every other preference in this file and
91
+ * is the whole point: telemetry is opt-in, not opt-out. Read by
92
+ * main.js telemetryEnabled() through getTelemetryOptIn(). */
93
+ const TELEMETRY_NAMESPACE = '__telemetry';
94
+
88
95
  /** Namespaces the provider-config surface must never see or mutate. */
89
96
  const RESERVED_NAMESPACES = Object.freeze([
90
97
  AEGIS_KEY_NAMESPACE,
@@ -93,6 +100,7 @@ const RESERVED_NAMESPACES = Object.freeze([
93
100
  CONFIRM_MODE_NAMESPACE,
94
101
  MEMORY_PERSIST_NAMESPACE,
95
102
  AVATAR_NAMESPACE,
103
+ TELEMETRY_NAMESPACE,
96
104
  ]);
97
105
 
98
106
  /** Motion modes the renderer understands (`system` = follow the OS). */
@@ -344,6 +352,28 @@ function createSettingsStore({ dir, safeStorage } = {}) {
344
352
  return getConfirmMode();
345
353
  }
346
354
 
355
+ // --- Telemetry: reserved namespace, plain preference, DEFAULT OFF --------
356
+ // The opt-in flag for the funnel instrumentation (Phase 2 of
357
+ // docs/upgrade-conversion-plan.md; the store itself is
358
+ // lib/local/telemetry.js). Unlike confirm mode, the absent case is FALSE:
359
+ // nothing is recorded until someone says so, either here or through
360
+ // `AEGIS_TELEMETRY=1` (main.js telemetryEnabled() reads both, env first).
361
+ // The flag only says "may this install record its own two prompt events to
362
+ // its own userData"; the records stay anonymous either way — see the header
363
+ // of lib/local/telemetry.js for what a record may contain.
364
+
365
+ function getTelemetryOptIn() {
366
+ const cfg = load()[TELEMETRY_NAMESPACE] || {};
367
+ return cfg.enabled === true;
368
+ }
369
+
370
+ function setTelemetryOptIn(enabled) {
371
+ const data = load();
372
+ data[TELEMETRY_NAMESPACE] = { enabled: Boolean(enabled) };
373
+ save(data);
374
+ return getTelemetryOptIn();
375
+ }
376
+
347
377
  // --- Persisting memory: reserved namespace, plain preference -------------
348
378
  // The desktop's half of "persisting memory for every account": whether a
349
379
  // finished turn is pushed to cloud memory automatically. ON when unset —
@@ -438,6 +468,8 @@ function createSettingsStore({ dir, safeStorage } = {}) {
438
468
  setQuickLauncherConfig,
439
469
  getConfirmMode,
440
470
  setConfirmMode,
471
+ getTelemetryOptIn,
472
+ setTelemetryOptIn,
441
473
  getMemoryPersist,
442
474
  memoryPersistState,
443
475
  setMemoryPersist,
@@ -455,6 +487,7 @@ module.exports = {
455
487
  CONFIRM_MODE_NAMESPACE,
456
488
  MEMORY_PERSIST_NAMESPACE,
457
489
  AVATAR_NAMESPACE,
490
+ TELEMETRY_NAMESPACE,
458
491
  AVATAR_MOTION_MODES,
459
492
  DEFAULT_QUICK_LAUNCHER_SHORTCUT,
460
493
  RESERVED_NAMESPACES,
@@ -37,6 +37,14 @@ function createTools(client) {
37
37
  // other module state.
38
38
  const aegis = client;
39
39
 
40
+ // Attribution for money prompts. A stub client (tests pass one) may not carry
41
+ // `promptUrl`, and a throw here would kill the tool body mid-message — so the
42
+ // guard degrades to an untagged link rather than to no link at all.
43
+ const promptUrl = (page, campaign) =>
44
+ typeof aegis.promptUrl === 'function'
45
+ ? aegis.promptUrl(page, campaign)
46
+ : `https://aegiscloud.org/go/${page}`;
47
+
40
48
  const TOOLS = {
41
49
  aegis_status: {
42
50
  description:
@@ -161,7 +169,7 @@ function createTools(client) {
161
169
  if ((data.balance_eur || 0) <= 0) {
162
170
  lines.push(
163
171
  '',
164
- 'Balance is empty — top up at https://aegiscloud.org/subscribe, or set your own ' +
172
+ `Balance is empty — top up at ${promptUrl('topup', 'topup_bank')}, or set your own ` +
165
173
  'provider key with aegis_byok_set to use aegis_ask for free at cost.'
166
174
  );
167
175
  }