aegiscode 6.8.5 → 6.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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,
@@ -13,6 +13,7 @@
13
13
 
14
14
  const { createClient } = require('../client/aegis.js');
15
15
  const credentials = require('../client/credentials.js');
16
+ const { autoProvisionApiKey } = require('../client/auto-provision.js');
16
17
  const { createTools } = require('./tools.js');
17
18
 
18
19
  // `~/.aegiscode/.env` read into process.env once, before anything resolves a
@@ -46,7 +47,6 @@ const aegis = createClient(credentials.clientOptions());
46
47
  // (cli/) so the two hosts cannot drift apart. This file owns the JSON-RPC
47
48
  // plumbing and nothing else.
48
49
  const { TOOLS, toolList } = createTools(aegis);
49
- const API_KEY = aegis.apiKey;
50
50
  const API_BASE = aegis.apiBase;
51
51
  const SERVER_NAME = 'aegis';
52
52
  // Keep in sync with .claude-plugin/plugin.json "version".
@@ -67,6 +67,36 @@ function missingKeyText() {
67
67
  ].join('\n');
68
68
  }
69
69
 
70
+ // A tool call with no key configured anywhere gets ONE auto-provision attempt
71
+ // per process, not one per call: `register-device` is rate-limited server-side
72
+ // at 5/hour/IP, and a session that fires several tool calls before the user
73
+ // notices the failure message must not burn through that budget on retries
74
+ // that would fail the same way. Success or failure, this only ever runs once.
75
+ // The provisioning itself (endpoint, fingerprint, timeout) is shared with the
76
+ // desktop app and the CLI — see client/auto-provision.js.
77
+ let provisionAttempted = false;
78
+ async function ensureApiKey() {
79
+ if (aegis.apiKey || provisionAttempted) return;
80
+ provisionAttempted = true;
81
+ const result = await autoProvisionApiKey(aegis, credentials);
82
+ if (result.error) {
83
+ process.stderr.write(`aegis: device auto-registration failed (${result.error.message}) — falling back to manual setup.\n`);
84
+ return;
85
+ }
86
+ if (!result.key) {
87
+ process.stderr.write('aegis: device auto-registration returned no usable key — falling back to manual setup.\n');
88
+ return;
89
+ }
90
+ // Starts at zero token-bank balance by design (see registerDevice()'s doc in
91
+ // client/aegis.js) — this grants an account, not free inference, so the
92
+ // very next call still 402s until the account is funded.
93
+ process.stderr.write(
94
+ 'aegis: no API key was configured — auto-provisioned a free AEGIS account' +
95
+ (result.ok ? ` (key saved to ${credentials.keyStatus().path}).\n` : ' (could not save it — see above).\n') +
96
+ `Fund it at ${aegis.promptUrl('topup', 'device_autoprovision')} or set your own BYOK key with aegis_byok_set.\n`
97
+ );
98
+ }
99
+
70
100
  // ---------------------------------------------------------------------------
71
101
  // JSON-RPC / MCP plumbing
72
102
  // ---------------------------------------------------------------------------
@@ -126,7 +156,8 @@ async function handleMessage(msg) {
126
156
  });
127
157
  return;
128
158
  }
129
- if (!API_KEY) {
159
+ if (!aegis.apiKey) await ensureApiKey();
160
+ if (!aegis.apiKey) {
130
161
  reply(id, {
131
162
  content: [{ type: 'text', text: missingKeyText() }],
132
163
  isError: true,
@@ -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
  }