aegiscode 6.8.12 → 6.8.14

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/bin/aegiscode.js CHANGED
@@ -61,6 +61,17 @@ Attestation (φ(α) — a sealed record of what a session was):
61
61
  aegiscode fingerprint vault --audit what is in the vault, and is a key in it
62
62
  aegiscode fingerprint help all subcommands and their flags
63
63
 
64
+ Code protection (the agent-key gate on aegiscodex-dev / aegiscode-plugin):
65
+ aegiscode gate status can THIS machine edit a gated tree?
66
+ aegiscode gate import-key [PATH] adopt a key dropped at PATH
67
+ (default ~/Downloads/agent.key),
68
+ then delete PATH
69
+ aegiscode gate bind-machine trust this machine in the manifest
70
+ aegiscode gate rotate mint a fresh key, burn the old one
71
+ aegiscode gate add-key add another key (from stdin)
72
+ aegiscode gate lock-status the server-side half of the lock
73
+ aegiscode gate help all subcommands and their flags
74
+
64
75
  Options:
65
76
  -m, --model <id> pin a model id (see /models; default: server choice)
66
77
  --base <url> API base (default $AEGIS_API_BASE or aegiscloud.org)
@@ -164,6 +175,17 @@ function parseArgs(argv) {
164
175
  opts.commandArg = sub;
165
176
  opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
166
177
  argv = [];
178
+ } else if (head === 'gate') {
179
+ // Same position-0 rule and the same reason as `fingerprint`/`mcp`: the
180
+ // tail belongs to the subcommand (`--cwd`, `--paths a b c`, `--keep` are
181
+ // agent-gate.mjs's flags, not this parser's), so it is handed over
182
+ // verbatim. A bare `gate` is the status report — "can this machine edit
183
+ // here?" — not a prompt.
184
+ const sub = argv[1] && !argv[1].startsWith('-') ? argv[1] : 'status';
185
+ opts.command = 'gate';
186
+ opts.commandArg = sub;
187
+ opts.commandArgv = argv.slice(argv[1] && !argv[1].startsWith('-') ? 2 : 1);
188
+ argv = [];
167
189
  }
168
190
 
169
191
  for (let i = 0; i < argv.length; i++) {
@@ -493,6 +515,16 @@ async function main(argv = process.argv.slice(2)) {
493
515
  });
494
516
  }
495
517
 
