aegiscode 6.8.2 → 6.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/panels.js CHANGED
@@ -41,6 +41,9 @@
41
41
 
42
42
  const { span, getSize, lineWidth } = require('./screen.js');
43
43
  const { themeOf, BOLD, BOLD_OFF, GLYPH } = require('./theme.js');
44
+ // Pure, like this module (signup.js requires nothing and does no I/O), so the
45
+ // "everything here is assertable from a plain Node test" contract still holds.
46
+ const { goUrl } = require('./signup.js');
44
47
 
45
48
  const VERSION = require('../package.json').version;
46
49
 
@@ -57,6 +60,30 @@ function str(v) {
57
60
  return v == null ? '' : String(v);
58
61
  }
59
62
 
63
+ /**
64
+ * The four token buckets these panels render, in the shared shape.
65
+ *
66
+ * `input` is the MISS half only — that is what `usageBuckets` normalises it to
67
+ * for every provider, and what the ledger rows and the desktop roll store — so
68
+ * the prompt a context window actually holds is `input + cacheRead +
69
+ * cacheWrite`, NOT `input` alone. Totalling `input + output` (what this file
70
+ * did before) therefore silently dropped the entire cached prompt: the exact
71
+ * turns where the cache was working and the context was largest were the turns
72
+ * the meter under-reported.
73
+ *
74
+ * `tok.total` wins when a caller supplies one (the live session tally does), so
75
+ * this fallback can only ever add information, never overwrite it. One formula,
76
+ * one place: /cost, /context and /tokens must not disagree about the same turn.
77
+ */
78
+ function tokenBuckets(tok) {
79
+ const input = num(tok.input);
80
+ const output = num(tok.output);
81
+ const cacheRead = num(tok.cacheRead);
82
+ const cacheWrite = num(tok.cacheWrite);
83
+ const prompt = input + cacheRead + cacheWrite;
84
+ return { input, output, cacheRead, cacheWrite, prompt, total: num(tok.total) || prompt + output };
85
+ }
86
+
60
87
  /** Group digits: 1562 -> "1,562". Matches the CLI's format.js rule. */
