aegiscode 7.0.14 → 7.0.15

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.
Files changed (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +3 -2
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
package/src/screens.js CHANGED
@@ -1,898 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Onboarding screens — trust check, theme picker, welcome.
10
- *
11
- * A direct port of the upstream engine reference, which is where the
12
- * reference's session actually begins: a genuine first run is
13
- *
14
- * showTrustCheck(ctx) → showThemePicker(ctx) → updateConfig() → welcome
15
- *
16
- * and every later run goes straight to the welcome box. The CLI had none of
17
- * this — `runInteractive` went directly into `chatflow.runSession`, so the
18
- * trust check, the theme picker and the pre-session welcome did not exist and
19
- * `configExists()` was dead code with zero callers. That is the gap this file
20
- * closes; the ordering and the copy are the reference's.
21
- *
22
- * Two deliberate departures, both so this client stays honest:
23
- *
24
- * - `runOnboarding` **returns** whether the user declined rather than calling
25
- * `process.exit` from inside a library function, so the caller owns process
26
- * lifecycle (and a test can drive the whole flow).
27
- * - The right-hand box is about *this* client: the commands that add a model
28
- * and set a key, each held to this package's own registry. It used to be a
29
- * `What's new` list of *this* package's release notes — never Aegiscodex's,
30
- * printing another project's changelog in our banner would be a lie about
31
- * what the user just installed — but a changelog is stale the moment the
32
- * next release lands, and it answered no question a new user has.
33
- *
34
- * Every screen is split into a pure line-builder (`trustLines`,
35
- * `themePickerLines`, `welcomeLines`) plus a thin key loop, so the exact
36
- * content of each screen is asserted by tests with no terminal and no timing.
37
- */
38
-
39
- const { getSize, paint, span, lineWidth, clip, w } = require('./screen.js');
40
- const events = require('./events.js');
41
- const { nextKey, KEY } = events;
42
- const { C, BOLD, BOLD_OFF, GLYPH, THEME_TABLE, themeOf, themeIsLight, terminalIsLight } = require('./theme.js');
43
- const { TAGLINE, TAGLINE_SHORT, welcomeArtParts } = require('./art.js');
44
- const { renderDiffPreview } = require('./markdown.js');
45
- const render = require('./render.js');
46
- const { updateConfig, configExists, loadConfig } = require('./config.js');
47
- const { updateNotice, updateLine, serverNotice, serverUpdateLine } = require('./update.js');
48
- const credentials = require('./credentials.js');
49
- const { signupUrl, signupDisplayUrl } = require('./signup.js');
50
- const { createSettingsStore, isReservedNamespace } = require('./deps.js');
51
-
52
- const VERSION = require('../package.json').version;
53
-
54
- const PRODUCT = 'AEGIS Code';
55
-
56
- /** The two boxes' contents. The right-hand box is `KEY_HELP` — the commands
57
- * that add a model and set a key — not a changelog; see its comment below. */
58
- const TIPS = [
59
- ' Run /init to create an AEGIS.md',
60
- ' Use ↑↓ to recall past prompts',
61
- ' Press / for commands',
62
- ' Press Tab to complete a command',
63
- ' Press ? for shortcuts',
64
- ];
65
-
66
- /**
67
- * The second box: what this build can DO for you, not what changed in it.
68
- *
69
- * It used to be a hand-written `What's new` patch list, and that shape was the
70
- * problem: a changelog on a welcome screen is read once and then goes stale by
71
- * construction, so the box spent most of its life advertising releases the user
72
- * was not running (it sat four minors behind while the package shipped 6.7.3)
73
- * or, worse, patch notes for a version nobody can act on. The four things a new
74
- * user actually has to know to get a turn running are all commands: how to add a
75
- * model, how to set a provider key, how to set an AEGIS account key, and how to
76
- * switch between the models they now hold. Those do not go stale — every command
77
- * named here is asserted to exist in the registry by test/cli-onboarding.test.mjs,
78
- * so a rename fails the suite instead of quietly leaving a dead route on the
79
- * first screen the user reads.
80
- *
81
- * The row count is load-bearing, exactly as the patch list's was: at 80×24 the
82
- * welcome screen fills rows-1 exactly (23 of 24), and `boxes()` receives an
83
- * `avail` it never reads, so a tenth row would push the footer hint off the
84
- * bottom of the commonest terminal there is. `test/cli-onboarding.test.mjs`
85
- * pins the total; retire a row rather than adding one. Each provider row wraps
86
- * its `argument list` onto a second row on purpose — a 60-cell command on a
87
- * 39-cell box would be clipped mid-word by `boxLines()`, which reads as a
88
- * rendering fault rather than as an example.
89
- */
90
- const KEY_HELP = [
91
- ' Add a model: /model add',
92
- ' <id> <name> <model> <url>',
93
- ' Set a provider key: /byok-key',
94
- ' <provider> — openai, anthropic',
95
- ' Set your account key: /key <key>',
96
- ' Switch model: /model, or alt+p',
97
- ' Reasoning effort: /effort',
98
- ' All commands: press / for the list',
99
- ];
100
-
101
- /**
102
- * The connect block — the two ways to power this client, plus the one-line
103
- * answer to "why would I want the app". Shown under the boxes on the welcome
104
- * screen, in place of the desktop host's welcome panel (BYOK + AEGIS Cloud).
105
- *
106
- * It is two plain rows and not a third box, and the reason is the same row
107
- * budget `KEY_HELP` is held to: at 80×24 the rule, mark, title, tagline and
108
- * the Tips/Models-and-keys pair already come to 21 of the 23 usable rows, so a
109
- * boxed third panel (three rows minimum, two of them rules) would push the
110
- * footer hint off the bottom of the commonest terminal there is. Two rows fit
111
- * exactly: one route row, and the desktop line under it.
112
- *
113
- * WHICH route row is the part that matters, and it is composed by
114
- * `connectRows()` below rather than being a constant, because the two routes
115
- * have separate gates. They used to share a single one that short-circuited on
116
- * the account key, so the `/byok-key` row disappeared the moment a user
117
- * redeemed an AEGIS key — see `byokRouteNeeded()`. Holding the block to two
118
- * rows is why the both-owed case merges the routes into one row again: at
119
- * 80×24 a third row is the footer hint.
120
- *
121
- * Both commands named here are real registry entries — `/byok-key` saves a
122
- * provider key, `/key` saves the AEGIS account key — and the URL is the shared
123
- * signup deep link from signup.js, not a hand-written one: it lands on the
124
- * register panel with the key page queued behind it and the channel attached,
125
- * which the bare `aegiscloud.org` this row used to print did not. Nothing here
126
- * is a URL or a command that only exists in this comment.
127
- */
128
- const CONNECT_BYOK = [
129
- 'Your own provider key: /byok-key <provider> — works with your AEGIS key',
130
- ];
131
-
132
- // The AEGIS Cloud route. The URL in the desktop row below is the shared signup
133
- // deep link from signup.js, not a hand-written one: it lands on the register
134
- // panel with the key page queued behind it and the channel attached, which the
135
- // bare `aegiscloud.org` that row used to print did not.
136
- //
137
- // The scheme-less form, and this is the only link in the CLI that uses it. The
138
- // row's copy spends 45 of the 75 cells `wrapped()` allows at 80 columns
139
- // (cols - 4 - indent), so `https://aegiscloud.org/key?s=cli` makes the row 77
140
- // and wraps — a line the 80x24 screen does not have, because the connect
141
- // block sits on row 21 of 23 and the row it pushes out is the footer hint.
142
- // `s=cli` is the parameter that files the signup, so it is the scheme that
143
- // goes, not the channel: see signup.js `signupDisplayUrl()`. Editing this copy
144
- // means re-measuring; test/cli-onboarding.test.mjs fails on the row count if
145
- // the row grows past the budget, and names the row that caused it.
146
- const CONNECT_CLOUD = [
147
- 'AEGIS Cloud, one account key: /key — no provider signup',
148
- ];
149
-
150
- // Both routes still owed (a fresh install): one row naming both, the original
151
- // copy. Two rows is the whole budget, so this is not a third line — see the
152
- // block comment above.
153
- const CONNECT_BOTH = [
154
- 'Your key, your bill: /byok-key <provider> — or AEGIS Cloud, /key',
155
- ];
156
-
157
- const CONNECT_DESKTOP = [
158
- `AEGIS Desktop: same engine on your machine — ${signupDisplayUrl()}`,
159
- ];
160
-
161
- /**
162
- * The connect rows to draw, in order, for the machine as it stands now.
163
- *
164
- * `[]` means nothing to say — both routes are configured — and the caller then
165
- * draws no block at all. Otherwise: one route row (both-owed merges into a
166
- * single row, the 80×24 budget above, and the desktop pointer always shares
167
- * the block with it).
168
- *
169
- * The gates are independent on purpose. An AEGIS key does not cancel the
170
- * `/byok-key` row and a provider route does not cancel the `/key` row: the two
171
- * are not alternatives, they are two ways in, and the row a user has already
172
- * taken is the only one that may be dropped.
173
- */
174
- function connectRows() {
175
- const rows = [];
176
- const byok = byokRouteNeeded();
177
- const cloud = cloudRouteNeeded();
178
- if (byok && cloud) rows.push(...CONNECT_BOTH);
179
- else if (byok) rows.push(...CONNECT_BYOK);
180
- else if (cloud) rows.push(...CONNECT_CLOUD);
181
- // The desktop pointer is not a route, so it is not gated on one: whenever the
182
- // block is drawn at all, the "why would I want the app" answer is in it.
183
- if (rows.length) rows.push(...CONNECT_DESKTOP);
184
- return rows;
185
- }
186
-
187
- /** Centre a plain string, returning one span line. Clip first, or a string
188
- * wider than the terminal produces a row that wraps and shears the frame. */
189
- function centered(text, cols, style) {
190
- const t = clip(String(text), Math.max(1, cols));
191
- const pad = Math.max(0, Math.floor((cols - w(t)) / 2));
192
- return [span('', ' '.repeat(pad)), span(style, t)];
193
- }
194
-
195
- /** Wrap body copy to `cols - 4`, one span line per row (the reference's
196
- * wrapGray, kept here because screen.js's wrapBlock takes spans). */
197
- function wrapped(text, cols, style, indent = 0) {
198
- const words = String(text).split(' ');
199
- const out = [];
200
- let line = [];
201
- let len = 0;
202
- for (const word of words) {
203
- if (len + w(word) + 1 > cols - 4 - indent && line.length) {
204
- out.push([span('', ' '.repeat(indent)), span(style, line.join(' '))]);
205
- line = [word];
206
- len = w(word);
207
- } else {
208
- if (line.length) len++;
209
- line.push(word);
210
- len += w(word);
211
- }
212
- }
213
- if (line.length) out.push([span('', ' '.repeat(indent)), span(style, line.join(' '))]);
214
- return out;
215
- }
216
-
217
- // ── trust check ──────────────────────────────────────────────────────────────
218
-
219
- /** The trust screen's lines. `sel` is 0 = trust, 1 = exit. Pure. */
220
- function trustLines(ctx, cols, sel = 0, cwd = process.cwd()) {
221
- const lines = [];
222
- lines.push([span(C.gold, '─'.repeat(Math.max(1, cols)))]);
223
- lines.push([span(C.white + BOLD, 'Accessing workspace:')]);
224
- lines.push([span(C.white + BOLD, clip(cwd, Math.max(1, cols - 1)))]);
225
- lines.push([span('', '')]);
226
- for (const l of wrapped(
227
- `Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team). If not, take a moment to review what's in this folder first.`,
228
- cols,
229
- C.white
230
- )) {
231
- lines.push(l);
232
- }
233
- lines.push([span('', '')]);
234
- lines.push([span(C.white, `${PRODUCT} will be able to read, edit, and execute files here.`)]);
235
- lines.push([span('', '')]);
236
- lines.push([span(C.white + BOLD, 'Security guide')]);
237
- lines.push([span('', '')]);
238
- for (let i = 0; i < 2; i++) {
239
- const active = sel === i;
240
- const left = active ? span(C.lavender, GLYPH.cursor) : span('', ' ');
241
- const n = span(C.gray, ` ${i + 1}.`);
242
- const label = i === 0 ? 'Yes, I trust this folder' : 'No, exit';
243
- lines.push([
244
- left,
245
- n,
246
- span(active ? C.lavender : C.white, label),
247
- ]);
248
- }
249
- lines.push([span('', '')]);
250
- lines.push([span(C.gray, `Enter to confirm ${GLYPH.bullet} Esc to cancel`)]);
251
- return lines;
252
- }
253
-
254
- /**
255
- * The trust check. Resolves true when the folder is trusted, false when the
256
- * user declines — the caller must abort the session on false, as the reference
257
- * does (it never reaches `session(ctx)`).
258
- */
259
- async function showTrustCheck(ctx) {
260
- const { cols } = getSize();
261
- let sel = 0;
262
- const renderScreen = () => paint(trustLines(ctx, cols, sel));
263
- renderScreen();
264
- for (;;) {
265
- const key = await nextKey();
266
- if (key.name === KEY.UP || key.name === KEY.DOWN || key.name === KEY.TAB) {
267
- sel = 1 - sel;
268
- renderScreen();
269
- } else if (key.name === KEY.ENTER) {
270
- return sel === 0;
271
- } else if (key.name === KEY.ESC || key.name === KEY.CTRL_C || key.name === KEY.CTRL_D) {
272
- return false;
273
- } else if (key.name === 'char') {
274
- const c = String(key.ch).trim();
275
- if (c === '1') {
276
- sel = 0;
277
- renderScreen();
278
- }
279
- if (c === '2') {
280
- sel = 1;
281
- renderScreen();
282
- }
283
- }
284
- }
285
- }
286
-
287
- // ── theme picker ─────────────────────────────────────────────────────────────
288
-
289
- /** Apply a picker row to a context: both the row index and the light flag, the
290
- * way the reference commits (`ctx.light = sel === 2 || sel === 4 || sel === 6`).
291
- * Row 0 is "Auto (match terminal)", whose flag is resolved from the terminal's
292
- * reported background by `themeIsLight` — reading the row's own `light` field
293
- * would commit the dark fallback and make the one auto row a dark row. */
294
- function applyTheme(ctx, sel) {
295
- const row = THEME_TABLE[sel] || THEME_TABLE[1];
296
- ctx.themeIndex = sel;
297
- ctx.light = themeIsLight(sel);
298
- return sel;
299
- }
300
-
301
- /** The theme picker's lines. Pure, so the 7 rows and their notes are testable. */
302
- function themePickerLines(ctx, cols, rows, sel) {
303
- const lines = [];
304
- lines.push([span(C.coral, `Welcome to ${PRODUCT} v${VERSION}`)]);
305
- lines.push([span(C.white + BOLD, "Let's get started.")]);
306
- lines.push([span(C.white, 'Choose the text style that looks best with your terminal')]);
307
- lines.push([span(C.gray, 'To change this later, run /theme')]);
308
- lines.push([span('', '')]);
309
- for (let i = 0; i < THEME_TABLE.length; i++) {
310
- const t = THEME_TABLE[i];
311
- const active = sel === i;
312
- const left = active ? span(C.lavender, GLYPH.cursor) : span('', ' ');
313
- const n = span(C.gray, `${i + 1}.`);
314
- const check = active ? span(C.green, ' ' + GLYPH.check) : span('', '');
315
- lines.push([
316
- left,
317
- n,
318
- span(active ? C.lavender : C.white, t.name),
319
- ...(t.note ? [span(C.gray, ' ' + t.note)] : []),
320
- check,
321
- ]);
322
- }
323
- // The diff preview is drawn in this terminal's palette, so a row actually
324
- // shows what it will look like rather than describing it.
325
- for (const l of renderDiffPreview(cols, ctx)) lines.push(l);
326
- lines.push([span(C.gray, ' Syntax theme: Monokai Extended (ctrl+t to disable)')]);
327
- while (lines.length < rows - 1) lines.push([span('', '')]);
328
- return lines;
329
- }
330
-
331
- /**
332
- * The theme picker. Resolves the chosen row index. Esc commits the highlighted
333
- * row rather than discarding it, matching the reference — there is no "cancel"
334
- * that leaves the theme unset on a first run.
335
- */
336
- async function showThemePicker(ctx, title = `Welcome to ${PRODUCT}`) {
337
- const { cols, rows } = getSize();
338
- // The highlighted row is a proposal about *this* terminal, so a first run
339
- // proposes the one it can show: a light terminal opened on "Dark mode" is the
340
- // same white-on-white mistake one keystroke away, this time as a default the
341
- // user is asked to accept. Nothing is committed until they answer.
342
- let sel = typeof ctx.themeIndex === 'number' ? ctx.themeIndex : terminalIsLight() ? 2 : 1;
343
- const renderScreen = () => paint(themePickerLines(ctx, cols, rows, sel));
344
- renderScreen();
345
- for (;;) {
346
- const key = await nextKey();
347
- if (key.name === KEY.UP) {
348
- sel = Math.max(0, sel - 1);
349
- renderScreen();
350
- } else if (key.name === KEY.DOWN) {
351
- sel = Math.min(THEME_TABLE.length - 1, sel + 1);
352
- renderScreen();
353
- } else if (key.name === KEY.ENTER || key.name === KEY.ESC || key.name === KEY.CTRL_C || key.name === KEY.CTRL_D) {
354
- return applyTheme(ctx, sel);
355
- } else if (key.name === KEY.CTRL_T) {
356
- ctx.light = !ctx.light;
357
- renderScreen();
358
- } else if (key.name === 'char') {
359
- const n = parseInt(key.ch, 10);
360
- if (n >= 1 && n <= THEME_TABLE.length) {
361
- sel = n - 1;
362
- renderScreen();
363
- }
364
- }
365
- }
366
- }
367
-
368
- // ── welcome ──────────────────────────────────────────────────────────────────
369
-
370
- /**
371
- * The welcome screen's lines: gold rule, the wordmark, the coral title,
372
- * the two boxes, the footer hint. Pure, so a test can assert all of it.
373
- *
374
- * The mark reuses `render.artRow`, the same renderer the scrollback banner
375
- * uses, so the mark cannot render two different ways in two places.
376
- */
377
- function welcomeLines(ctx, cols, rows, firstRun = true) {
378
- const t = themeOf(ctx);
379
- const lines = [];
380
- lines.push([span(t.gold, '━' + '─'.repeat(Math.max(0, cols - 2)) + '━')]);
381
- lines.push([span('', '')]);
382
-
383
- // A newer release, if the last run found one. Reads cache only — the
384
- // refresh it may kick off lands for the NEXT launch, so drawing this box
385
- // never waits on the registry.
386
- let updateMsg = null;
387
- try {
388
- const cfg = loadConfig();
389
- const notice = updateNotice({
390
- current: VERSION,
391
- cache: cfg.updateCheck,
392
- save: (v) => { try { updateConfig({ updateCheck: v }); } catch { /* not fatal */ } },
393
- });
394
- updateMsg = updateLine({ current: VERSION, ...notice });
395
-
396
- // The server's own verdict, which outranks the registry's: "a newer
397
- // release exists" is a suggestion, "this build is no longer served" is
398
- // the app about to stop working. aegis1 refuses clients below
399
- // MIN_CLIENT_VERSION with a 426, so without this line a user learns it
400
- // by being cut off mid-task instead of by reading their welcome box.
401
- // Same cache-read-only rule: the refresh lands for the next launch.
402
- const srv = serverNotice({
403
- current: VERSION,
404
- cache: cfg.updateCheckServer,
405
- save: (v) => { try { updateConfig({ updateCheckServer: v }); } catch { /* not fatal */ } },
406
- });
407
- updateMsg = serverUpdateLine(srv) || updateMsg;
408
- } catch {
409
- // An update notice is never worth failing a launch over.
410
- }
411
-
412
- const parts = welcomeArtParts();
413
- if (cols >= parts.width + 2) {
414
- const leftPad = Math.max(0, Math.floor((cols - parts.width) / 2));
415
- for (const row of parts.rows) {
416
- lines.push(wrapPlain(render.artRow(ctx, row, parts, leftPad)));
417
- }
418
- } else {
419
- lines.push(centered(`${PRODUCT}`, cols, t.gold + BOLD));
420
- }
421
- if (updateMsg) {
422
- lines.push([span('', '')]);
423
- lines.push(centered(updateMsg, cols, t.gold));
424
- }
425
- lines.push([span('', '')]);
426
-
427
- const title = firstRun ? `Welcome to ${PRODUCT}` : 'Welcome back!';
428
- lines.push(centered(title, cols, t.coral + BOLD));
429
- // Shorten the subtitle rather than clipping it: a truncated tagline reads as
430
- // a rendering fault, a shorter one just reads as a shorter one. The threshold
431
- // is derived from the string's own width, not a fixed column count — the copy
432
- // lives in `art.js` now, so a hardcoded breakpoint here would silently start
433
- // clipping the moment the tagline grew by a word.
434
- const tagline = cols >= w(TAGLINE) + 4 ? TAGLINE : TAGLINE_SHORT;
435
- lines.push(centered(tagline, cols, t.gray));
436
- lines.push([span('', '')]);
437
-
438
- lines.push(...boxes(t, cols, rows - lines.length - 4));
439
- lines.push([span('', '')]);
440
- // The connect block, before the footer hint. The rows are composed by
441
- // `connectRows()` — the two routes gate SEPARATELY, so an AEGIS-key holder
442
- // with no provider route of their own is still told `/byok-key` exists,
443
- // which is the whole point: holding an account key is not a reason to hide
444
- // the bring-your-own-key route. `wrapped` splits rather than clips, so a
445
- // narrow terminal gets short rows instead of sheared ones; the height budget
446
- // is unaffected at 80×24, where each row still fits on one line.
447
- for (const text of connectRows()) lines.push(...wrapped(text, cols, t.white, 1));
448
- lines.push([span(t.gray, GLYPH.hint), span(t.white, ' Try "write a test for <filepath>"')]);
449
- while (lines.length < rows - 1) lines.push([span('', '')]);
450
- return lines;
451
- }
452
-
453
- /**
454
- * One box: a `╭─ Header ────╮` top rule, the body rows, a bottom rule. The
455
- * reference draws only the side rails, which reads as a table next to the
456
- * identity panel's rules; the rounds match the CLI's overlay frames.
457
- */
458
- function boxLines(t, header, rows, boxW) {
459
- const inner = Math.max(1, boxW - 4);
460
- // The top rule must be exactly `boxW` cells, like the body rows and the
461
- // bottom rule: `╭` + `─` + head + dashes + `╮`. Deriving the pad from
462
- // `inner + 2 - head.length` made the rule one cell too wide, so a full-width
463
- // pair of boxes overran the terminal by two columns and wrapped, shearing the
464
- // frame. The header is clipped rather than allowed to push the box open.
465
- const head = ` ${clip(header, Math.max(0, boxW - 4))} `;
466
- const top = [
467
- span(t.gray, '╭─'),
468
- span(t.gray + BOLD, head),
469
- span(t.gray, '─'.repeat(Math.max(0, boxW - 3 - head.length)) + '╮'),
470
- ];
471
- const out = [top];
472
- for (const r of rows) {
473
- const text = clip(String(r), inner);
474
- out.push([span(t.gray, '│ '), span(t.white, text + ' '.repeat(Math.max(0, inner - w(text)))), span(t.gray, ' │')]);
475
- }
476
- out.push([span(t.gray, '╰' + '─'.repeat(inner + 2) + '╯')]);
477
- return out;
478
- }
479
-
480
- /** The Tips + Models-and-keys boxes, side by side (stacked when too narrow). */
481
- function boxes(t, cols, avail) {
482
- const gap = 2;
483
- const twoUp = Math.floor((cols - gap) / 2);
484
- const tipRows = TIPS.map((s) => `${GLYPH.pointer}${s}`);
485
- const newsRows = KEY_HELP;
486
- // Name the running build in the header. The rows below are commands and
487
- // cannot go stale, but the header is the only place the screen says which
488
- // build is running, and it is derived from `VERSION` rather than typed — so
489
- // a user on a newer build is never reading notes written for an older one.
490
- const newsHead = `Models & keys · v${VERSION}`;
491
- if (twoUp >= 30) {
492
- let a = boxLines(t, 'Tips for getting started', tipRows, twoUp);
493
- let b = boxLines(t, newsHead, newsRows, twoUp);
494
- // Equalise the heights so both bottom rules land on the same row — boxes of
495
- // different heights leave a ragged pair of corners otherwise.
496
- const h = Math.max(a.length, b.length);
497
- const padBox = (box) => {
498
- if (box.length >= h) return box;
499
- const out = box.slice(0, box.length - 1);
500
- const blank = [span(t.gray, '│ '), span('', ' '.repeat(Math.max(0, twoUp - 4))), span(t.gray, ' │')];
501
- while (out.length < h - 1) out.push(blank);
502
- out.push(box[box.length - 1]);
503
- return out;
504
- };
505
- a = padBox(a);
506
- b = padBox(b);
507
- const out = [];
508
- for (let i = 0; i < h; i++) {
509
- out.push([...a[i], span('', ' '.repeat(gap)), ...b[i]]);
510
- }
511
- return out;
512
- }
513
- // Narrow: stack, so neither box is rendered at an unreadable width.
514
- const wd = Math.max(20, cols - 1);
515
- return [...boxLines(t, 'Tips for getting started', tipRows, wd), ...boxLines(t, newsHead, newsRows, wd)];
516
- }
517
-
518
- /**
519
- * Split a plain ANSI string back into the span model `paint` expects. Only the
520
- * SGR prefixes `render.artRow` emits are recognised, and every non-SGR run is
521
- * taken verbatim, so an unknown escape degrades to visible text rather than
522
- * being silently dropped.
523
- */
524
- function wrapPlain(s) {
525
- const out = [];
526
- const re = /\x1b\[[0-9;]*m/g;
527
- let last = 0;
528
- let style = '';
529
- let m;
530
- while ((m = re.exec(s)) !== null) {
531
- if (m.index > last) out.push(make(style, s.slice(last, m.index)));
532
- style = m[0];
533
- last = m.index + m[0].length;
534
- }
535
- if (last < s.length) out.push(make(style, s.slice(last)));
536
- return out;
537
- }
538
-
539
- function make(style, text) {
540
- const sp = span(style, text);
541
- if (style) {
542
- sp.s = style;
543
- sp.w = w(text);
544
- }
545
- return sp;
546
- }
547
-
548
- /**
549
- * Whether this machine holds a BYOK provider route of the user's own — the
550
- * desktop host's `providerRouteConfigured()`, ported here because the CLI's
551
- * `/byok-key <provider>` writes the exact same `byok:<provider>` row (see
552
- * `engine.js`'s `byokNamespace`) into the exact same settings.json, and
553
- * `connectNeeded()` below used to only ever check the AEGIS account key —
554
- * so a CLI user who did BYOK and never touched the account key got the
555
- * connect block re-pitched at them on every single launch.
556
- *
557
- * `settings.list()` goes through `get()`, which never puts a plaintext key on
558
- * a row (only the `configured` boolean already derived from it) — that field
559
- * is what a row counts on, not a `key` string that doesn't exist on it.
560
- *
561
- * Failure reads as "no configured route found", which keeps the block
562
- * visible — same fail-toward-showing-it bias as the account-key read below.
563
- */
564
- function providerRouteConfigured() {
565
- try {
566
- const store = createSettingsStore({ dir: credentials.aegisHome() });
567
- return store.list().some((row) => {
568
- if (!row || !row.provider || isReservedNamespace(row.provider)) return false;
569
- const baseURL = typeof row.baseURL === 'string' ? row.baseURL.trim() : '';
570
- return Boolean(row.configured || baseURL);
571
- });
572
- } catch {
573
- return false;
574
- }
575
- }
576
-
577
- /**
578
- * Whether ANY part of the connect block is still owed to this machine.
579
- *
580
- * It is the OR of the two route gates, and it is deliberately not the thing
581
- * `welcomeLines` branches on any more: the rows are composed one at a time by
582
- * `connectRows()`, so a machine that holds an AEGIS account key and no
583
- * provider route still gets the `/byok-key` row. This helper is the coarse
584
- * question ("is there anything left to say") — a caller that wants the rows
585
- * should ask `connectRows()` instead.
586
- *
587
- * A read that fails (no credentials file, an unreadable one) resolves to
588
- * "show it": the block is exactly what a user with no key needs, and a
589
- * failed status read must never be the reason a new install is told nothing
590
- * about how to start.
591
- */
592
- function connectNeeded() {
593
- try {
594
- return byokRouteNeeded() || cloudRouteNeeded();
595
- } catch {
596
- return true;
597
- }
598
- }
599
-
600
- /**
601
- * The two halves of the connect block, gated SEPARATELY — this is the fix.
602
- *
603
- * They used to share one gate that short-circuited on the account key, so a
604
- * user who redeemed an AEGIS key was never told BYOK exists at all: the row
605
- * naming `/byok-key` was retired at the exact moment they had an account and
606
- * were most likely to want a provider route of their own (unlimited/no relay
607
- * billing, a model the pool does not carry). An account key and a provider
608
- * route are not alternatives — `/byok-key` works alongside one — so the BYOK
609
- * row is now gated on the BYOK route alone and an AEGIS-key holder still
610
- * reads it. The Cloud row keeps the old account-key gate, because that is the
611
- * thing it pitches.
612
- *
613
- * Both reads fail toward SHOWING the row: a failed status read must never be
614
- * the reason a new install is told nothing about how to start.
615
- */
616
- function byokRouteNeeded() {
617
- try {
618
- return !providerRouteConfigured();
619
- } catch {
620
- return true;
621
- }
622
- }
623
-
624
- function cloudRouteNeeded() {
625
- try {
626
- return !credentials.keyStatus().configured;
627
- } catch {
628
- return true;
629
- }
630
- }
631
-
632
- /**
633
- * The welcome screen. Enter or Esc continues into the session; ctrl+c/d is the
634
- * user asking to leave, which is returned to the caller as `{ exit: true }`
635
- * rather than calling `process.exit` from here.
636
- */
637
- async function showWelcome(ctx, firstRun = true) {
638
- const renderScreen = () => {
639
- const { cols, rows } = getSize();
640
- paint(welcomeLines(ctx, cols, rows, firstRun));
641
- };
642
- renderScreen();
643
- for (;;) {
644
- const key = await nextKey();
645
- if (key.name === KEY.ENTER || key.name === KEY.ESC) return { exit: false };
646
- if (key.name === KEY.CTRL_C || key.name === KEY.CTRL_D) return { exit: true };
647
- }
648
- }
649
-
650
- // ── the account key ──────────────────────────────────────────────────────────
651
-
652
- // The key screen is the highest-intent moment in the CLI: the user pressed
653
- // Enter on a bare /key, so they have already decided they want an account.
654
- // The link is the short aegis1 deep link (see signup.js) — it lands on the
655
- // register panel with the key page queued behind it, which is the round trip
656
- // that used to be left to the user to figure out from the homepage.
657
- const KEY_URL = signupUrl('key_screen');
658
-
659
- /**
660
- * The key screen's lines. Pure, so what the user is told is asserted directly.
661
- *
662
- * `value` is echoed back as bullets: this is the one screen in the product
663
- * where the thing being typed is a secret, and a screen that echoes it would
664
- * put the key in a scrollback buffer, a screenshot and a screen share.
665
- */
666
- function keyLines(ctx, cols, { value = '', error = null, verify = false } = {}) {
667
- const t = themeOf(ctx);
668
- const lines = [];
669
- lines.push([span(t.gold, '─'.repeat(Math.max(1, cols)))]);
670
- lines.push([span(t.white + BOLD, 'Connect your AEGIS account')]);
671
- lines.push([span('', '')]);
672
- for (const l of wrapped(
673
- 'Paste an API key to use AEGIS Cloud. It is stored in your user config ' +
674
- 'directory with owner-only permissions, so later launches and scripts ' +
675
- 'pick it up without an export.',
676
- cols,
677
- t.white
678
- )) {
679
- lines.push(l);
680
- }
681
- // The link gets its own row whenever it would otherwise run past the edge:
682
- // a URL sheared across two lines is not typeable, and this is the one screen
683
- // where the user has nothing to copy it out of.
684
- lines.push([span('', '')]);
685
- const invite = ' No key yet? Free one at ';
686
- if (w(invite) + w(KEY_URL) + 2 <= cols) {
687
- lines.push([span(t.white, invite), span(t.cyan, KEY_URL)]);
688
- } else {
689
- lines.push([span(t.white, ' No key yet? Free one:')]);
690
- lines.push([span(t.cyan, ` ${KEY_URL}`)]);
691
- }
692
- lines.push([span('', '')]);
693
- lines.push([
694
- span(t.lavender, GLYPH.cursor),
695
- span(t.gray, ' API key: '),
696
- span(t.white, '•'.repeat(String(value).length)),
697
- span(verify ? t.cyan : t.gray, verify ? ' verifying…' : ''),
698
- ]);
699
- if (error) lines.push([span(t.coral, ` ${error}`)]);
700
- lines.push([span('', '')]);
701
- lines.push([
702
- span(t.gray, ` ${GLYPH.check} `),
703
- span(t.gray, 'Enter to save'),
704
- span(t.gray, ' · '),
705
- span(t.gray, 'Esc to skip'),
706
- ]);
707
- return lines;
708
- }
709
-
710
- /**
711
- * Ask for the account key. Resolves `{key}` when submitted, `{skipped:true}`
712
- * when the user declines, `{exit:true}` on ctrl+c.
713
- *
714
- * `submit(key)` is the caller's verification+persistence step; its rejection
715
- * message is shown on the screen and the user stays on it, because the failure
716
- * mode this prevents is a key that is accepted into the config while the
717
- * account behind it rejects every call.
718
- */
719
- async function requestApiKey(ctx, o = {}) {
720
- const submit = o.submit || (async () => ({ ok: true }));
721
- const { cols } = getSize();
722
- let value = '';
723
- let error = null;
724
- let verify = false;
725
- const paintScreen = () => paint(keyLines(ctx, cols, { value, error, verify }));
726
- paintScreen();
727
-
728
- for (;;) {
729
- const key = await nextKey();
730
- if (key.name === KEY.ENTER) {
731
- if (!value.trim()) return { skipped: true };
732
- verify = true;
733
- error = null;
734
- paintScreen();
735
- let res;
736
- try {
737
- res = await submit(value);
738
- } catch (e) {
739
- res = { ok: false, message: (e && e.message) || String(e) };
740
- }
741
- verify = false;
742
- if (res && res.ok === false) {
743
- error = res.message || 'that key was refused';
744
- paintScreen();
745
- continue;
746
- }
747
- return { key: value, result: res };
748
- }
749
- if (key.name === KEY.ESC) return { skipped: true };
750
- if (key.name === KEY.CTRL_C || key.name === KEY.CTRL_D) return { exit: true };
751
- if (key.name === KEY.BACKSPACE) {
752
- value = value.slice(0, -1);
753
- error = null;
754
- paintScreen();
755
- continue;
756
- }
757
- if (key.name === 'char') {
758
- const ch = key.ch;
759
- if (ch && ch >= ' ') {
760
- value += ch;
761
- error = null;
762
- paintScreen();
763
- }
764
- continue;
765
- }
766
- // A paste arrives as its own event (events.js rushes multi-char reads);
767
- // without this a pasted key is dropped on the floor.
768
- if (key.name === 'paste' && key.text) {
769
- value = (value + String(key.text)).replace(/\s+/g, '');
770
- error = null;
771
- paintScreen();
772
- }
773
- }
774
- }
775
-
776
- // ── the sequence ─────────────────────────────────────────────────────────────
777
-
778
- /**
779
- * Run the pre-session onboarding, exactly as the reference orders it.
780
- *
781
- * @param {object} ctx the shared command context (in: themeIndex, light)
782
- * @param {object} [o]
783
- * @param {boolean} [o.continue] skip onboarding (the reference's --continue)
784
- * @param {() => boolean} [o.seen] an explicit "has run before" probe; defaults
785
- * to the config file's existence
786
- * @param {(patch:object)=>void} [o.save] persist patch; defaults to updateConfig
787
- * @param {() => boolean} [o.needsKey] true when no account key is configured —
788
- * the key screen is shown only then
789
- * @param {(key:string)=>Promise<object>} [o.submitKey] verify + persist a key
790
- * @returns {Promise<{ok:boolean, firstRun:boolean, themeIndex:number,
791
- * key:{set:boolean, skipped:boolean}}>} `ok` is false when the user
792
- * declined the trust check or asked to exit.
793
- */
794
- async function runOnboarding(ctx, o = {}) {
795
- const seen = o.seen || configExists;
796
- const save = o.save || updateConfig;
797
- // Injectable so the *sequence* — which screens run, in what order, and what is
798
- // persisted — can be asserted without a terminal. The screens themselves are
799
- // tested directly through their pure line-builders.
800
- const ui = {
801
- showTrustCheck,
802
- showThemePicker,
803
- showWelcome,
804
- requestApiKey: (c, opts) =>
805
- requestApiKey(c, { submit: o.submitKey || (async () => ({ ok: true })), ...opts }),
806
- // An injected `ui` overrides the screens it names and inherits the rest, so
807
- // a caller testing the sequence does not have to supply a key screen it
808
- // never wants to exercise.
809
- ...(o.ui || {}),
810
- };
811
- // No key is the one state where the session cannot do anything at all, so it
812
- // is asked for in-band rather than left to a shell export the user has to
813
- // discover. Default reads the credential store so a caller that forgets to
814
- // pass it still gets the right behaviour.
815
- const needsKey = o.needsKey || (() => !credentials.hasApiKey());
816
- // …but only where a question can actually be asked. Without this a library
817
- // caller with no TTY reaches a screen that waits on a key queue nothing will
818
- // ever feed — a hang instead of a missing credential.
819
- const canPrompt = o.canPrompt || (() => !!(process.stdin && process.stdin.isTTY));
820
- // Declared out here because both the sequence and its key step report on it.
821
- const key = { set: false, skipped: false };
822
- if (o.continue) return { ok: true, firstRun: false, themeIndex: ctx.themeIndex, key: { set: false, skipped: false } };
823
-
824
- // Onboarding runs *before* the session loop, and the session loop is what
825
- // normally attaches the key pump — so without this the first screen paints and
826
- // then blocks forever on a key queue nothing feeds. Only attach if nobody
827
- // else has (the chatflow re-attaches for the session), and only ever detach
828
- // what we attached.
829
- const owns = !events.isKeyStreamAttached() && !!(process.stdin && process.stdin.isTTY);
830
- if (owns) events.attachKeyStream(process.stdin);
831
- try {
832
- return await runScreens();
833
- } finally {
834
- if (owns) events.detachKeyStream();
835
- }
836
-
837
- async function runScreens() {
838
- if (!seen()) {
839
- // Genuine first run: trust check, then the theme picker, then persist so
840
- // neither is ever shown again. Re-running this every launch greeted
841
- // returning users with "Let's get started." and discarded their session.
842
- const trusted = await ui.showTrustCheck(ctx);
843
- if (!trusted) return { ok: false, firstRun: true, themeIndex: ctx.themeIndex, key };
844
- await ui.showThemePicker(ctx);
845
- save({ themeIndex: ctx.themeIndex, light: ctx.light });
846
- if (await askKey()) return { ok: false, firstRun: true, themeIndex: ctx.themeIndex, key };
847
- const welcome = await ui.showWelcome(ctx, true);
848
- if (welcome && welcome.exit) return { ok: false, firstRun: true, themeIndex: ctx.themeIndex, key };
849
- return { ok: true, firstRun: true, themeIndex: ctx.themeIndex, key };
850
- }
851
-
852
- if (await askKey()) return { ok: false, firstRun: false, themeIndex: ctx.themeIndex, key };
853
- const welcome = await ui.showWelcome(ctx, false);
854
- if (welcome && welcome.exit) return { ok: false, firstRun: false, themeIndex: ctx.themeIndex, key };
855
- return { ok: true, firstRun: false, themeIndex: ctx.themeIndex, key };
856
- }
857
-
858
- /** @returns {Promise<boolean>} true when the user asked to exit. */
859
- async function askKey() {
860
- if (!needsKey() || !canPrompt()) return false;
861
- const res = await ui.requestApiKey(ctx);
862
- if (res && res.exit) return true;
863
- if (res && res.key) key.set = true;
864
- else key.skipped = true;
865
- return false;
866
- }
867
- }
868
-
869
- module.exports = {
870
- PRODUCT,
871
- TIPS,
872
- KEY_HELP,
873
- CONNECT_BYOK,
874
- CONNECT_CLOUD,
875
- CONNECT_BOTH,
876
- CONNECT_DESKTOP,
877
- connectRows,
878
- connectNeeded,
879
- byokRouteNeeded,
880
- cloudRouteNeeded,
881
- providerRouteConfigured,
882
- trustLines,
883
- themePickerLines,
884
- keyLines,
885
- applyTheme,
886
- welcomeLines,
887
- boxes,
888
- boxLines,
889
- centered,
890
- wrapped,
891
- wrapPlain,
892
- showTrustCheck,
893
- showThemePicker,
894
- requestApiKey,
895
- showWelcome,
896
- runOnboarding,
897
- KEY_URL,
898
- };
3
+ const{getSize:e,paint:t,span:r,lineWidth:n,clip:s,w:o}=require("./screen.js"),i=require("./events.js"),{nextKey:a,KEY:u}=i,{C:c,BOLD:h,BOLD_OFF:p,GLYPH:l,THEME_TABLE:m,themeOf:d,themeIsLight:f,terminalIsLight:y}=require("./theme.js"),{TAGLINE:g,TAGLINE_SHORT:k,welcomeArtParts:w}=require("./art.js"),{renderDiffPreview:x}=require("./markdown.js"),C=require("./render.js"),{updateConfig:T,configExists:E,loadConfig:I}=require("./config.js"),{updateNotice:S,updateLine:v,serverNotice:R,serverUpdateLine:L}=require("./update.js"),A=require("./credentials.js"),{signupUrl:N,signupDisplayUrl:b}=require("./signup.js"),{createSettingsStore:M,isReservedNamespace:P}=require("./deps.js"),_=require("../package.json").version,O="AEGIS Code",$=[" Run /init to create an AEGIS.md"," Use ↑↓ to recall past prompts"," Press / for commands"," Press Tab to complete a command"," Press ? for shortcuts"],j=[" Add a model: /model add"," <id> <name> <model> <url>"," Set a provider key: /byok-key"," <provider> — openai, anthropic"," Set your account key: /key <key>"," Switch model: /model, or alt+p"," Reasoning effort: /effort"," All commands: press / for the list"],K=["Your own provider key: /byok-key <provider> — works with your AEGIS key"],q=["AEGIS Cloud, one account key: /key — no provider signup"],D=["Your key, your bill: /byok-key <provider> — or AEGIS Cloud, /key"],G=[`AEGIS Desktop: same engine on your machine — ${b()}`];function U(){const e=[],t=re(),r=ne();return t&&r?e.push(...D):t?e.push(...K):r&&e.push(...q),e.length&&e.push(...G),e}function W(e,t,n){const i=s(String(e),Math.max(1,t)),a=Math.max(0,Math.floor((t-o(i))/2));return[r(""," ".repeat(a)),r(n,i)]}function Y(e,t,n,s=0){const i=String(e).split(" "),a=[];let u=[],c=0;for(const e of i)c+o(e)+1>t-4-s&&u.length?(a.push([r(""," ".repeat(s)),r(n,u.join(" "))]),u=[e],c=o(e)):(u.length&&c++,u.push(e),c+=o(e));return u.length&&a.push([r(""," ".repeat(s)),r(n,u.join(" "))]),a}function B(e,t,n=0,o=process.cwd()){const i=[];i.push([r(c.gold,"─".repeat(Math.max(1,t)))]),i.push([r(c.white+h,"Accessing workspace:")]),i.push([r(c.white+h,s(o,Math.max(1,t-1)))]),i.push([r("","")]);for(const e of Y("Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team). If not, take a moment to review what's in this folder first.",t,c.white))i.push(e);i.push([r("","")]),i.push([r(c.white,`${O} will be able to read, edit, and execute files here.`)]),i.push([r("","")]),i.push([r(c.white+h,"Security guide")]),i.push([r("","")]);for(let e=0;e<2;e++){const t=n===e,s=t?r(c.lavender,l.cursor):r(""," "),o=r(c.gray,` ${e+1}.`),a=0===e?"Yes, I trust this folder":"No, exit";i.push([s,o,r(t?c.lavender:c.white,a)])}return i.push([r("","")]),i.push([r(c.gray,`Enter to confirm ${l.bullet} Esc to cancel`)]),i}async function H(r){const{cols:n}=e();let s=0;const o=()=>t(B(0,n,s));for(o();;){const e=await a();if(e.name===u.UP||e.name===u.DOWN||e.name===u.TAB)s=1-s,o();else{if(e.name===u.ENTER)return 0===s;if(e.name===u.ESC||e.name===u.CTRL_C||e.name===u.CTRL_D)return!1;if("char"===e.name){const t=String(e.ch).trim();"1"===t&&(s=0,o()),"2"===t&&(s=1,o())}}}}function F(e,t){return m[t]||m[1],e.themeIndex=t,e.light=f(t),t}function z(e,t,n,s){const o=[];o.push([r(c.coral,`Welcome to ${O} v${_}`)]),o.push([r(c.white+h,"Let's get started.")]),o.push([r(c.white,"Choose the text style that looks best with your terminal")]),o.push([r(c.gray,"To change this later, run /theme")]),o.push([r("","")]);for(let e=0;e<m.length;e++){const t=m[e],n=s===e,i=n?r(c.lavender,l.cursor):r(""," "),a=r(c.gray,`${e+1}.`),u=n?r(c.green," "+l.check):r("","");o.push([i,a,r(n?c.lavender:c.white,t.name),...t.note?[r(c.gray," "+t.note)]:[],u])}for(const r of x(t,e))o.push(r);for(o.push([r(c.gray," Syntax theme: Monokai Extended (ctrl+t to disable)")]);o.length<n-1;)o.push([r("","")]);return o}async function Q(r,n=`Welcome to ${O}`){const{cols:s,rows:o}=e();let i="number"==typeof r.themeIndex?r.themeIndex:y()?2:1;const c=()=>t(z(r,s,o,i));for(c();;){const e=await a();if(e.name===u.UP)i=Math.max(0,i-1),c();else if(e.name===u.DOWN)i=Math.min(m.length-1,i+1),c();else{if(e.name===u.ENTER||e.name===u.ESC||e.name===u.CTRL_C||e.name===u.CTRL_D)return F(r,i);if(e.name===u.CTRL_T)r.light=!r.light,c();else if("char"===e.name){const t=parseInt(e.ch,10);t>=1&&t<=m.length&&(i=t-1,c())}}}}function J(e,t,n,s=!0){const i=d(e),a=[];a.push([r(i.gold,"━"+"─".repeat(Math.max(0,t-2))+"━")]),a.push([r("","")]);let u=null;try{const e=I(),t=S({current:_,cache:e.updateCheck,save:e=>{try{T({updateCheck:e})}catch{}}});u=v({current:_,...t});const r=R({current:_,cache:e.updateCheckServer,save:e=>{try{T({updateCheckServer:e})}catch{}}});u=L(r)||u}catch{}const c=w();if(t>=c.width+2){const r=Math.max(0,Math.floor((t-c.width)/2));for(const t of c.rows)a.push(Z(C.artRow(e,t,c,r)))}else a.push(W(`${O}`,t,i.gold+h));u&&(a.push([r("","")]),a.push(W(u,t,i.gold))),a.push([r("","")]);const p=s?`Welcome to ${O}`:"Welcome back!";a.push(W(p,t,i.coral+h));const m=t>=o(g)+4?g:k;a.push(W(m,t,i.gray)),a.push([r("","")]),a.push(...X(i,t,a.length)),a.push([r("","")]);for(const e of U())a.push(...Y(e,t,i.white,1));for(a.push([r(i.gray,l.hint),r(i.white,' Try "write a test for <filepath>"')]);a.length<n-1;)a.push([r("","")]);return a}function V(e,t,n,i){const a=Math.max(1,i-4),u=` ${s(t,Math.max(0,i-4))} `,c=[[r(e.gray,"╭─"),r(e.gray+h,u),r(e.gray,"─".repeat(Math.max(0,i-3-u.length))+"╮")]];for(const t of n){const n=s(String(t),a);c.push([r(e.gray,"│ "),r(e.white,n+" ".repeat(Math.max(0,a-o(n)))),r(e.gray," │")])}return c.push([r(e.gray,"╰"+"─".repeat(a+2)+"╯")]),c}function X(e,t,n){const s=Math.floor((t-2)/2),o=$.map((e=>`${l.pointer}${e}`)),i=j,a=`Models & keys · v${_}`;if(s>=30){let t=V(e,"Tips for getting started",o,s),n=V(e,a,i,s);const u=Math.max(t.length,n.length),c=t=>{if(t.length>=u)return t;const n=t.slice(0,t.length-1),o=[r(e.gray,"│ "),r(""," ".repeat(Math.max(0,s-4))),r(e.gray," │")];for(;n.length<u-1;)n.push(o);return n.push(t[t.length-1]),n};t=c(t),n=c(n);const h=[];for(let e=0;e<u;e++)h.push([...t[e],r(""," ".repeat(2)),...n[e]]);return h}const u=Math.max(20,t-1);return[...V(e,"Tips for getting started",o,u),...V(e,a,i,u)]}function Z(e){const t=[],r=/\x1b\[[0-9;]*m/g;let n,s=0,o="";for(;null!==(n=r.exec(e));)n.index>s&&t.push(ee(o,e.slice(s,n.index))),o=n[0],s=n.index+n[0].length;return s<e.length&&t.push(ee(o,e.slice(s))),t}function ee(e,t){const n=r(e,t);return e&&(n.s=e,n.w=o(t)),n}function te(){try{return M({dir:A.aegisHome()}).list().some((e=>{if(!e||!e.provider||P(e.provider))return!1;const t="string"==typeof e.baseURL?e.baseURL.trim():"";return Boolean(e.configured||t)}))}catch{return!1}}function re(){try{return!te()}catch{return!0}}function ne(){try{return!A.keyStatus().configured}catch{return!0}}async function se(r,n=!0){for((()=>{const{cols:s,rows:o}=e();t(J(r,s,o,n))})();;){const e=await a();if(e.name===u.ENTER||e.name===u.ESC)return{exit:!1};if(e.name===u.CTRL_C||e.name===u.CTRL_D)return{exit:!0}}}const oe=N("key_screen");function ie(e,t,{value:n="",error:s=null,verify:i=!1}={}){const a=d(e),u=[];u.push([r(a.gold,"─".repeat(Math.max(1,t)))]),u.push([r(a.white+h,"Connect your AEGIS account")]),u.push([r("","")]);for(const e of Y("Paste an API key to use AEGIS Cloud. It is stored in your user config directory with owner-only permissions, so later launches and scripts pick it up without an export.",t,a.white))u.push(e);u.push([r("","")]);const c=" No key yet? Free one at ";return o(c)+o(oe)+2<=t?u.push([r(a.white,c),r(a.cyan,oe)]):(u.push([r(a.white," No key yet? Free one:")]),u.push([r(a.cyan,` ${oe}`)])),u.push([r("","")]),u.push([r(a.lavender,l.cursor),r(a.gray," API key: "),r(a.white,"•".repeat(String(n).length)),r(i?a.cyan:a.gray,i?" verifying…":"")]),s&&u.push([r(a.coral,` ${s}`)]),u.push([r("","")]),u.push([r(a.gray,` ${l.check} `),r(a.gray,"Enter to save"),r(a.gray," · "),r(a.gray,"Esc to skip")]),u}async function ae(r,n={}){const s=n.submit||(async()=>({ok:!0})),{cols:o}=e();let i="",c=null,h=!1;const p=()=>t(ie(r,o,{value:i,error:c,verify:h}));for(p();;){const e=await a();if(e.name===u.ENTER){if(!i.trim())return{skipped:!0};let e;h=!0,c=null,p();try{e=await s(i)}catch(t){e={ok:!1,message:t&&t.message||String(t)}}if(h=!1,e&&!1===e.ok){c=e.message||"that key was refused",p();continue}return{key:i,result:e}}if(e.name===u.ESC)return{skipped:!0};if(e.name===u.CTRL_C||e.name===u.CTRL_D)return{exit:!0};if(e.name!==u.BACKSPACE)if("char"!==e.name)"paste"===e.name&&e.text&&(i=(i+String(e.text)).replace(/\s+/g,""),c=null,p());else{const t=e.ch;t&&t>=" "&&(i+=t,c=null,p())}else i=i.slice(0,-1),c=null,p()}}module.exports={PRODUCT:O,TIPS:$,KEY_HELP:j,CONNECT_BYOK:K,CONNECT_CLOUD:q,CONNECT_BOTH:D,CONNECT_DESKTOP:G,connectRows:U,connectNeeded:function(){try{return re()||ne()}catch{return!0}},byokRouteNeeded:re,cloudRouteNeeded:ne,providerRouteConfigured:te,trustLines:B,themePickerLines:z,keyLines:ie,applyTheme:F,welcomeLines:J,boxes:X,boxLines:V,centered:W,wrapped:Y,wrapPlain:Z,showTrustCheck:H,showThemePicker:Q,requestApiKey:ae,showWelcome:se,runOnboarding:async function(e,t={}){const r=t.seen||E,n=t.save||T,s={showTrustCheck:H,showThemePicker:Q,showWelcome:se,requestApiKey:(e,r)=>ae(e,{submit:t.submitKey||(async()=>({ok:!0})),...r}),...t.ui||{}},o=t.needsKey||(()=>!A.hasApiKey()),a=t.canPrompt||(()=>!(!process.stdin||!process.stdin.isTTY)),u={set:!1,skipped:!1};if(t.continue)return{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:{set:!1,skipped:!1}};const c=!i.isKeyStreamAttached()&&!(!process.stdin||!process.stdin.isTTY);c&&i.attachKeyStream(process.stdin);try{return await async function(){if(!r()){if(!await s.showTrustCheck(e))return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:u};if(await s.showThemePicker(e),n({themeIndex:e.themeIndex,light:e.light}),await h())return{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:u};const t=await s.showWelcome(e,!0);return t&&t.exit?{ok:!1,firstRun:!0,themeIndex:e.themeIndex,key:u}:{ok:!0,firstRun:!0,themeIndex:e.themeIndex,key:u}}if(await h())return{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:u};const t=await s.showWelcome(e,!1);return t&&t.exit?{ok:!1,firstRun:!1,themeIndex:e.themeIndex,key:u}:{ok:!0,firstRun:!1,themeIndex:e.themeIndex,key:u}}()}finally{c&&i.detachKeyStream()}async function h(){if(!o()||!a())return!1;const t=await s.requestApiKey(e);return!(!t||!t.exit)||(t&&t.key?u.set=!0:u.skipped=!0,!1)}},KEY_URL:oe};