518
+ // The agent-key gate on aegiscodex-dev / aegiscode-plugin. Dispatched here,
519
+ // before a session is built, for the same reason `fingerprint` is: it is a
520
+ // one-shot administrative question ("can this machine edit that tree?"),
521
+ // not a prompt, and it must work with no terminal at all (a fresh npm
522
+ // install with no git clone is exactly the case this exists for).
523
+ if (opts.command === 'gate') {
524
+ const { runGate } = require('../src/gate.js');
525
+ return runGate(opts.commandArg || 'status', opts.commandArgv || []);
526
+ }
527
+
496
528
  if (ACCOUNT_COMMANDS.has(opts.command)) {
497
529
  return runAccountCommand(opts.command, opts.commandArg, {
498
530
  json: opts.json,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.12",
4
+ "version": "6.8.14",
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",
@@ -24,7 +24,7 @@
24
24
 
25
25
  import fs from 'node:fs';
26
26
  import path from 'node:path';
27
- import { fileURLToPath } from 'node:url';
27
+ import { fileURLToPath, pathToFileURL } from 'node:url';
28
28
  import { createRequire } from 'node:module';
29
29
 
30
30
  const require = createRequire(import.meta.url);
@@ -189,6 +189,14 @@ const FILES = [
189
189
  // The decode command and the CC0 notice, shipped beside the artifact so a
190
190
  // reader who finds the seal in an installed package can reverse it.
191
191
  'covenant/README.md',
192
+ // The agent-key gate CLI (status/check/init/bind-machine/import-key/rotate/
193
+ // add-key/lock-status). Resolved lazily by src/gate.js through
194
+ // resolveShared() rather than eagerly by deps.js, since it is an ES module
195
+ // (import/export) loaded via dynamic import(), not require(); a package
196
+ // built without it fails only the gate subcommand, at the point someone runs
197
+ // it, not at CLI load. Staged under vendor/tools so a checkout and a
198
+ // published package resolve the same repo-relative path.
199
+ 'tools/agent-gate.mjs',
192
200
  ];
193
201
 
194
202
  function main() {
@@ -310,3 +318,16 @@ function main() {
310
318
  }
311
319
 
312
320
  main();
321
+
322
+ // The gate module is an ES module (import/export), loaded by src/gate.js via
323
+ // dynamic import() rather than require() — so this check is async and runs
324
+ // after main()'s synchronous staging, and a broken staged copy must fail
325
+ // predist here, not wait for the first `aegiscode gate` invocation someone
326
+ // runs after publish.
327
+ const gateStagedPath = path.join(VENDOR, 'tools', 'agent-gate.mjs');
328
+ const gateMod = await import(pathToFileURL(gateStagedPath).href);
329
+ if (typeof gateMod.run !== 'function') {
330
+ console.error('predist: staged tools/agent-gate.mjs exposes no run()');
331
+ process.exit(1);
332
+ }
333
+ console.log('predist: staged tools/agent-gate.mjs loads standalone and exposes run()');
package/src/app.js CHANGED
@@ -685,10 +685,7 @@ function createApp(options = {}) {
685
685
  */
686
686
  function emit(lines) {
687
687
  const block = typeof lines === 'string' ? [lines] : lines;
688
- for (const l of block) {
689
- if (capture) capture.push(l);
690
- else out.write(l + '\n');
691
- }
688
+ for (const l of block) out.write(l + '\n');
692
689
  }
693
690
 
694
691
  // --- the ask path ---------------------------------------------------------
@@ -1246,19 +1243,6 @@ function createApp(options = {}) {
1246
1243
  // The one spelling of a provider's settings row, shared with the engine
1247
1244
  // that reads it (`byok:<provider>`) — see engine.js byokNamespace.
1248
1245
  byokNamespace: (p) => byokNamespace(p),
1249
- // Whether a provider key is already on this machine — read through the
1250
- // same `byok:<provider>` rows /byok-key writes, so the model picker's
1251
- // "does this row need a key?" answer cannot disagree with the store that
1252
- // would supply it. Never throws: an injected engine may carry no store.
1253
- hasProviderKey: (p) => {
1254
- const store = engine.settings || null;
1255
- if (!store || !p || typeof store.rawKey !== 'function') return false;
1256
- try { return !!store.rawKey(byokNamespace(p)); } catch { return false; }
1257
- },
1258
- // And whether the ACCOUNT key resolves anywhere (env → credentials.json).
1259
- // A pooled row needs that key, not a provider one, and prompting for a
1260
- // key the machine demonstrably holds is the bug this prevents.
1261
- accountConfigured: () => !!credentials.keyStatus().configured,
1262
1246
  // The class surface: /class switches, /models lists for whichever class
1263
1247
  // is live (the frozen state carries the current one as c.ctx.modelClass).
1264
1248
  listModelsFor: (cls) => listModelsFor(cls),
@@ -1468,20 +1452,9 @@ function createApp(options = {}) {
1468
1452
  async function runOnce(prompt, { json = false } = {}) {
1469
1453
  adoptLegacyKeyOnce();
1470
1454
  if (!client.apiKey) {
1471
- err.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV}.\n`);
1455
+ err.write(`aegiscode: no AEGIS account key. ${credentials.HOW_TO_SET}, or set $${credentials.KEY_ENV}.\n`);
1472
1456
  return 2;
1473
1457
  }
1474
- // A leading `/` is a LOCAL command at every other entry point (the chatflow
1475
- // dispatches it, the linear REPL dispatches it), so it must be one here too.
1476
- // This path used to skip the dispatcher entirely and hand `"/cost"` to the
1477
- // model as ordinary user text: the request went out as a chat completion, and
1478
- // the pool — which has no answer for a bare slash command — opened an
1479
- // event-stream and sent nothing, so the turn died on the client's 60s idle
1480
- // watchdog with "stream stalled". Every documented non-interactive use of a
1481
- // command (`aegiscode -p "/cost"`, `--json -p "/models"`) was affected, and
1482
- // the failure was indistinguishable from a server outage.
1483
- const parsed = parseLine(prompt);
1484
- if (parsed.kind !== 'prompt') return runOnceCommand(prompt, parsed, { json });
1485
1458
  // Snapshot the account's existing ledger BEFORE the billed call. Without
1486
1459
  // this the refresh after the turn would treat every historical row as new,
1487
1460
  // and the reported charge would be whatever the account spent last rather
@@ -1520,64 +1493,6 @@ function createApp(options = {}) {
1520
1493
  return res.interrupted ? 130 : 0;
1521
1494
  }
1522
1495
 
1523
- /**
1524
- * The one-shot variant of `handleLine`: run a local command and print what it
1525
- * produced. Returns the process exit code.
1526
- *
1527
- * The commands are dispatched through the SAME `handleLine` the interactive
1528
- * loop uses — not a second implementation — so `/cost`, `/models` and friends
1529
- * cannot answer differently depending on whether a human was watching. What
1530
- * this adds over the interactive path is only the two things a non-interactive
1531
- * caller has that the loop does not: an exit code, and, under `--json`, a
1532
- * machine-readable envelope around the command's own output.
1533
- *
1534
- * Preferences are restored first. The interactive entry point calls
1535
- * `restorePrefs()` on startup and this one never did, so a command run through
1536
- * `-p` would have read a context that ignored the config on disk — `/model`
1537
- * with no pin, for instance, would not have seen the model the user pinned.
1538
- */
1539
- async function runOnceCommand(line, parsed, { json }) {
1540
- if (parsed.kind === 'empty') return 0;
1541
- if (parsed.kind === 'unknown') {
1542
- // Straight to stderr, and non-zero: an unknown command is a caller bug, and
1543
- // `-p` is the entry point scripts use. Going through `emit` would put the
1544
- // diagnostic on stdout where a `$(...)` capture would swallow it, and
1545
- // exiting 0 would make a typo look like a success.
1546
- const alt = nearest(parsed.name);
1547
- err.write(`aegiscode: unknown command: /${parsed.name}${alt ? ` — did you mean /${alt}?` : ''}\n`);
1548
- return 2;
1549
- }
1550
- restorePrefs();
1551
- await refreshSpend();
1552
- const lines = json ? [] : null;
1553
- if (lines) capture = lines;
1554
- let keep = true;
1555
- try {
1556
- keep = await handleLine(line);
1557
- } finally {
1558
- capture = null;
1559
- }
1560
- if (json) {
1561
- out.write(
1562
- JSON.stringify(
1563
- {
1564
- command: parsed.kind === 'command' ? '/' + parsed.command.name : line,
1565
- arg: parsed.arg || '',
1566
- // `handleLine` returns false when the command asked to end the
1567
- // session (`/quit`, `/exit`); in one-shot that simply means the
1568
- // command ran and there is nothing further to do.
1569
- ended: keep === false,
1570
- output: lines,
1571
- balance_eur: session.balance,
1572
- },
1573
- null,
1574
- 2
1575
- ) + '\n'
1576
- );
1577
- }
1578
- return 0;
1579
- }
1580
-
1581
1496
  /** Fold one completed turn's usage into the session tallies.
1582
1497
  * @returns {number|null} the total token count for the turn, when known. */
1583
1498
  function recordTurn(res) {
@@ -1964,7 +1879,14 @@ function createApp(options = {}) {
1964
1879
  // byte that was not the answer is handed back to the key pump's own queue
1965
1880
  // rather than to the stream: `events.feedKeys` delivers it exactly as a
1966
1881
  // `data` event would have, including after stdin has ended.
1967
- await probeTerminalBackground({ onLeftover: (text) => events.feedKeys(text) });
1882
+ // `keystrokes: true` matters. The probe hands back a whole burst, and a
1883
+ // command issued at launch (`/exit\r`) arrives as one string containing a
1884
+ // newline — which the paste heuristic would otherwise collapse into a
1885
+ // single paste key, losing the Enter and parking the session loop forever
1886
+ // at the welcome screen. See `events.feedKeys`.
1887
+ await probeTerminalBackground({
1888
+ onLeftover: (text) => events.feedKeys(text, { keystrokes: true }),
1889
+ });
1968
1890
  restorePrefs();
1969
1891
  themeNoticeFirstRun();
1970
1892
  adoptLegacyKeyOnce();
package/src/caps.js CHANGED
@@ -380,13 +380,20 @@ function probeBackground({ stdin = process.stdin, stdout = process.stdout, timeo
380
380
  if (settled) return;
381
381
  settled = true;
382
382
  if (timer) clearTimeout(timer);
383
+ // Pause BEFORE dropping the listener. In flowing mode a chunk emitted
384
+ // between `removeListener` and `pause` has no subscriber and is silently
385
+ // discarded — and that gap is a real window, not a theoretical one: with
386
+ // the probe on, 1 run in 10 lost the command typed at launch and hung at
387
+ // the fully-drawn welcome screen (9120 bytes, no exit). Pausing first
388
+ // stops the flow and leaves any in-flight bytes in the readable buffer,
389
+ // where the session pump's `resume()` collects them.
390
+ stdin.pause();
383
391
  stdin.removeListener('data', onData);
384
392
  try {
385
393
  if (!wasRaw) stdin.setRawMode(false);
386
394
  } catch {
387
395
  /* the terminal closed under us; the read end is already gone */
388
396
  }
389
- stdin.pause();
390
397
  if (leftover) {
391
398
  // Bytes that were not the answer belong to the session, not to us.
392
399
  // `onLeftover` routes them back through the caller's key queue, which
package/src/commands.js CHANGED
@@ -69,6 +69,7 @@ const cloudsync = require('./cloudsync.js');
69
69
  const { maskKey, fmtTokens } = require('./format.js');
70
70
  const { pickerEntries } = require('./models.js');
71
71
  const { resolveShared } = require('./sharedpaths.js');
72
+ const { createCliEntitlement, paymentView, probeFee } = require('./entitlement.js');
72
73
  const { openUrl, URLS } = require('./system.js');
73
74
  const { sniffProject, buildAegisMd } = require('./init.js');
74
75
  const { upgradeAdvice, latestPublishedVersion } = require('./update.js');
@@ -220,6 +221,56 @@ async function runMultiCommand(c, task, { yolo = false, title = 'ÆGIS Multi' }
220
221
  /** /upgrade's advice as panel rows (the advice itself is plain strings). */
221
222
  const upgradePanelLines = (lines) => lines.map((l) => [span(C.white, l)]);
222
223
 
224
+ /**
225
+ * The paid prompt `/billing` prints, or `undefined` when it cannot be earned.
226
+ *
227
+ * WHY THIS EXISTS AS A FUNCTION. `/billing` is the one screen a user opens when
228
+ * they are already thinking about money, and it was the only money surface in
229
+ * this client that did not ask the account anything: it printed the ledger and
230
+ * the line "AEGIS has no subscription of its own". Both are now answered from
231
+ * the SAME decision the drain clamps on (`desktop/lib/local/entitlement.js`,
232
+ * reached through `cli/src/entitlement.js` with `host: 'cli'`), so the terminal
233
+ * cannot sell a plan the drain would refuse, or refuse a fan-out to a bank the
234
+ * panel just called funded.
235
+ *
236
+ * `force` on the refresh, deliberately: the gate's snapshot is a 60 s cache
237
+ * built for a drain that must not probe per task, but `/billing` is an explicit
238
+ * ask — "what do I owe" answered from a minute-old read is the wrong answer at
239
+ * exactly the moment it is being asked. One probe per `/billing`, not per task.
240
+ *
241
+ * Returns undefined rather than a guess when the gate cannot be built at all
242
+ * (no client, no shared module). The panel then prints its neutral top-up row.
243
+ * The failure direction matters: inventing a wall for an account we could not
244
+ * read is the one error here that costs real money — either selling Pro to
245
+ * someone who has it or telling a funded user their bank is empty.
246
+ */
247
+ async function billingPayment(c) {
248
+ if (!c || !c.client) return undefined;
249
+ let gate;
250
+ try {
251
+ gate = createCliEntitlement({ aegis: c.client });
252
+ } catch {
253
+ return undefined;
254
+ }
255
+ // Through the spinner when the host has one: this is a network read, and an
256
+ // unannounced two-second pause after `/billing` reads as a hang.
257
+ const run = c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
258
+ try {
259
+ await run(() => gate.refresh({ force: true }));
260
+ } catch {
261
+ // `refresh()` is contractually non-throwing, but a broken host could still
262
+ // reject; the cached (or boot) snapshot is a real read and still usable.
263
+ }
264
+ // The relay's handling fee, published by the same server the probe just
265
+ // talked to. Fetched here rather than in the panel because the panel is pure
266
+ // (and tested as such), and fetched WITHOUT `force`: a minute-old price is
267
+ // still the price, unlike a minute-old entitlement verdict, and this keeps
268
+ // `/billing` at one probe plus one cheap GET rather than two round trips to
269
+ // the same host.
270
+ const fee = await probeFee();
271
+ return paymentView(gate.current(), { host: 'cli', fee });
272
+ }
273
+
223
274
  /**
224
275
  * The pinnable-model list for the class the session is on, fetched fresh.
225
276
  *
@@ -1957,6 +2008,18 @@ const COMMANDS = [
1957
2008
  panel(c, panels.buildBilling({
1958
2009
  ...st,
1959
2010
  balance: spend && spend.balance != null ? spend.balance : st.balance,
2011
+ // The paid prompt, from the SAME gate that decides the fan-out. This is
2012
+ // the whole reason `/billing` can be trusted to say what Pro costs: the
2013
+ // verdict and the ceiling come from one decision (`is_pro` mirrored by
2014
+ // the shared module) instead of a second, panel-local guess about the
2015
+ // account — two readings is how a screen ends up selling Pro to someone
2016
+ // who owns it, or telling a paying customer their bank is empty.
2017
+ //
2018
+ // A probe that cannot be built (no shared module, no client) leaves the
2019
+ // field unset: the panel then prints its plain top-up row rather than an
2020
+ // unverified pitch. Never the reverse — a failure here must not invent
2021
+ // a wall.
2022
+ payment: await billingPayment(c),
1960
2023
  }, c.ctx));
1961
2024
  c.render();
1962
2025
  return true;
@@ -105,4 +105,210 @@ function createCliEntitlement({ aegis, now, ttlMs } = {}) {
105
105
  });
106
106
  }
107
107
 
108
- module.exports = { createCliEntitlement, buildProbe, loadModule };
108
+ // ── the payment surface ─────────────────────────────────────────────────────
109
+
110
+ /**
111
+ * The copy every paid prompt in this host prints, read from the SHARED module
112
+ * when it resolves and from a frozen literal when it does not.
113
+ *
114
+ * Why a fallback at all: `loadModule()` requires a file that exists in a source
115
+ * checkout and in the `predist` staging tree, but the CLI also ships as an npm
116
+ * tarball where the shared modules live under `vendor/` — and a `/billing`
117
+ * panel that threw on a lookup would take the whole command down rather than
118
+ * show a user the one screen that can take their money. The literals below are
119
+ * therefore a COPY of the shared constants, and `test/cli-billing-payment.test.mjs`
120
+ * asserts copy === shared module so the copy cannot drift silently; if the
121
+ * shared module resolves, its strings win and the literal is never printed.
122
+ */
123
+ const FALLBACK_COPY = Object.freeze({
124
+ paidReason: 'Pro puts the drain in the cloud, so the job keeps running after you close the laptop',
125
+ honesty:
126
+ 'Everything on your machine is free, permanently. The cloud drain is what you pay for.',
127
+ ask: 'Do X autonomously',
128
+ });
129
+
130
+ /** The two walls, and the campaign id each one owns. Same ids the plan fixed
131
+ * (`status_card` for "an account prompt on a status/billing surface",
132
+ * `topup_bank` for the bank running dry) and the same ones aegis1 accepts. */
133
+ const BILLING_WALL = Object.freeze({ campaign: 'status_card', page: 'upgrade' });
134
+ const BALANCE_WALL = Object.freeze({ campaign: 'topup_bank', page: 'topup' });
135
+
136
+ /**
137
+ * The shared module, or undefined — resolved once and remembered, because
138
+ * `/billing` is a hot path for a user staring at a wall and a filesystem probe
139
+ * per panel render buys nothing. A `require` that throws is cached as
140
+ * undefined; the literals above are the answer from then on.
141
+ */
142
+ let sharedCache;
143
+ function shared() {
144
+ if (sharedCache !== undefined) return sharedCache || undefined;
145
+ try {
146
+ sharedCache = loadModule();
147
+ } catch {
148
+ sharedCache = null;
149
+ }
150
+ return sharedCache || undefined;
151
+ }
152
+
153
+ /** The sentences a paid prompt prints, shared-first. */
154
+ function paymentCopy() {
155
+ const mod = shared();
156
+ return {
157
+ paidReason: str(mod && mod.PRO_VALUE, FALLBACK_COPY.paidReason),
158
+ honesty: str(mod && mod.FREE_HONESTY, FALLBACK_COPY.honesty),
159
+ ask: str(mod && mod.ASK_EXAMPLE, FALLBACK_COPY.ask),
160
+ };
161
+ }
162
+
163
+ function str(v, fallback) {
164
+ const s = v == null ? '' : String(v);
165
+ return s.trim() ? s : fallback;
166
+ }
167
+
168
+ /**
169
+ * The campaign-tagged link a wall sends someone to. Built here rather than in
170
+ * `panels.js` so the channel is `s=cli` by construction: the shared module's
171
+ * own URL literals hardcode `s=desktop` (they predate the host seam), and
172
+ * printing one from a terminal would file every terminal click as a desktop
173
+ * conversion — the silent zero `/go/` exists to prevent.
174
+ *
175
+ * `goUrl` is preferred when the shared module resolves (one implementation, and
176
+ * it validates the channel against aegis1's accepted set); the fallback spells
177
+ * the same URL for hosts that cannot resolve it.
178
+ */
179
+ function paymentUrl(wall) {
180
+ const mod = shared();
181
+ if (mod && typeof mod.goUrl === 'function') {
182
+ try {
183
+ return mod.goUrl(wall.page, wall.campaign, 'cli');
184
+ } catch {
185
+ // Fall through to the literal below — a link is better than a throw.
186
+ }
187
+ }
188
+ return `https://aegiscloud.org/go/${wall.page}?s=cli&c=${wall.campaign}`;
189
+ }
190
+
191
+ /**
192
+ * The payment view for a surface that is allowed to ask: plain data, formatted
193
+ * by `panels.buildBilling` which stays pure (it renders what it is handed and
194
+ * never probes).
195
+ *
196
+ * `snapshot` is the shared gate's `current()`. The verdict is read through the
197
+ * MODULE's own rules — `entitled` is `pro || banked` — so this host cannot
198
+ * arrive at a different answer than the drain does about who owes money. The
199
+ * only branch taken here is which WALL the user is in front of, and that is the
200
+ * module's own `wall` field:
201
+ *
202
+ * entitled → the offer is already owned; state it, ask nothing
203
+ * wall === 'balance' → the bank ran dry: top up (campaign `topup_bank`)
204
+ * anything else / free → Pro (campaign `status_card`)
205
+ *
206
+ * `degraded` (no real answer: timeout, no key, unreadable body) still renders
207
+ * the offer — the panel is allowed to sell — but it is reported as `verified:
208
+ * false` so the caller can say the verdict was not confirmed rather than
209
+ * presenting a timeout as a fact about the account.
210
+ */
211
+ /**
212
+ * The BYOK handling fee, as the TERMINAL renders it.
213
+ *
214
+ * Formatting only — the words and the numbers both come from one place: the
215
+ * rate is aegis1's published payload (never a literal here, or the two hosts
216
+ * drift from the ledger), and the sentence is the shared module's
217
+ * `byokFeeLine`, so the GUI and the terminal cannot describe the relay's price
218
+ * differently. `line === ''` means "no published fee" and every caller must
219
+ * then say nothing at all rather than guess.
220
+ */
221
+ function feeView(fee) {
222
+ const f = fee && typeof fee === 'object' ? fee : null;
223
+ let line = '';
224
+ try {
225
+ const mod = loadModule();
226
+ if (typeof mod.byokFeeLine === 'function') line = String(mod.byokFeeLine(f) || '');
227
+ } catch {
228
+ // No shared module (staged tree without the host payload): silence, which
229
+ // is the honest reading of "this host cannot price the lane right now".
230
+ line = '';
231
+ }
232
+ return {
233
+ line,
234
+ published: line !== '',
235
+ // Enforcement, not price. A host that knows the relay demands an account
236
+ // can say so before the user meets the 402 instead of after.
237
+ accountRequired: !!(f && f.require_account === true),
238
+ anonymousDailyCalls: f && Number.isFinite(Number(f.anonymous_daily_calls))
239
+ ? Number(f.anonymous_daily_calls) : 0,
240
+ gateMode: f && typeof f.gate_mode === 'string' ? f.gate_mode : '',
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Fetch the server's published BYOK fee. Non-throwing, and offline it returns
246
+ * null — the fee is disclosure, not a gate, so a failed read must not turn
247
+ * `/billing` into an error the user has to interpret.
248
+ */
249
+ async function probeFee() {
250
+ try {
251
+ const client = loadClient();
252
+ if (!client || typeof client.byokProviders !== 'function') return null;
253
+ const data = await client.byokProviders();
254
+ return (data && data.fee) || null;
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+
260
+ function paymentView(snapshot, { host = 'cli', fee = null } = {}) {
261
+ const copy = paymentCopy();
262
+ const snap = snapshot && typeof snapshot === 'object' ? snapshot : {};
263
+ const entitled = snap.entitled === true;
264
+ const feeLine = feeView(fee).line;
265
+ const wall = entitled ? 'owned' : snap.wall === 'balance' ? 'balance' : 'plan';
266
+ const which = wall === 'balance' ? BALANCE_WALL : BILLING_WALL;
267
+ return {
268
+ host,
269
+ wall,
270
+ entitled,
271
+ // "The module actually answered." `degraded` is the module's own flag for
272
+ // "no real answer" (timeout, no plan field, no probe), and it must ALSO have
273
+ // named where the verdict came from — an unresolved boot snapshot has
274
+ // `degraded === false` only because nothing ever ran, and reporting that as
275
+ // verified would present "we never asked" as a fact about the account.
276
+ // Derived from the module's two fields rather than from the plan string, so
277
+ // this host never re-decides what counts as knowledge.
278
+ verified: snap.degraded === false && typeof snap.source === 'string' && snap.source !== '',
279
+ plan: snap.plan ? String(snap.plan) : 'free',
280
+ paid: entitled,
281
+ reason: copy.paidReason,
282
+ honesty: copy.honesty,
283
+ ask: copy.ask,
284
+ // No link once the offer is owned: a paying customer being sold the thing
285
+ // they already bought is the one prompt that can only lose money.
286
+ url: entitled ? '' : paymentUrl(which),
287
+ campaign: entitled ? '' : which.campaign,
288
+ // The BYOK lane's price, from the server's own published rate. Empty when
289
+ // the server published none — never a client-side guess (see the shared
290
+ // module's byokFeeLine). This is the sentence that closes the one place the
291
+ // bill and the pitch disagreed: a user was told BYOK costs "your provider's
292
+ // cost" while aegis1 charged a handling fee on top of it.
293
+ byok: feeLine,
294
+ label: entitled ? 'Pro' : wall === 'balance' ? 'Top up' : 'Upgrade',
295
+ unlock:
296
+ wall === 'balance'
297
+ ? 'Unlock: top up the Token Bank, or upgrade to Pro'
298
+ : 'Unlock: Pro, or any Token Bank balance',
299
+ };
300
+ }
301
+
302
+ module.exports = {
303
+ createCliEntitlement,
304
+ buildProbe,
305
+ loadModule,
306
+ paymentView,
307
+ paymentCopy,
308
+ feeView,
309
+ probeFee,
310
+ paymentUrl,
311
+ FALLBACK_COPY,
312
+ BILLING_WALL,
313
+ BALANCE_WALL,
314
+ };