61
88
  function fmtTokens(n) {
62
89
  const v = Number(n);
@@ -178,8 +205,14 @@ function buildHelp(commands, ctx = {}) {
178
205
  out.push([span(t.gray, 'No commands registered.')]);
179
206
  }
180
207
  out.push([span('', '')]);
208
+ // 71 cells, and it has to stay under 80. This row was 81: the label already
209
+ // reads "Shortcuts:", so `? shortcuts` repeated the word — which cost the 10
210
+ // cells that pushed it one over, and `padLine()` truncates to `cols` rather
211
+ // than wrapping, so on every 80-column terminal the row rendered as
212
+ // "Ctrl-D exi". Measured by test/cli-panels.test.mjs, which asserts every
213
+ // buildHelp row fits the terminal.
181
214
  out.push([
182
- span(t.gray, 'Shortcuts: '), span(t.white, '?'), span(t.gray, ' shortcuts · '),
215
+ span(t.gray, 'Shortcuts: '), span(t.white, '?'), span(t.gray, ' · '),
183
216
  span(t.white, '/help'), span(t.gray, ' commands · '), span(t.white, '↑↓'), span(t.gray, ' history · '),
184
217
  span(t.white, 'Ctrl-L'), span(t.gray, ' clear · '), span(t.white, 'Ctrl-D'), span(t.gray, ' exit'),
185
218
  ]);
@@ -258,9 +291,7 @@ function buildCost(state, ctx = {}) {
258
291
  const { cols } = getSize();
259
292
  const W = Math.max(30, cols - 2);
260
293
  const tok = s.tokens && typeof s.tokens === 'object' ? s.tokens : {};
261
- const input = num(tok.input);
262
- const output = num(tok.output);
263
- const total = num(tok.total) || input + output;
294
+ const { input, output, cacheRead, cacheWrite, prompt, total } = tokenBuckets(tok);
264
295
  const cost = num(s.costEur);
265
296
  const model = str(s.model) || 'the pinned model';
266
297
  const window = num(s.contextWindow) || 200000;
@@ -281,7 +312,14 @@ function buildCost(state, ctx = {}) {
281
312
  lines.push([span('', ' '), span(t.white, 'Turns:'), span(t.gray, ` ${num(s.turns)} turns · ${num(s.calls)} calls`)]);
282
313
  }
283
314
  lines.push([span('', ' '), span(t.white, ' Usage by model:')]);
284
- lines.push([span('', ' '), span(t.gray, ` ${model}: ${fmtTokens(input)} input, ${fmtTokens(output)} output (${fmtEur(cost)})`)]);
315
+ // The prompt, not the miss. `input` is the miss half only (see tokenBuckets),
316
+ // so printing it as "input" reported 1.2k for a turn that had sent 31.2k —
317
+ // the same under-report /context was fixed for, in the panel that sits right
318
+ // next to it. With a cache in play the row is a sum, so show the split too.
319
+ lines.push([span('', ' '), span(t.gray, ` ${model}: ${fmtTokens(prompt)} input, ${fmtTokens(output)} output (${fmtEur(cost)})`)]);
320
+ if (cacheRead || cacheWrite) {
321
+ lines.push([span('', ' '), span(t.dim, ` ↳ miss ${fmtTokens(input)} · cache read ${fmtTokens(cacheRead)} · cache write ${fmtTokens(cacheWrite)}`)]);
322
+ }
285
323
  lines.push([span('', ' ')]);
286
324
  lines.push([span('', ' '), span(t.white + BOLD, 'Current session'), span(BOLD_OFF, '')]);
287
325
  lines.push(contextBar(total, window, t));
@@ -300,9 +338,7 @@ function buildContext(state, ctx = {}) {
300
338
  const { cols } = getSize();
301
339
  const W = Math.max(30, cols - 2);
302
340
  const tok = s.tokens && typeof s.tokens === 'object' ? s.tokens : {};
303
- const input = num(tok.input);
304
- const output = num(tok.output);
305
- const total = num(tok.total) || input + output;
341
+ const { input, output, cacheRead, cacheWrite, prompt, total } = tokenBuckets(tok);
306
342
  const window = num(s.contextWindow) || 200000;
307
343
 
308
344
  const lines = [];
@@ -315,7 +351,17 @@ function buildContext(state, ctx = {}) {
315
351
  span('', ' '.repeat(Math.max(1, 10 - fmtTokens(tokens).length))),
316
352
  ...contextBar(tokens, window, t),
317
353
  ];
318
- lines.push(row('Prompt tokens', input));
354
+ lines.push(row('Prompt tokens', prompt));
355
+ // With a cache in play the prompt row is a SUM, and a sum hides the one thing
356
+ // the operator is looking for: how much of the prompt was re-sent at full
357
+ // price. Show the split, so "280.0k" cannot be misread as 280k of fresh
358
+ // input. Absent a cache the row is byte-identical to before.
359
+ if (cacheRead || cacheWrite) {
360
+ lines.push([
361
+ span('', ' '),
362
+ span(t.dim, ` ↳ miss ${fmtTokens(input)} · cache read ${fmtTokens(cacheRead)} · cache write ${fmtTokens(cacheWrite)}`),
363
+ ]);
364
+ }
319
365
  lines.push(row('Output tokens', output));
320
366
  lines.push([span('', ' ')]);
321
367
  lines.push([span('', ' '), span(t.gray, '─'.repeat(Math.max(1, W - 2)))]);
@@ -866,7 +912,15 @@ function buildBilling(state, ctx = {}) {
866
912
  lines.push([span('', '')]);
867
913
  lines.push([span(t.white, 'AEGIS pooled inference'), span(t.gray, ' metered against your token bank')]);
868
914
  lines.push([span(t.gray, ' AEGIS has no subscription of its own — /cost shows this session\'s spend.')]);
869
- lines.push([span(t.gray, ' Top-ups and invoices: https://aegiscloud.org/billing')]);
915
+ // Was a literal `https://aegiscloud.org/billing`, which has never been a
916
+ // route on aegis1 — only `/billing/success` is real; the page is `/topup`.
917
+ // So the one row on the one screen that exists to convert a free user sent
918
+ // every user who reached it to a 404, and correcting a wrong path needed an
919
+ // npm release because it was compiled into the client. Now it points at
920
+ // `/go/topup`, a server-side indirection: the destination can change without
921
+ // a client release, and the click arrives tagged with the channel. 75 cells
922
+ // of 80 — measured, because `padLine()` truncates rather than wraps.
923
+ lines.push([span(t.gray, ` Top-ups and invoices: ${goUrl('topup', 'cost_screen')}`)]);
870
924
  return lines;
871
925
  }
872
926
 
@@ -879,11 +933,7 @@ function buildTokens(state, ctx = {}) {
879
933
  const { cols } = getSize();
880
934
  const W = Math.max(24, cols - 2);
881
935
  const tok = s.tokens && typeof s.tokens === 'object' ? s.tokens : {};
882
- const input = num(tok.input);
883
- const output = num(tok.output);
884
- const cacheRead = num(tok.cacheRead);
885
- const cacheWrite = num(tok.cacheWrite);
886
- const total = num(tok.total) || input + output;
936
+ const { input, output, cacheRead, cacheWrite, total } = tokenBuckets(tok);
887
937
  const cost = num(s.costEur);
888
938
  const window = num(s.contextWindow) || 200000;
889
939
  const pct = window > 0 ? Math.min(100, Math.round((total / window) * 100)) : 0;
package/src/screen.js CHANGED
@@ -224,11 +224,129 @@ const isAltScreen = () => inAlt;
224
224
  const enableBracketedPaste = () => process.stdout.write('\x1b[?2004h');
225
225
  const disableBracketedPaste = () => process.stdout.write('\x1b[?2004l');
226
226
 
227
- // Mouse button-event tracking (DECSET 1000) + SGR coordinates (1006). Only the
228
- // alt-screen/overlay path turns these on; disabled on exit so the shell we
229
- // return to isn't left forwarding raw wheel bytes as input.
230
- const enableMouseTracking = () => process.stdout.write('\x1b[?1000h\x1b[?1006h');
231
- const disableMouseTracking = () => process.stdout.write('\x1b[?1000l\x1b[?1006l');
227
+ // Mouse tracking + SGR coordinates. DECSET 1000 is the press/wheel report the
228
+ // click-to-toggle path needs; 1002 adds DRAG reports, without which a
229
+ // drag-to-mark gesture is invisible — the terminal reports the press and the
230
+ // release and nothing in between, so a sweep over three lines arrives as a
231
+ // single-cell marking. The terminal's own selection can't substitute for it:
232
+ // the alt screen has no scrollback for the terminal to select from. Disabled on
233
+ // exit so the shell we return to isn't left forwarding raw wheel bytes as input.
234
+ const enableMouseTracking = () => process.stdout.write('\x1b[?1000h\x1b[?1002h\x1b[?1006h');
235
+ const disableMouseTracking = () => process.stdout.write('\x1b[?1000l\x1b[?1002l\x1b[?1006l');
236
+
237
+ // Reverse video, used to paint a mouse marking (text selection) over the
238
+ // already-styled grid: the selected slice keeps its own colors and inverts its
239
+ // background. SELECT_OFF (SGR 27) turns inversion back off for the spans that
240
+ // follow the selection on the same row — paint() only resets attributes at the
241
+ // start of a row, so a leftover inverse would wash out the row's tail.
242
+ const SELECT_ON = '\x1b[7m';
243
+ const SELECT_OFF = '\x1b[27m';
244
+
245
+ // ── mouse marking (text selection) ─────────────────────────────────────────
246
+ // The TUI owns the alternate screen, so the terminal's own drag-to-select is
247
+ // unreachable — a marking has to be built from the SGR drag stream (events.js)
248
+ // against the grid the last frame painted (chatflow.js keeps it as
249
+ // `frameLines`). All of it is pure and cell-based: coordinates are grid row +
250
+ // CELL column (0-based), never string indices, so wide glyphs and padded rows
251
+ // can't shift the selection off the text the reader is pointing at.
252
+ // Ported from aegiscodex-dev/src/screen.js so both hosts mark identically.
253
+
254
+ /** Two drag endpoints → the same range in reading order (top-left first). */
255
+ function selectionRange(a, b) {
256
+ if (a.row < b.row || (a.row === b.row && a.col <= b.col)) {
257
+ return { startRow: a.row, startCol: a.col, endRow: b.row, endCol: b.col };
258
+ }
259
+ return { startRow: b.row, startCol: b.col, endRow: a.row, endCol: a.col };
260
+ }
261
+
262
+ /**
263
+ * Clip a span line to the cell range [from, to). Edges are cut on whole code
264
+ * points via w() — slicing by character index would split a 2-cell glyph and
265
+ * shift every later column by one. Spans keep their own style, so a marking
266
+ * across a colored diff block stays colored.
267
+ */
268
+ function sliceLine(line, from, to) {
269
+ const out = [];
270
+ let col = 0;
271
+ for (const sp of line) {
272
+ const start = col;
273
+ col += sp.w;
274
+ if (col <= from || start >= to) continue;
275
+ let text = sp.t;
276
+ let seen = start; // cell column of text[0]
277
+ if (seen < from) {
278
+ const drop = from - seen;
279
+ let acc = 0;
280
+ let cut = 0;
281
+ for (const ch of text) {
282
+ if (acc >= drop) break;
283
+ acc += w(ch);
284
+ cut += ch.length;
285
+ }
286
+ text = text.slice(cut);
287
+ seen += acc;
288
+ }
289
+ if (seen + w(text) > to) {
290
+ let acc = 0;
291
+ let keep = '';
292
+ for (const ch of text) {
293
+ const cw = w(ch);
294
+ if (seen + acc + cw > to) break;
295
+ keep += ch;
296
+ acc += cw;
297
+ }
298
+ text = keep;
299
+ }
300
+ if (text) out.push({ t: text, s: sp.s, w: w(text) });
301
+ }
302
+ return out;
303
+ }
304
+
305
+ /**
306
+ * The text a marking covers, read as a terminal would copy it: hard newlines
307
+ * between rows, trailing padding trimmed (rows are padded to the full width,
308
+ * and nobody wants 200 spaces per line on the clipboard), leading/trailing
309
+ * blank rows dropped.
310
+ */
311
+ function selectionText(lines, sel) {
312
+ const rows = [];
313
+ for (let r = sel.startRow; r <= sel.endRow; r++) {
314
+ const line = lines[r] || [];
315
+ const from = r === sel.startRow ? sel.startCol : 0;
316
+ const to = r === sel.endRow ? sel.endCol : Infinity;
317
+ rows.push(sliceLine(line, from, to).map((sp) => sp.t).join('').replace(/[ \t]+$/, ''));
318
+ }
319
+ while (rows.length && rows[0] === '') rows.shift();
320
+ while (rows.length && rows[rows.length - 1] === '') rows.pop();
321
+ return rows.join('\n');
322
+ }
323
+
324
+ /**
325
+ * A copy of `lines` with the marked cells wrapped in reverse video. Rows
326
+ * outside the range are shared, not cloned — a marking repaints up to ~30x/sec
327
+ * during a sweep and only the rows it touches should allocate. Each is padded
328
+ * first so a short row's selection is still painted over the blank cells the
329
+ * reader dragged across.
330
+ */
331
+ function applySelection(lines, sel, width) {
332
+ const out = lines.slice();
333
+ for (let r = sel.startRow; r <= sel.endRow; r++) {
334
+ if (r < 0 || r >= out.length) continue;
335
+ const line = padLine(out[r] || [], width);
336
+ const from = r === sel.startRow ? sel.startCol : 0;
337
+ const to = r === sel.endRow ? sel.endCol : width;
338
+ const mid = sliceLine(line, from, to);
339
+ if (!mid.length) continue;
340
+ out[r] = [
341
+ ...sliceLine(line, 0, from),
342
+ { t: '', s: SELECT_ON, w: 0 },
343
+ ...mid,
344
+ { t: '', s: SELECT_OFF, w: 0 },
345
+ ...sliceLine(line, to, width),
346
+ ];
347
+ }
348
+ return out;
349
+ }
232
350
 
233
351
  /**
234
352
  * Paint span lines top-aligned and clear the rest of the frame. Used by the
@@ -346,6 +464,13 @@ module.exports = {
346
464
  disableBracketedPaste,
347
465
  enableMouseTracking,
348
466
  disableMouseTracking,
467
+ // mouse marking (text selection)
468
+ SELECT_ON,
469
+ SELECT_OFF,
470
+ selectionRange,
471
+ sliceLine,
472
+ selectionText,
473
+ applySelection,
349
474
  // the live region + sizing (app/bin)
350
475
  LiveRegion,
351
476
  termWidth,
package/src/screens.js CHANGED
@@ -38,6 +38,7 @@ const render = require('./render.js');
38
38
  const { updateConfig, configExists, loadConfig } = require('./config.js');
39
39
  const { updateNotice, updateLine } = require('./update.js');
40
40
  const credentials = require('./credentials.js');
41
+ const { signupUrl, signupDisplayUrl } = require('./signup.js');
41
42
  const { createSettingsStore, isReservedNamespace } = require('./deps.js');
42
43
 
43
44
  const VERSION = require('../package.json').version;
@@ -93,13 +94,24 @@ const WHATS_NEW = [
93
94
  * exactly, one route each, and the desktop line shares the second.
94
95
  *
95
96
  * Both commands named here are real registry entries — `/byok-key` saves a
96
- * provider key, `/key` saves the AEGIS account key — and the URL is the same
97
- * `aegiscloud.org` the key screen and `/cloud` panels already point at. Nothing
98
- * here is a URL or a command that only exists in this comment.
97
+ * provider key, `/key` saves the AEGIS account key — and the URL is the shared
98
+ * signup deep link from signup.js, not a hand-written one: it lands on the
99
+ * register panel with the key page queued behind it and the channel attached,
100
+ * which the bare `aegiscloud.org` this row used to print did not. Nothing here
101
+ * is a URL or a command that only exists in this comment.
99
102
  */
100
103
  const CONNECT = [
101
104
  'Your key, your bill: /byok-key <provider> — or AEGIS Cloud, /key',
102
- 'AEGIS Desktop: same engine in a window, on your machine — aegiscloud.org',
105
+ // The scheme-less form, and this is the only link in the CLI that uses it.
106
+ // The row's copy spends 45 of the 75 cells `wrapped()` allows at 80 columns
107
+ // (cols - 4 - indent), so `https://aegiscloud.org/key?s=cli` makes the row 77
108
+ // and wraps — a line the 80x24 screen does not have, because the connect
109
+ // block sits on row 21 of 23 and the row it pushes out is the footer hint.
110
+ // `s=cli` is the parameter that files the signup, so it is the scheme that
111
+ // goes, not the channel: see signup.js `signupDisplayUrl()`. Editing this copy
112
+ // means re-measuring; test/cli-onboarding.test.mjs fails on the row count if
113
+ // the row grows past the budget, and names the row that caused it.
114
+ `AEGIS Desktop: same engine on your machine — ${signupDisplayUrl()}`,
103
115
  ];
104
116
 
105
117
  /** Centre a plain string, returning one span line. Clip first, or a string
@@ -514,7 +526,12 @@ async function showWelcome(ctx, firstRun = true) {
514
526
 
515
527
  // ── the account key ──────────────────────────────────────────────────────────
516
528
 
517
- const KEY_URL = 'https://aegiscloud.org';
529
+ // The key screen is the highest-intent moment in the CLI: the user pressed
530
+ // Enter on a bare /key, so they have already decided they want an account.
531
+ // The link is the short aegis1 deep link (see signup.js) — it lands on the
532
+ // register panel with the key page queued behind it, which is the round trip
533
+ // that used to be left to the user to figure out from the homepage.
534
+ const KEY_URL = signupUrl('key_screen');
518
535
 
519
536
  /**
520
537
  * The key screen's lines. Pure, so what the user is told is asserted directly.
@@ -530,13 +547,25 @@ function keyLines(ctx, cols, { value = '', error = null, verify = false } = {})
530
547
  lines.push([span(t.white + BOLD, 'Connect your AEGIS account')]);
531
548
  lines.push([span('', '')]);
532
549
  for (const l of wrapped(
533
- `Paste an API key to use AEGIS Cloud. Get one free at ${KEY_URL}. ` +
534
- 'It is stored in your user config directory with owner-only permissions, so later launches and scripts pick it up without an export.',
550
+ 'Paste an API key to use AEGIS Cloud. It is stored in your user config ' +
551
+ 'directory with owner-only permissions, so later launches and scripts ' +
552
+ 'pick it up without an export.',
535
553
  cols,
536
554
  t.white
537
555
  )) {
538
556
  lines.push(l);
539
557
  }
558
+ // The link gets its own row whenever it would otherwise run past the edge:
559
+ // a URL sheared across two lines is not typeable, and this is the one screen
560
+ // where the user has nothing to copy it out of.
561
+ lines.push([span('', '')]);
562
+ const invite = ' No key yet? Free one at ';
563
+ if (w(invite) + w(KEY_URL) + 2 <= cols) {
564
+ lines.push([span(t.white, invite), span(t.cyan, KEY_URL)]);
565
+ } else {
566
+ lines.push([span(t.white, ' No key yet? Free one:')]);
567
+ lines.push([span(t.cyan, ` ${KEY_URL}`)]);
568
+ }
540
569
  lines.push([span('', '')]);
541
570
  lines.push([
542
571
  span(t.lavender, GLYPH.cursor),
package/src/signup.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The one place the CLI tells a user where to get an account key.
3
+ *
4
+ * Every prompt used to say "free at https://aegiscloud.org" — the marketing
5
+ * homepage. No registration panel, no route to the page that shows the key,
6
+ * and (because the landing URL carried no UTM) no way for aegis1 to tell the
7
+ * signup came from the CLI at all. That is a round trip the user has to
8
+ * complete unaided, at the exact moment they have already decided to keep the
9
+ * tool: the prompts were the top of the funnel and they dead-ended.
10
+ *
11
+ * So the prompt now prints a short, typeable deep link instead:
12
+ *
13
+ * https://aegiscloud.org/key?s=cli&c=key_screen
14
+ *
15
+ * `/key` is a real aegis1 route (app.py `key_short_link`) that expands —
16
+ * server-side — into the register panel plus the key page, with the channel
17
+ * UTMs attached. Two consequences worth knowing before editing anything here:
18
+ *
19
+ * - `s=cli` must stay in aegis1's SIGNUP_SOURCES or the signup is filed as
20
+ * 'direct' and this channel looks dead in the funnel. `s` is deliberately
21
+ * not caller-supplied: one wrong value silently zeroes the channel.
22
+ * - the URL is displayed, not just linked, so it has to stay short enough
23
+ * not to wrap in an 80-column terminal. That is the whole reason the
24
+ * expansion is a server-side redirect rather than a long query string: the
25
+ * full form is 108 chars and shears across lines.
26
+ *
27
+ * `campaign` is the prompt that printed the link, so prompts can be compared
28
+ * against each other instead of reported as one number. Unknown or absent
29
+ * campaigns are simply not sent — unattributed is a missing datapoint, never a
30
+ * wrong one.
31
+ */
32
+
33
+ const SIGNUP_ORIGIN = 'https://aegiscloud.org';
34
+
35
+ /** The short aegis1 route that expands to "register, then show me my key". */
36
+ const SIGNUP_PATH = '/key';
37
+
38
+ /** The channel every CLI signup is filed under in aegis1 (SIGNUP_SOURCES). */
39
+ const SIGNUP_SOURCE = 'cli';
40
+
41
+ /** Bare `https://aegiscloud.org` for copy about the project rather than the
42
+ * key — the docs/troubleshooting links in system.js want the homepage. */
43
+ const HOME_URL = SIGNUP_ORIGIN;
44
+
45
+ /** Longest campaign slug aegis1 will record (`_sanitize_signup_slug`). */
46
+ const CAMPAIGN_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
47
+
48
+ /**
49
+ * The deep link to show a user who has no key.
50
+ *
51
+ * A campaign that would not survive aegis1's slug sanitiser is dropped rather
52
+ * than sent: a link that records nothing is honest, a link that records the
53
+ * wrong prompt is not.
54
+ */
55
+ function signupUrl(campaign) {
56
+ const url = new URL(SIGNUP_ORIGIN + SIGNUP_PATH);
57
+ url.searchParams.set('s', SIGNUP_SOURCE);
58
+ const slug = campaign === undefined || campaign === null ? '' : String(campaign).trim().toLowerCase();
59
+ if (CAMPAIGN_RE.test(slug)) url.searchParams.set('c', slug);
60
+ return url.toString();
61
+ }
62
+
63
+ /**
64
+ * Any other aegiscloud.org page the CLI links to, tagged with the same
65
+ * channel so the visit is attributable if it ends in a signup.
66
+ *
67
+ * aegis1's first-touch hook stores the UTMs on whichever page the visitor
68
+ * lands on, so a tagged link to the desktop page or the subscribe page is
69
+ * enough for the signup it eventually produces to be credited to the CLI —
70
+ * no separate route needed, unlike the key link above.
71
+ */
72
+ function link(path, campaign) {
73
+ const url = new URL(SIGNUP_ORIGIN + (String(path).startsWith('/') ? path : `/${path}`));
74
+ url.searchParams.set('utm_source', SIGNUP_SOURCE);
75
+ url.searchParams.set('utm_medium', 'app');
76
+ const slug = campaign === undefined || campaign === null ? '' : String(campaign).trim().toLowerCase();
77
+ if (CAMPAIGN_RE.test(slug)) url.searchParams.set('utm_campaign', slug);
78
+ return url.toString();
79
+ }
80
+
81
+ /**
82
+ * The printed form of the same link: scheme-less.
83
+ *
84
+ * Not cosmetic, and not a second URL — it is `signupUrl()` with the `https://`
85
+ * stripped, so the host, the route and the channel still come from one place.
86
+ * It exists because the welcome screen's connect row wraps its text at
87
+ * `cols - 4 - indent` (screens.js `wrapped()`), which is 75 cells at 80
88
+ * columns, and the row's copy already spends 45 of them:
89
+ *
90
+ * AEGIS Desktop: same engine on your machine — <url>
91
+ *
92
+ * https://aegiscloud.org/key?s=cli -> 77 cells, wraps
93
+ * aegiscloud.org/key?s=cli -> 69 cells, fits
94
+ *
95
+ * A wrapped row is not just ugly there: the welcome screen fills 23 of an
96
+ * 80x24 terminal's 24 rows, so the extra line pushes the footer hint off the
97
+ * bottom (test/cli-onboarding.test.mjs measures it). Given that, the scheme is
98
+ * the cheapest thing to lose — a browser prepends it when the user pastes, and
99
+ * `aegiscloud.org/teleport` is already printed this way in commands.js — while
100
+ * `s=cli` is not, because dropping that files the signup as 'direct'.
101
+ *
102
+ * Screens with room for the real thing (the key screen puts the link on its
103
+ * own row) must use `signupUrl()`.
104
+ */
105
+ function signupDisplayUrl(campaign) {
106
+ return signupUrl(campaign).replace(/^https?:\/\//, '');
107
+ }
108
+
109
+ /** aegis1's paid-prompt indirection: `/go/<page>` (app.py `GO_TARGETS`). */
110
+ const GO_PATH = '/go/';
111
+
112
+ /**
113
+ * A paid prompt's destination, in the short form `/go/<page>` documents.
114
+ *
115
+ * Deliberately NOT `link()`, and this is the whole reason the function exists.
116
+ * `link()` appends the wire names (`utm_source`/`utm_campaign`) because
117
+ * aegis1's first-touch hook reads those off whichever page the visitor lands
118
+ * on. `/go/<page>` is not that kind of link: it is a redirect, and it reads the
119
+ * short names (`s`/`c`) and re-emits the wire names itself.
120
+ *
121
+ * Sending wire names to `/go/` does not fail loudly. It fails silently, in the
122
+ * worst available way — the route finds no `s`, files the click as 'direct',
123
+ * drops the campaign, and the client that sent it reads as zero conversions
124
+ * while the link still visibly works. Measured against a real app instance:
125
+ *
126
+ * /go/upgrade?s=cli&c=memory_quota -> ?utm_source=cli&utm_campaign=memory_quota
127
+ * /go/upgrade?utm_source=cli&... -> ?utm_source=direct&utm_medium=app
128
+ *
129
+ * The route now also accepts the wire names as a fallback, so that mistake can
130
+ * no longer zero a channel — but the short form is still what to send, and not
131
+ * only for correctness: it is ~40 cells shorter, on rows that `padLine()`
132
+ * truncates rather than wraps (see `signupDisplayUrl()` above).
133
+ */
134
+ function goUrl(page, campaign) {
135
+ const slug = String(page == null ? '' : page).trim().toLowerCase().replace(/^\/+|\/+$/g, '');
136
+ const url = new URL(SIGNUP_ORIGIN + GO_PATH + slug);
137
+ url.searchParams.set('s', SIGNUP_SOURCE);
138
+ const c = campaign === undefined || campaign === null ? '' : String(campaign).trim().toLowerCase();
139
+ if (CAMPAIGN_RE.test(c)) url.searchParams.set('c', c);
140
+ return url.toString();
141
+ }
142
+
143
+ module.exports = {
144
+ signupUrl,
145
+ signupDisplayUrl,
146
+ goUrl,
147
+ link,
148
+ HOME_URL,
149
+ SIGNUP_SOURCE,
150
+ SIGNUP_PATH,
151
+ SIGNUP_ORIGIN,
152
+ CAMPAIGN_RE,
153
+ };