@osdlc/wayfinder 0.7.4 → 0.8.0

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 (121) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/CONTRIBUTING.md +6 -0
  3. package/README.md +295 -150
  4. package/SECURITY.md +19 -5
  5. package/dist/actions.d.ts +23 -0
  6. package/dist/actions.js +97 -0
  7. package/dist/app.d.ts +1 -13
  8. package/dist/app.js +1 -13
  9. package/dist/args.d.ts +11 -6
  10. package/dist/args.js +25 -7
  11. package/dist/cache.d.ts +2 -4
  12. package/dist/cache.js +5 -10
  13. package/dist/catalog.d.ts +30 -3
  14. package/dist/catalog.js +87 -11
  15. package/dist/clean-command.d.ts +65 -36
  16. package/dist/clean-command.js +372 -226
  17. package/dist/cli.d.ts +24 -57
  18. package/dist/cli.js +139 -568
  19. package/dist/commands/browse.d.ts +128 -0
  20. package/dist/commands/browse.js +151 -0
  21. package/dist/commands/index.d.ts +25 -0
  22. package/dist/commands/index.js +71 -0
  23. package/dist/commands/list.d.ts +208 -0
  24. package/dist/commands/list.js +127 -0
  25. package/dist/commands/query.d.ts +166 -0
  26. package/dist/commands/query.js +73 -0
  27. package/dist/commands/run.d.ts +114 -0
  28. package/dist/commands/run.js +139 -0
  29. package/dist/commands/shared.d.ts +152 -0
  30. package/dist/commands/shared.js +209 -0
  31. package/dist/config-command.d.ts +27 -43
  32. package/dist/config-command.js +129 -330
  33. package/dist/config-keys.d.ts +25 -0
  34. package/dist/config-keys.js +29 -0
  35. package/dist/config.d.ts +271 -257
  36. package/dist/config.js +610 -460
  37. package/dist/core/copy-text.d.ts +30 -0
  38. package/dist/core/copy-text.js +50 -0
  39. package/dist/core/filter.d.ts +55 -0
  40. package/dist/core/filter.js +59 -0
  41. package/dist/core/run.d.ts +22 -0
  42. package/dist/core/run.js +59 -0
  43. package/dist/core/saved-view.d.ts +59 -0
  44. package/dist/core/saved-view.js +119 -0
  45. package/dist/core/session.d.ts +262 -0
  46. package/dist/core/session.js +589 -0
  47. package/dist/core/skills.d.ts +53 -0
  48. package/dist/core/skills.js +54 -0
  49. package/dist/core/unknowns.d.ts +72 -0
  50. package/dist/core/unknowns.js +68 -0
  51. package/dist/devlink.d.ts +3 -0
  52. package/dist/devlink.js +5 -2
  53. package/dist/document-schemas.generated.d.ts +22 -0
  54. package/dist/document-schemas.generated.js +916 -0
  55. package/dist/documents.d.ts +432 -0
  56. package/dist/documents.js +163 -0
  57. package/dist/groups.d.ts +22 -26
  58. package/dist/groups.js +13 -29
  59. package/dist/guide.d.ts +26 -13
  60. package/dist/guide.js +119 -103
  61. package/dist/index.d.ts +112 -0
  62. package/dist/index.js +58 -0
  63. package/dist/keys.d.ts +51 -0
  64. package/dist/keys.js +273 -0
  65. package/dist/page.d.ts +18 -8
  66. package/dist/page.js +28 -17
  67. package/dist/providers-command.d.ts +81 -20
  68. package/dist/providers-command.js +33 -75
  69. package/dist/schema.d.ts +48 -0
  70. package/dist/schema.js +61 -0
  71. package/dist/serve/auth.d.ts +46 -0
  72. package/dist/serve/auth.js +82 -0
  73. package/dist/serve/catalog-share.d.ts +51 -0
  74. package/dist/serve/catalog-share.js +116 -0
  75. package/dist/serve/index.d.ts +98 -0
  76. package/dist/serve/index.js +251 -0
  77. package/dist/serve/routes.d.ts +60 -0
  78. package/dist/serve/routes.js +186 -0
  79. package/dist/serve/terminal-input.d.ts +50 -0
  80. package/dist/serve/terminal-input.js +108 -0
  81. package/dist/skills.d.ts +19 -0
  82. package/dist/skills.js +54 -0
  83. package/dist/terminal-text.d.ts +8 -0
  84. package/dist/terminal-text.js +19 -6
  85. package/dist/tool-info.d.ts +24 -0
  86. package/dist/tool-info.js +17 -0
  87. package/dist/trust-command.d.ts +15 -27
  88. package/dist/trust-command.js +110 -208
  89. package/dist/trust-store.d.ts +5 -10
  90. package/dist/trust-store.js +9 -42
  91. package/dist/tui/app.d.ts +180 -0
  92. package/dist/tui/app.js +1278 -0
  93. package/dist/tui/copy.d.ts +29 -0
  94. package/dist/tui/copy.js +39 -0
  95. package/dist/tui/index.d.ts +33 -0
  96. package/dist/tui/index.js +97 -0
  97. package/dist/tui/keys-input.d.ts +27 -0
  98. package/dist/tui/keys-input.js +87 -0
  99. package/dist/tui/settings.d.ts +94 -0
  100. package/dist/tui/settings.js +198 -0
  101. package/dist/tui/style.d.ts +62 -0
  102. package/dist/tui/style.js +77 -0
  103. package/dist/version.d.ts +6 -0
  104. package/dist/version.js +7 -0
  105. package/dist/vocabulary.d.ts +89 -0
  106. package/dist/vocabulary.js +153 -0
  107. package/dist/web/main.js +1965 -568
  108. package/dist/web/page.html +39 -33
  109. package/dist/web/styles.css +457 -329
  110. package/dist/xdg.d.ts +76 -4
  111. package/dist/xdg.js +77 -5
  112. package/package.json +28 -9
  113. package/schema/config.json +133 -0
  114. package/dist/http.d.ts +0 -22
  115. package/dist/http.js +0 -149
  116. package/dist/origin-owner.d.ts +0 -19
  117. package/dist/origin-owner.js +0 -85
  118. package/dist/serve.d.ts +0 -98
  119. package/dist/serve.js +0 -671
  120. package/dist/tui.d.ts +0 -177
  121. package/dist/tui.js +0 -840
@@ -0,0 +1,1278 @@
1
+ /**
2
+ * The terminal UI as an object: its state, the frame it draws and the keys it
3
+ * answers. `createTui` makes one over a {@link Session} and a {@link TuiHost};
4
+ * `runTui` in `./index.ts` gives it a real terminal. Tests give it a fake
5
+ * host, so every key and every frame can be checked without a terminal.
6
+ *
7
+ * Collection is async, which is what much of the state handling is for: keys
8
+ * arrive during a refresh, and a row can be stale.
9
+ */
10
+ import { commandString } from '@osdlc/command-seam';
11
+ import { humanAge, humanMs } from '@osdlc/system-model/duration';
12
+ import { paramShape } from '@osdlc/system-model/params';
13
+ import { fitWidth } from '@osdlc/ux';
14
+ import { BIN } from "../app.js";
15
+ import { splitArgs } from "../args.js";
16
+ import { orderedCatalog } from "../catalog.js";
17
+ import { COPY_REFUSED, skillCopyText, taskCopyText } from "../core/copy-text.js";
18
+ import { SessionError } from "../core/session.js";
19
+ import { skillLine } from "../core/skills.js";
20
+ import { groupOf, SKILLS_GROUP } from "../groups.js";
21
+ import { footerHints, keyLines, keysFor } from "../keys.js";
22
+ import { terminalSafe } from "../terminal-text.js";
23
+ import { countRunners, displayPath, parametersUnknownLabel, probeTimeLabel, runnerLabel, withheldLabel, } from "../vocabulary.js";
24
+ import { isText, namedKey, splitKeys } from "./keys-input.js";
25
+ import { cycleDiscovery, editPaths, execOffCause, moveRunner, settingsLines, toggleRunner, } from "./settings.js";
26
+ import { CLEAR_EOL, chunksWidth, line } from "./style.js";
27
+ /** The scopes `^o` cycles through, as the web view's Scope buttons. */
28
+ export const SCOPES = [
29
+ { label: 'all', maxDepth: undefined },
30
+ { label: 'root', maxDepth: 0 },
31
+ { label: '+2', maxDepth: 2 },
32
+ { label: '+3', maxDepth: 3 },
33
+ ];
34
+ /** The `all` tab. */
35
+ export const ALL = 'all';
36
+ /**
37
+ * The Skills tab. Its rows are agent skills, not a runner's tasks. The `#`
38
+ * keeps it apart from any runner id.
39
+ */
40
+ export const SKILLS_TAB = `#${SKILLS_GROUP.id}`;
41
+ /**
42
+ * `text` wrapped at word breaks to `width` columns. Each later line is
43
+ * indented to where the text after a key column starts (the first run of two
44
+ * spaces after the first word), so a key's action lines up under itself.
45
+ */
46
+ export function wrapHanging(text, width) {
47
+ if (text.length <= width || width < 20)
48
+ return [text];
49
+ const column = /^(\s*\S+(?: \S+)*?\s{2,})/.exec(text)?.[1]?.length;
50
+ const hang = ' '.repeat(Math.min(column ?? /^\s*/.exec(text)[0].length, Math.floor(width / 2)));
51
+ const out = [];
52
+ let rest = text;
53
+ while (rest.length > width) {
54
+ let cut = rest.lastIndexOf(' ', width);
55
+ if (cut <= hang.length)
56
+ cut = width;
57
+ out.push(rest.slice(0, cut).trimEnd());
58
+ rest = hang + rest.slice(cut).trimStart();
59
+ }
60
+ out.push(rest);
61
+ return out;
62
+ }
63
+ /**
64
+ * What the status line says about stale rows, in three states. Fresh says
65
+ * nothing. Stale and measured slow is kept apart from ordinary stale,
66
+ * because it is the case the store exists for.
67
+ */
68
+ export function refreshNote(rows, loading) {
69
+ const stale = rows.filter((r) => r.state === 'stale');
70
+ if (stale.length === 0)
71
+ return null;
72
+ const named = (r) => r.estimateMs === null
73
+ ? `${runnerLabel(r.runner)} (never timed here)`
74
+ : `${runnerLabel(r.runner)} (~${humanMs(r.estimateMs)})`;
75
+ const slow = stale.filter((r) => r.slow);
76
+ if (!loading) {
77
+ // The refresh is over and these rows are still what the store held.
78
+ return {
79
+ slow: slow.length > 0,
80
+ text: `cached rows: ${stale.map((r) => `${runnerLabel(r.runner)} ${humanAge(r.ageMs)}`).join(', ')} — ^r to re-probe`,
81
+ };
82
+ }
83
+ if (slow.length > 0) {
84
+ const rest = stale.filter((r) => !slow.includes(r));
85
+ return {
86
+ slow: true,
87
+ text: `cached rows — ${slow.map(named).join(', ')} ` +
88
+ `${slow.length === 1 ? 'is' : 'are'} slow to probe here, so this takes a moment` +
89
+ (rest.length > 0 ? `; also re-probing ${rest.map(named).join(', ')}` : ''),
90
+ };
91
+ }
92
+ return { slow: false, text: `cached rows — re-probing ${stale.map(named).join(', ')}` };
93
+ }
94
+ const HOME = '\x1b[H';
95
+ const CLEAR_BELOW = '\x1b[J';
96
+ /** The one separator line character. */
97
+ const RULE = '─';
98
+ const errorText = (err) => (err instanceof Error ? err.message : String(err));
99
+ /** Make a terminal UI. Nothing is drawn or probed until {@link Tui.boot}. */
100
+ export function createTui({ session, host, styles: s }) {
101
+ /** `argv` quoted for the shell, as the CLI prints the run line. */
102
+ const commandLine = (argv) => commandString(argv, { platform: host.platform });
103
+ const state = {
104
+ catalog: null,
105
+ cache: [],
106
+ skills: [],
107
+ runnerOrder: session.runnerOrder(),
108
+ probed: false,
109
+ fromProbe: false,
110
+ runner: ALL,
111
+ query: '',
112
+ mode: 'fuzzy',
113
+ servicesOnly: false,
114
+ declaredOnly: false,
115
+ scope: 0,
116
+ selectedId: null,
117
+ scroll: 0,
118
+ message: null,
119
+ loading: false,
120
+ confirmingTrust: false,
121
+ trustScope: null,
122
+ entering: null,
123
+ view: 'list',
124
+ helpFrom: 'list',
125
+ helpScroll: 0,
126
+ settings: null,
127
+ revoked: false,
128
+ generation: 0,
129
+ inFlight: null,
130
+ rows: [],
131
+ skillRows: [],
132
+ };
133
+ const pending = new Set();
134
+ const track = (work) => {
135
+ const p = work
136
+ .catch((err) => say(errorText(err), 'error'))
137
+ .finally(() => {
138
+ pending.delete(p);
139
+ draw();
140
+ });
141
+ pending.add(p);
142
+ };
143
+ const say = (text, tone = 'note') => {
144
+ state.message = { text, tone };
145
+ };
146
+ // ------------------------------------------------------------ the catalog
147
+ const reports = () => state.catalog?.reports ?? [];
148
+ const reportFor = (runner) => reports().find((r) => r.runner === runner);
149
+ const tabs = () => [
150
+ ALL,
151
+ ...reports().map((r) => r.runner),
152
+ ...(state.skills.length > 0 ? [SKILLS_TAB] : []),
153
+ ];
154
+ const showsSkills = () => state.runner === ALL || state.runner === SKILLS_TAB;
155
+ const cacheFor = (runner) => state.cache.find((c) => c.runner === runner);
156
+ const chainOf = (runner) => reportFor(runner)?.chain ?? [];
157
+ /** Each withheld runner, with its label and the scopes it needs. */
158
+ const withheldRunners = () => state.catalog === null
159
+ ? []
160
+ : session
161
+ .unknowns({ catalog: state.catalog, cache: state.cache })
162
+ .filter((u) => u.kind === 'withheld');
163
+ /** The withheld runners, and why, or null when execution is allowed. */
164
+ const withheld = () => {
165
+ const reason = session.withheldReason();
166
+ const held = withheldRunners();
167
+ if (reason === null || held.length === 0)
168
+ return null;
169
+ let cause;
170
+ if (reason === 'exec-off') {
171
+ cause = `withheld: ${execOffCause(session.settings().settings, session.gate)}`;
172
+ }
173
+ else if (held.some((w) => w.reason === 'tool-untrusted')) {
174
+ const missing = [...new Set(held.flatMap((w) => w.missing ?? []))];
175
+ cause = withheldLabel('tool-untrusted', missing);
176
+ }
177
+ else {
178
+ cause = withheldLabel('untrusted');
179
+ }
180
+ return { count: held.length, cause, trustable: session.trustable() };
181
+ };
182
+ const tabTasks = () => state.runner === ALL
183
+ ? reports().flatMap((r) => r.tasks)
184
+ : (reportFor(state.runner)?.tasks ?? []);
185
+ /** How many rows the selected tab has before filtering. */
186
+ const tabTotal = () => tabTasks().length + (showsSkills() ? state.skills.length : 0);
187
+ const entries = () => [
188
+ ...state.rows.map((task) => ({ task })),
189
+ ...state.skillRows.map((skill) => ({ skill })),
190
+ ];
191
+ const entryId = (e) => e === undefined ? null : e.task !== undefined ? e.task.task.id : e.skill.skill.id;
192
+ function recompute() {
193
+ const filter = {
194
+ query: state.query,
195
+ mode: state.mode,
196
+ servicesOnly: state.servicesOnly,
197
+ declaredOnly: state.declaredOnly,
198
+ maxDepth: SCOPES[state.scope].maxDepth,
199
+ };
200
+ if (state.catalog === null || state.runner === SKILLS_TAB) {
201
+ state.rows = [];
202
+ }
203
+ else {
204
+ const scoped = state.runner === ALL ? reports() : reports().filter((r) => r.runner === state.runner);
205
+ state.rows = session.search({ ...state.catalog, reports: scoped }, filter);
206
+ }
207
+ state.skillRows = showsSkills() ? session.searchSkills(state.skills, filter) : [];
208
+ const all = entries();
209
+ if (state.selectedId !== null && !all.some((e) => entryId(e) === state.selectedId)) {
210
+ state.selectedId = entryId(all[0]);
211
+ }
212
+ }
213
+ function cursor() {
214
+ if (state.selectedId === null)
215
+ return 0;
216
+ const at = entries().findIndex((e) => entryId(e) === state.selectedId);
217
+ return at === -1 ? 0 : at;
218
+ }
219
+ function select(index) {
220
+ const all = entries();
221
+ const clamped = Math.max(0, Math.min(index, all.length - 1));
222
+ state.selectedId = entryId(all[clamped]);
223
+ }
224
+ const resetSelection = () => {
225
+ state.selectedId = null;
226
+ state.scroll = 0;
227
+ };
228
+ // ---------------------------------------------------------------- render
229
+ /** The chain, dimmed except for the leaf, with matched characters marked. */
230
+ function chainChunks(row) {
231
+ const { path } = row.task;
232
+ const shown = displayPath(path, row.task.runner);
233
+ const marks = new Set(row.labelHits ?? []);
234
+ const chunks = [];
235
+ let at = 0;
236
+ for (let p = 0; p < path.length; p++) {
237
+ const leaf = p === path.length - 1;
238
+ const plain = leaf ? s.bold : s.dim;
239
+ if (shown[p] !== path[p]) {
240
+ // A runner id shown as its label: the marks index the id, so none apply.
241
+ chunks.push({ text: shown[p], paint: plain });
242
+ at += path[p].length;
243
+ if (!leaf) {
244
+ chunks.push({ text: ' > ', paint: s.dim });
245
+ at++;
246
+ }
247
+ continue;
248
+ }
249
+ let run = '';
250
+ let marked = marks.has(at);
251
+ for (const ch of path[p]) {
252
+ const on = marks.has(at);
253
+ if (on !== marked) {
254
+ chunks.push({ text: run, paint: marked ? s.match : plain });
255
+ run = '';
256
+ marked = on;
257
+ }
258
+ run += ch;
259
+ at++;
260
+ }
261
+ if (run)
262
+ chunks.push({ text: run, paint: marked ? s.match : plain });
263
+ if (!leaf) {
264
+ chunks.push({ text: ' > ', paint: s.dim });
265
+ at++; // the " " the label was joined on
266
+ }
267
+ }
268
+ return chunks;
269
+ }
270
+ /**
271
+ * A skill's line, `/name [hint]`, with matched name characters marked and
272
+ * its origin dimmed after it. Skill text is repository text, so it is
273
+ * filtered; `terminalSafe` keeps its length, so the offsets still fit.
274
+ */
275
+ function skillChunks(hit) {
276
+ const marks = new Set((hit.labelHits ?? []).map((i) => i + 1)); // after the `/`
277
+ const text = terminalSafe(skillLine(hit.skill));
278
+ const nameEnd = hit.skill.invoke.length;
279
+ const paintAt = (i) => (marks.has(i) ? s.match : i < nameEnd ? s.bold : undefined);
280
+ const chunks = [];
281
+ let from = 0;
282
+ for (let i = 1; i <= text.length; i++) {
283
+ if (i === text.length || paintAt(i) !== paintAt(from)) {
284
+ chunks.push({ text: text.slice(from, i), paint: paintAt(from) });
285
+ from = i;
286
+ }
287
+ }
288
+ chunks.push({ text: ` ${terminalSafe(hit.skill.origin)}`, paint: s.dim });
289
+ return chunks;
290
+ }
291
+ /**
292
+ * The tab row: each tab's chunks, scrolled so the selected tab is in view,
293
+ * with `‹` and `›` where tabs are cut off. The mode flags keep their room
294
+ * at the right.
295
+ */
296
+ function tabRow(width) {
297
+ const names = tabs();
298
+ const segments = names.map((name, i) => {
299
+ const count = name === ALL
300
+ ? reports().reduce((n, r) => n + r.tasks.length, 0) + state.skills.length
301
+ : name === SKILLS_TAB
302
+ ? state.skills.length
303
+ : (reportFor(name)?.tasks.length ?? 0);
304
+ // A leading `~` marks rows from the store that are out of date. A `–`
305
+ // in place of the count marks a withheld runner. Both show without color.
306
+ const stale = name === ALL
307
+ ? state.cache.some((c) => c.state === 'stale')
308
+ : cacheFor(name)?.state === 'stale';
309
+ const held = name !== ALL && reportFor(name)?.skippedForExec === true;
310
+ const title = name === ALL ? ALL : name === SKILLS_TAB ? SKILLS_GROUP.id : runnerLabel(name);
311
+ const label = `${stale ? '~' : ''}${title} ${held ? '–' : count}`;
312
+ const selected = name === state.runner;
313
+ const chunks = [];
314
+ const prev = names[i - 1];
315
+ const newGroup = name === SKILLS_TAB || groupOf(prev ?? ALL) !== groupOf(name);
316
+ if (name !== ALL && prev !== undefined && prev !== ALL && newGroup) {
317
+ chunks.push({ text: '│', paint: s.dim });
318
+ }
319
+ // Brackets mark the selected tab in the same width as the spaces
320
+ // around the others, so it shows without color or inverse.
321
+ chunks.push({
322
+ text: selected ? `[${label}]` : ` ${label} `,
323
+ paint: selected ? s.selected : stale || held ? s.warning : s.dim,
324
+ });
325
+ return chunks;
326
+ });
327
+ const scope = SCOPES[state.scope];
328
+ const flags = [
329
+ state.mode,
330
+ ...(state.servicesOnly ? ['services'] : []),
331
+ ...(state.declaredOnly ? ['declared'] : []),
332
+ ...(scope.maxDepth !== undefined ? [`scope ${scope.label}`] : []),
333
+ ...(state.catalog?.allowExec ? ['exec'] : []),
334
+ ].join(' ');
335
+ const room = Math.max(1, width - flags.length - 1);
336
+ const widths = segments.map((c) => chunksWidth(c));
337
+ const span = (from, to) => widths.slice(from, to + 1).reduce((a, b) => a + b, 0) +
338
+ (from > 0 ? 1 : 0) +
339
+ (to < segments.length - 1 ? 1 : 0);
340
+ const sel = Math.max(0, names.indexOf(state.runner));
341
+ let from = 0;
342
+ let to = segments.length - 1;
343
+ if (span(from, to) > room) {
344
+ to = 0;
345
+ while (to < segments.length - 1 && span(0, to + 1) <= room)
346
+ to++;
347
+ if (sel > to) {
348
+ from = sel;
349
+ to = sel;
350
+ while (from > 0 && span(from - 1, to) <= room)
351
+ from--;
352
+ while (to < segments.length - 1 && span(from, to + 1) <= room)
353
+ to++;
354
+ }
355
+ }
356
+ const chunks = [];
357
+ if (from > 0)
358
+ chunks.push({ text: '‹', paint: s.dim });
359
+ for (let i = from; i <= to; i++)
360
+ chunks.push(...segments[i]);
361
+ if (to < segments.length - 1)
362
+ chunks.push({ text: '›', paint: s.dim });
363
+ const used = chunksWidth(chunks);
364
+ chunks.push({ text: ' '.repeat(Math.max(1, width - used - flags.length)) });
365
+ chunks.push({ text: flags, paint: s.dim });
366
+ return line(chunks, width);
367
+ }
368
+ function statusLine(width) {
369
+ const shown = state.rows.length + state.skillRows.length;
370
+ const chunks = [{ text: `${shown}/${tabTotal()}`, paint: s.dim }];
371
+ // The clock and the probe time give way first when the line is too long,
372
+ // so a warning after them is not cut.
373
+ const clock = [];
374
+ if (state.catalog === null) {
375
+ chunks.push({ text: ' collecting', paint: s.dim });
376
+ }
377
+ else {
378
+ clock.push({
379
+ text: ` checked ${new Date(state.catalog.generatedAt).toLocaleTimeString()}`,
380
+ paint: s.dim,
381
+ });
382
+ const times = state.cache.map((c) => c.probeMs).filter((n) => n !== undefined);
383
+ if (times.length > 0 && !state.loading) {
384
+ clock.push({ text: `, ${probeTimeLabel(Math.max(...times))}`, paint: s.dim });
385
+ }
386
+ chunks.push(...clock);
387
+ }
388
+ const note = refreshNote(state.cache, state.loading);
389
+ if (state.loading && note === null && state.catalog !== null) {
390
+ chunks.push({ text: ' refreshing', paint: s.note });
391
+ }
392
+ if (note !== null) {
393
+ chunks.push({ text: ` ${note.text}`, paint: note.slow ? s.error : s.warning });
394
+ }
395
+ if (state.message !== null) {
396
+ const tone = state.message.tone;
397
+ chunks.push({
398
+ text: ` ${state.message.text}`,
399
+ paint: tone === 'error' ? s.error : tone === 'warning' ? s.warning : s.note,
400
+ });
401
+ }
402
+ const held = withheld();
403
+ if (state.confirmingTrust) {
404
+ const what = state.trustScope === null ? 'this repository' : `${state.trustScope} here`;
405
+ chunks.push({ text: ` trust ${what}? y/n`, paint: s.warning });
406
+ }
407
+ else if (held !== null) {
408
+ chunks.push({
409
+ text: ` ${countRunners(held.count)} ${held.cause}${held.trustable ? ' (^s to trust)' : ''}`,
410
+ paint: s.warning,
411
+ });
412
+ }
413
+ for (const r of reports().filter((r) => r.status === 'error')) {
414
+ chunks.push({ text: ` ${runnerLabel(r.runner)} failed`, paint: s.error });
415
+ }
416
+ const length = (list) => list.reduce((n, c) => n + c.text.length, 0);
417
+ const fitted = length(chunks) > width ? chunks.filter((c) => !clock.includes(c)) : chunks;
418
+ return line(fitted, width);
419
+ }
420
+ function queryLine(width) {
421
+ // One cursor on screen: the query's only while the list takes the keys.
422
+ const active = state.view === 'list' && state.entering === null;
423
+ return line([
424
+ { text: '> ', paint: s.accent },
425
+ { text: state.query, paint: active ? undefined : s.dim },
426
+ ...(active ? [{ text: '█', paint: s.accent }] : []),
427
+ ], width);
428
+ }
429
+ const footer = (view, width, row = 'task') => line([{ text: footerHints(keysFor('tui', view), width, ' ', row), paint: s.dim }], width);
430
+ /** The lines of the help screen. */
431
+ function helpLines(width) {
432
+ const section = (title, view) => [
433
+ { text: title, heading: true },
434
+ ...keyLines('tui', view).map((text) => ({ text })),
435
+ { text: '' },
436
+ ];
437
+ const lines = [
438
+ ...section('LIST', 'list'),
439
+ ...section('ARGUMENTS', 'arguments'),
440
+ ...section('SETTINGS', 'settings'),
441
+ { text: 'MARKS', heading: true },
442
+ { text: ' > the selected row' },
443
+ { text: ' [all 9] the selected tab' },
444
+ { text: ' * a service: it runs until you stop it' },
445
+ { text: ' ? parameters unknown; Enter asks for arguments' },
446
+ { text: ' ~ a tab whose rows came from the store and are out of date' },
447
+ { text: ' – a withheld runner: reading it means running it' },
448
+ { text: '' },
449
+ { text: 'SKILLS', heading: true },
450
+ { text: ' An agent skill is typed in the agent as /<name>. Enter and ^y copy it;' },
451
+ { text: ' nothing runs here.' },
452
+ ];
453
+ return lines.flatMap((l) => l.heading === true ? [l] : wrapHanging(l.text, width).map((text) => ({ text })));
454
+ }
455
+ function settingsFacts(screen) {
456
+ const snapshot = session.settings();
457
+ return {
458
+ settings: screen.settings,
459
+ gate: session.gate,
460
+ trustable: session.trustable(),
461
+ revoked: state.revoked,
462
+ reports: reports(),
463
+ withheld: session.withheldReason(),
464
+ withheldRunners: withheldRunners(),
465
+ tools: snapshot.tools,
466
+ trustedTools: snapshot.trustedTools,
467
+ };
468
+ }
469
+ /** A scrolled body of `room` lines, with the cursor line marked. */
470
+ function body(lines, scroll, room, cursorAt, width) {
471
+ const out = [];
472
+ for (let i = 0; i < room; i++) {
473
+ const entry = lines[scroll + i];
474
+ if (entry === undefined) {
475
+ out.push(CLEAR_EOL);
476
+ continue;
477
+ }
478
+ const item = 'item' in entry && entry.item !== undefined;
479
+ const mark = item ? (scroll + i === cursorAt ? '> ' : ' ') : '';
480
+ out.push(line([
481
+ { text: mark, paint: s.accent },
482
+ { text: entry.text, paint: entry.heading === true ? s.bold : undefined },
483
+ ], width));
484
+ }
485
+ return out;
486
+ }
487
+ function frame(width, height) {
488
+ const out = [tabRow(width), queryLine(width), statusLine(width)];
489
+ if (state.view === 'help') {
490
+ const lines = helpLines(width);
491
+ const room = Math.max(1, height - out.length - 2);
492
+ state.helpScroll = Math.max(0, Math.min(state.helpScroll, lines.length - room));
493
+ out.push(...body(lines, state.helpScroll, room, null, width));
494
+ out.push(line([{ text: RULE.repeat(width), paint: s.dim }], width));
495
+ out.push(footer('help', width));
496
+ return HOME + out.join('\r\n') + CLEAR_BELOW;
497
+ }
498
+ if (state.view === 'settings' && state.settings !== null) {
499
+ const screen = state.settings;
500
+ const lines = linesOf(screen);
501
+ const at = cursorLine(screen, lines);
502
+ const room = Math.max(1, height - out.length - 2);
503
+ if (at < screen.scroll)
504
+ screen.scroll = at;
505
+ if (at >= screen.scroll + room)
506
+ screen.scroll = at - room + 1;
507
+ out.push(...body(lines, screen.scroll, room, at, width));
508
+ out.push(line([{ text: RULE.repeat(width), paint: s.dim }], width));
509
+ if (screen.adding !== null) {
510
+ out.push(line([
511
+ { text: 'add path: ', paint: s.dim },
512
+ { text: screen.adding },
513
+ { text: '█', paint: s.accent },
514
+ { text: ' enter add esc cancel', paint: s.dim },
515
+ ], width));
516
+ }
517
+ else {
518
+ out.push(footer('settings', width));
519
+ }
520
+ return HOME + out.join('\r\n') + CLEAR_BELOW;
521
+ }
522
+ // The list, in the rows left over. The entry line takes one more row than
523
+ // the key hints it replaces, so the list gives up a row while arguments
524
+ // are typed.
525
+ const at = cursor();
526
+ const list = entries();
527
+ const listHeight = Math.max(1, height - out.length - (state.entering ? 5 : 4));
528
+ if (at < state.scroll)
529
+ state.scroll = at;
530
+ if (at >= state.scroll + listHeight)
531
+ state.scroll = at - listHeight + 1;
532
+ if (state.scroll < 0)
533
+ state.scroll = 0;
534
+ for (let i = 0; i < listHeight; i++) {
535
+ const entry = list[state.scroll + i];
536
+ if (!entry) {
537
+ out.push(i === 0 ? emptyList(width) : CLEAR_EOL);
538
+ continue;
539
+ }
540
+ if (entry.skill !== undefined) {
541
+ out.push(line([
542
+ { text: state.scroll + i === at ? '>' : ' ', paint: s.accent },
543
+ { text: ' ' },
544
+ ...skillChunks(entry.skill),
545
+ ], width));
546
+ continue;
547
+ }
548
+ const row = entry.task;
549
+ out.push(line([
550
+ { text: state.scroll + i === at ? '>' : ' ', paint: s.accent },
551
+ { text: row.task.persistent.value ? '*' : ' ', paint: s.success },
552
+ { text: row.task.parametersUnknown !== undefined ? '?' : ' ', paint: s.warning },
553
+ { text: ' ' },
554
+ ...chainChunks(row),
555
+ ], width));
556
+ }
557
+ // What Enter would run, always on screen.
558
+ const currentEntry = list[at];
559
+ const current = currentEntry?.task;
560
+ out.push(line([{ text: RULE.repeat(width), paint: s.dim }], width));
561
+ if (currentEntry?.skill !== undefined) {
562
+ const skill = currentEntry.skill.skill;
563
+ const text = terminalSafe(skillLine(skill));
564
+ const where = terminalSafe(`skill for ${skill.harnesses.join(', ')}`);
565
+ const gap = width - text.length - where.length - 1;
566
+ out.push(line(gap >= 3
567
+ ? [{ text, paint: s.bold }, { text: ' '.repeat(gap) }, { text: where, paint: s.dim }]
568
+ : [{ text, paint: s.bold }], width));
569
+ out.push(line([
570
+ {
571
+ text: terminalSafe(`${skill.description ?? ''} ${skill.path}`.trim()),
572
+ paint: s.dim,
573
+ },
574
+ ], width));
575
+ }
576
+ else if (current) {
577
+ const shape = chainOf(current.task.runner)
578
+ .map((c) => c.label)
579
+ .join(' > ');
580
+ const gap = width - current.task.display.length - shape.length - 1;
581
+ out.push(line(gap >= 3
582
+ ? [
583
+ { text: current.task.display, paint: s.bold },
584
+ { text: ' '.repeat(gap) },
585
+ { text: shape, paint: s.dim },
586
+ ]
587
+ : [{ text: current.task.display, paint: s.bold }], width));
588
+ out.push(line(infoChunks(current.task), width));
589
+ }
590
+ else {
591
+ out.push(line([], width));
592
+ out.push(line([], width));
593
+ }
594
+ if (state.entering) {
595
+ const { task, text } = state.entering;
596
+ out.push(line([
597
+ { text: '$ ', paint: s.dim },
598
+ { text: terminalSafe(commandLine(task.argv)) + ' ', paint: s.bold },
599
+ { text },
600
+ { text: '█', paint: s.accent },
601
+ ], width));
602
+ const hints = footerHints(keysFor('tui', 'arguments'), width);
603
+ const about = task.parametersUnknown !== undefined
604
+ ? `${parametersUnknownLabel(task.parametersUnknown)}; type any, or none`
605
+ : `takes ${paramShape(task.parameters)}`;
606
+ const aboutRoom = Math.max(0, width - hints.length - 6);
607
+ out.push(line([{ text: ` ${fitWidth(terminalSafe(about), aboutRoom)} ${hints}`, paint: s.dim }], width));
608
+ }
609
+ else {
610
+ out.push(footer('list', width, currentEntry?.skill !== undefined ? 'skill' : 'task'));
611
+ }
612
+ return HOME + out.join('\r\n') + CLEAR_BELOW;
613
+ }
614
+ /** The first list line when there are no rows: why. */
615
+ function emptyList(width) {
616
+ let text;
617
+ if (state.runner === SKILLS_TAB)
618
+ text = state.query !== '' ? 'no match' : 'no skills';
619
+ else if (state.catalog === null)
620
+ text = state.probed ? 'nothing collected' : 'collecting…';
621
+ else if (state.runner !== ALL && reportFor(state.runner)?.skippedForExec === true) {
622
+ const held = withheld();
623
+ text = held === null ? 'withheld' : `${held.cause}${held.trustable ? ' — ^s to trust' : ''}`;
624
+ }
625
+ else if (state.query !== '')
626
+ text = 'no match';
627
+ else if (tabTasks().length > 0)
628
+ text = 'no task passes the filters';
629
+ else
630
+ text = state.probed || !state.loading ? 'nothing collected' : 'collecting…';
631
+ return line([{ text: ` ${text}`, paint: s.dim }], width);
632
+ }
633
+ /** The line under the selected task: its marks spelled out, then its doc. */
634
+ function infoChunks(task) {
635
+ const chunks = [];
636
+ if (task.persistent.value)
637
+ chunks.push({ text: '* service ', paint: s.success });
638
+ if (task.parametersUnknown !== undefined) {
639
+ chunks.push({
640
+ text: `? ${parametersUnknownLabel(task.parametersUnknown)} `,
641
+ paint: s.warning,
642
+ });
643
+ }
644
+ chunks.push({ text: task.doc ?? task.detail ?? '', paint: s.dim });
645
+ return chunks;
646
+ }
647
+ function draw() {
648
+ recompute();
649
+ host.write(frame(host.columns() || 100, host.rows() || 30));
650
+ }
651
+ // --------------------------------------------------------------- actions
652
+ function quit(code) {
653
+ state.inFlight?.abort();
654
+ host.release();
655
+ host.exit(code);
656
+ }
657
+ /**
658
+ * Run `task` with `args`, handing it the terminal. The plan is resolved
659
+ * first, so a refusal (an editor variable, arguments the tool will not
660
+ * take) is shown on the status line and nothing is handed over.
661
+ */
662
+ let confirming = false;
663
+ function run(task, args) {
664
+ if (state.catalog === null)
665
+ return;
666
+ let plan;
667
+ try {
668
+ plan = session.resolveRun(state.catalog, task.id, args);
669
+ }
670
+ catch (err) {
671
+ if (err instanceof SessionError) {
672
+ say(err.message, 'error');
673
+ return;
674
+ }
675
+ throw err;
676
+ }
677
+ if (state.fromProbe) {
678
+ handOver(task, plan, args);
679
+ return;
680
+ }
681
+ // The row came from the saved listing or the store: read its runner
682
+ // again first, and refuse a task that changed. One check at a time, so a
683
+ // second Enter cannot hand off twice.
684
+ if (confirming)
685
+ return;
686
+ confirming = true;
687
+ say(`checking ${task.display} — ${runnerLabel(task.runner)} is read again first`, 'note');
688
+ draw();
689
+ void session.confirmRun(plan, args).then((confirmed) => handOver(task, confirmed, args), (err) => {
690
+ confirming = false;
691
+ say(err instanceof Error ? err.message : String(err), 'error');
692
+ draw();
693
+ if (err instanceof SessionError && err.code === 'task-changed')
694
+ track(refresh());
695
+ });
696
+ }
697
+ /** Hand the terminal to `plan`'s task and exit with its code. */
698
+ function handOver(task, plan, args) {
699
+ state.inFlight?.abort();
700
+ host.release();
701
+ host.write(`$ ${terminalSafe(commandLine(plan.argv))}\n`);
702
+ if (task.parameters.length > 0 && args.length === 0) {
703
+ host.write(` takes ${terminalSafe(paramShape(task.parameters))}\n`);
704
+ }
705
+ const result = host.handOff(plan);
706
+ if (result.error !== undefined) {
707
+ host.write(terminalSafe(`${BIN}: ${plan.argv[0]}: ${result.error}`) + '\n');
708
+ const from = cacheFor(task.runner);
709
+ if (from !== undefined && from.state === 'stale') {
710
+ host.write(`${BIN}: that row came from a cached listing of ${terminalSafe(runnerLabel(task.runner))} taken ${humanAge(from.ageMs)}` +
711
+ ` — the task may no longer exist; start ${BIN} again to re-probe\n`);
712
+ }
713
+ }
714
+ host.exit(result.exit);
715
+ }
716
+ /** Enter on a row: run it, or ask for its arguments first. */
717
+ function activate(task) {
718
+ if (task.parametersUnknown === 'editor-variable') {
719
+ say(parametersUnknownLabel('editor-variable'), 'error');
720
+ return;
721
+ }
722
+ // A task that takes arguments, or whose parameters could not be read,
723
+ // asks first. Running it here would spawn it without them and hand over
724
+ // the terminal before the mistake could be reported.
725
+ if (task.parameters.length > 0 || task.parametersUnknown !== undefined) {
726
+ state.entering = { task, text: '' };
727
+ return;
728
+ }
729
+ run(task, []);
730
+ }
731
+ async function refresh(note) {
732
+ if (state.loading)
733
+ return;
734
+ const generation = ++state.generation;
735
+ const controller = new AbortController();
736
+ state.inFlight = controller;
737
+ state.loading = true;
738
+ state.message = note ?? null;
739
+ draw();
740
+ try {
741
+ // Always a real probe. ^r means "ask again", and an answer from the
742
+ // store would look the same as doing nothing.
743
+ const snapshot = await session.catalog({ signal: controller.signal });
744
+ if (generation !== state.generation)
745
+ return;
746
+ state.catalog = orderedCatalog(snapshot.catalog, state.runnerOrder);
747
+ state.cache = snapshot.cache;
748
+ state.skills = snapshot.skills;
749
+ state.fromProbe = snapshot.origin === 'probe';
750
+ if (state.runner === SKILLS_TAB && state.skills.length === 0)
751
+ state.runner = ALL;
752
+ }
753
+ catch (err) {
754
+ if (generation === state.generation && !controller.signal.aborted) {
755
+ say(`refresh failed: ${errorText(err)}`, 'error');
756
+ }
757
+ }
758
+ finally {
759
+ if (generation === state.generation) {
760
+ state.loading = false;
761
+ state.inFlight = null;
762
+ state.probed = true;
763
+ if (note !== undefined && state.message === note)
764
+ state.message = null;
765
+ }
766
+ }
767
+ }
768
+ async function boot() {
769
+ // The saved view first: one file, so the tasks show at once. Without
770
+ // one, the store: no probe, but it detects the project and hashes each
771
+ // runner's files, which takes seconds on a large repository.
772
+ try {
773
+ // savedCatalog never throws; a bad file reads as none.
774
+ const stored = (await session.savedCatalog()) ?? (await session.storedCatalog());
775
+ if (stored !== null) {
776
+ state.catalog = orderedCatalog(stored.catalog, state.runnerOrder);
777
+ state.cache = stored.cache;
778
+ state.skills = stored.skills;
779
+ }
780
+ }
781
+ catch {
782
+ // A store that cannot be read is the same as an empty one.
783
+ }
784
+ draw();
785
+ await refresh();
786
+ draw();
787
+ }
788
+ /**
789
+ * Grant trust, to the repository or with `scope` to one tool, then probe
790
+ * again so the withheld runners appear.
791
+ */
792
+ async function grantTrust(scope) {
793
+ let note;
794
+ try {
795
+ note = (await session.grantTrust(scope)).note;
796
+ }
797
+ catch (err) {
798
+ // Never silent: the user must know why the runners are still withheld.
799
+ say(`trust failed: ${errorText(err)}`, 'error');
800
+ return;
801
+ }
802
+ state.revoked = false;
803
+ // A probe started before the grant runs with the old settings, and
804
+ // refresh() ignores a call while one runs. Abandon it first; refresh()
805
+ // raises the generation, so its result is discarded.
806
+ state.inFlight?.abort();
807
+ state.inFlight = null;
808
+ state.loading = false;
809
+ const trusted = scope === undefined ? 'trusted' : `trusted ${scope}`;
810
+ await refresh({
811
+ text: note ? `${trusted} — re-probing; ${note}` : `${trusted} — re-probing`,
812
+ tone: 'note',
813
+ });
814
+ }
815
+ /** Remove one tool's grant; it is withheld again from the next probe. */
816
+ async function revokeToolTrust(scope) {
817
+ let changed;
818
+ try {
819
+ changed = (await session.revokeTrust(scope)).changed;
820
+ }
821
+ catch (err) {
822
+ say(`untrust failed: ${errorText(err)}`, 'error');
823
+ return;
824
+ }
825
+ if (!changed) {
826
+ say(`${scope} has no grant to remove; trust rules in your user config may trust it`, 'warning');
827
+ return;
828
+ }
829
+ state.inFlight?.abort();
830
+ state.inFlight = null;
831
+ state.loading = false;
832
+ await refresh({ text: `removed trust for ${scope} — re-probing`, tone: 'note' });
833
+ if (state.message === null)
834
+ say(`removed trust for ${scope}`);
835
+ }
836
+ async function revokeTrust() {
837
+ try {
838
+ const change = await session.revokeTrust();
839
+ if (change.changed) {
840
+ state.revoked = true;
841
+ say(`trust removed; the next ${BIN} run withholds what needs it`);
842
+ }
843
+ else if (session.gate.trusted) {
844
+ say('no grant to remove; trust rules in your user config trust this repository', 'warning');
845
+ }
846
+ else {
847
+ say('this repository has no trust grant');
848
+ }
849
+ }
850
+ catch (err) {
851
+ say(`untrust failed: ${errorText(err)}`, 'error');
852
+ }
853
+ }
854
+ /** Ask `y/n` before a grant: for the repository, or with `scope` for one tool. */
855
+ function askTrust(scope = null) {
856
+ if (session.trustable()) {
857
+ state.trustScope = scope;
858
+ state.confirmingTrust = true;
859
+ }
860
+ else if (withheld() !== null)
861
+ say('trust would not change this run: execution is off', 'warning');
862
+ else
863
+ say('nothing is withheld');
864
+ }
865
+ async function copy(task) {
866
+ await toClipboard(taskCopyText(task, host.platform), 'copied');
867
+ }
868
+ /** A skill runs in an agent, so its action copies `/<name>` and spawns nothing. */
869
+ async function copySkill(skill) {
870
+ await toClipboard(skillCopyText(skill), terminalSafe(`copied ${skill.invoke}; type it in ${skill.harnesses.join(', ')}`));
871
+ }
872
+ /** Copy `text`; null is text that holds a control character, which is refused. */
873
+ async function toClipboard(text, done) {
874
+ if (text === null) {
875
+ say(COPY_REFUSED, 'warning');
876
+ return;
877
+ }
878
+ say('copying…');
879
+ let ok = false;
880
+ try {
881
+ ok = await host.clipboard(text);
882
+ }
883
+ catch {
884
+ ok = false;
885
+ }
886
+ say(ok ? done : 'clipboard unavailable', ok ? 'note' : 'warning');
887
+ }
888
+ function cycleRunner(step) {
889
+ const names = tabs();
890
+ const at = Math.max(0, names.indexOf(state.runner));
891
+ state.runner = names[(at + step + names.length) % names.length];
892
+ resetSelection();
893
+ }
894
+ // -------------------------------------------------------------- settings
895
+ /** Show `settings`, which the session has just read. */
896
+ function adoptSettings(settings) {
897
+ state.runnerOrder = settings.runnerOrder.value;
898
+ if (state.catalog !== null)
899
+ state.catalog = orderedCatalog(state.catalog, state.runnerOrder);
900
+ }
901
+ async function openSettings() {
902
+ let settings;
903
+ try {
904
+ settings = (await session.reloadSettings()).settings;
905
+ }
906
+ catch (err) {
907
+ say(`settings unavailable: ${errorText(err)}`, 'error');
908
+ return;
909
+ }
910
+ const screen = { settings, at: null, hint: 0, scroll: 0, adding: null };
911
+ state.settings = screen;
912
+ state.view = 'settings';
913
+ }
914
+ const linesOf = (screen) => settingsLines(settingsFacts(screen));
915
+ const sameItem = (a, b) => a !== undefined && b !== null && JSON.stringify(a) === JSON.stringify(b);
916
+ /** The index of the next line with an item from `from` in direction `step`, or null. */
917
+ function itemIndex(lines, from, step) {
918
+ for (let i = from; i >= 0 && i < lines.length; i += step) {
919
+ if (lines[i].item !== undefined)
920
+ return i;
921
+ }
922
+ return null;
923
+ }
924
+ /**
925
+ * The cursor's line: its item's, else the nearest item at or above where it
926
+ * was, else the first. The screen remembers the answer.
927
+ */
928
+ function cursorLine(screen, lines) {
929
+ let at = lines.findIndex((l) => sameItem(l.item, screen.at));
930
+ if (at === -1) {
931
+ const from = Math.min(screen.hint, lines.length - 1);
932
+ at = itemIndex(lines, from, -1) ?? itemIndex(lines, 0, 1) ?? 0;
933
+ }
934
+ screen.at = lines[at]?.item ?? null;
935
+ screen.hint = at;
936
+ return at;
937
+ }
938
+ function moveSettings(screen, steps) {
939
+ const lines = linesOf(screen);
940
+ let at = cursorLine(screen, lines);
941
+ const dir = steps > 0 ? 1 : -1;
942
+ for (let n = 0; n < Math.abs(steps); n++) {
943
+ const next = itemIndex(lines, at + dir, dir);
944
+ if (next === null)
945
+ break;
946
+ at = next;
947
+ }
948
+ screen.at = lines[at]?.item ?? null;
949
+ screen.hint = at;
950
+ }
951
+ async function applyEdit(edit) {
952
+ let saved;
953
+ try {
954
+ const result = await session.saveSetting(edit.key, edit.value);
955
+ adoptSettings(result.snapshot.settings);
956
+ if (state.settings !== null)
957
+ state.settings.settings = result.snapshot.settings;
958
+ saved = `saved ${edit.key} to ${result.file}`;
959
+ if (result.pinned) {
960
+ say(`${saved}; a command-line flag decides it for this run`, 'warning');
961
+ return;
962
+ }
963
+ }
964
+ catch (err) {
965
+ // The session's message says whether the write or the read back failed.
966
+ say(errorText(err), 'error');
967
+ return;
968
+ }
969
+ if (edit.key === 'runners.order') {
970
+ say(saved);
971
+ return;
972
+ }
973
+ // Probe again so the list shows what the new setting collects.
974
+ state.inFlight?.abort();
975
+ state.inFlight = null;
976
+ state.loading = false;
977
+ await refresh({ text: `${saved} — re-probing`, tone: 'note' });
978
+ if (state.message === null)
979
+ say(saved);
980
+ }
981
+ function handleSettings(key) {
982
+ const screen = state.settings;
983
+ if (screen === null) {
984
+ state.view = 'list';
985
+ return;
986
+ }
987
+ if (screen.adding !== null) {
988
+ if (key === '\x1b' || key === '\x03')
989
+ screen.adding = null;
990
+ else if (key === '\r' || key === '\n') {
991
+ const edit = editPaths(screen.settings, { add: screen.adding });
992
+ screen.adding = null;
993
+ if (edit !== null)
994
+ track(applyEdit(edit));
995
+ }
996
+ else if (key === '\x7f' || key === '\x08')
997
+ screen.adding = screen.adding.slice(0, -1);
998
+ else if (key === '\x15')
999
+ screen.adding = '';
1000
+ else if (isText(key))
1001
+ screen.adding += key;
1002
+ return;
1003
+ }
1004
+ const lines = linesOf(screen);
1005
+ const item = lines[cursorLine(screen, lines)]?.item;
1006
+ const page = Math.max(1, host.rows() - 6);
1007
+ switch (namedKey(key) ?? key) {
1008
+ case '\x1b':
1009
+ case '\x03':
1010
+ case ',':
1011
+ case 'q':
1012
+ state.view = 'list';
1013
+ state.settings = null;
1014
+ return;
1015
+ case '?':
1016
+ state.helpFrom = 'settings';
1017
+ state.view = 'help';
1018
+ state.helpScroll = 0;
1019
+ return;
1020
+ case 'up':
1021
+ case '\x10':
1022
+ moveSettings(screen, -1);
1023
+ return;
1024
+ case 'down':
1025
+ case '\x0e':
1026
+ moveSettings(screen, 1);
1027
+ return;
1028
+ case 'pageUp':
1029
+ moveSettings(screen, -page);
1030
+ return;
1031
+ case 'pageDown':
1032
+ moveSettings(screen, page);
1033
+ return;
1034
+ case ' ':
1035
+ case '\r':
1036
+ case '\n':
1037
+ if (item?.kind === 'runner')
1038
+ track(applyEdit(toggleRunner(screen.settings, item.runner)));
1039
+ else if (item?.kind === 'discovery')
1040
+ track(applyEdit(cycleDiscovery(screen.settings)));
1041
+ else if (item?.kind === 'add-path')
1042
+ screen.adding = '';
1043
+ else if (item?.kind === 'trust') {
1044
+ if (session.trustable())
1045
+ askTrust();
1046
+ else if (session.gate.trusted && !state.revoked)
1047
+ track(revokeTrust());
1048
+ }
1049
+ else if (item?.kind === 'tool') {
1050
+ if (item.trusted)
1051
+ track(revokeToolTrust(item.tool));
1052
+ else
1053
+ askTrust(item.tool);
1054
+ }
1055
+ return;
1056
+ case '[':
1057
+ case ']': {
1058
+ if (item?.kind !== 'runner')
1059
+ return;
1060
+ const edit = moveRunner({ settings: screen.settings, reports: reports() }, item.runner, key === '[' ? -1 : 1);
1061
+ if (edit !== null)
1062
+ track(applyEdit(edit));
1063
+ return;
1064
+ }
1065
+ case 'a':
1066
+ screen.adding = '';
1067
+ return;
1068
+ case 'x':
1069
+ case '\x1b[3~': {
1070
+ if (item?.kind !== 'path')
1071
+ return;
1072
+ const edit = editPaths(screen.settings, { remove: item.path });
1073
+ if (edit !== null)
1074
+ track(applyEdit(edit));
1075
+ return;
1076
+ }
1077
+ case 't':
1078
+ case '\x13':
1079
+ askTrust(item?.kind === 'tool' && !item.trusted ? item.tool : null);
1080
+ return;
1081
+ case 'u':
1082
+ if (item?.kind === 'tool') {
1083
+ if (item.trusted)
1084
+ track(revokeToolTrust(item.tool));
1085
+ return;
1086
+ }
1087
+ track(revokeTrust());
1088
+ return;
1089
+ }
1090
+ }
1091
+ // ------------------------------------------------------------------- keys
1092
+ function handle(key) {
1093
+ // The trust question takes exactly one key. `y` grants; any other key
1094
+ // cancels and is used up, so it does not also do its usual job.
1095
+ if (state.confirmingTrust) {
1096
+ const scope = state.trustScope ?? undefined;
1097
+ state.confirmingTrust = false;
1098
+ state.trustScope = null;
1099
+ state.message = null;
1100
+ if (key === 'y' || key === 'Y')
1101
+ track(grantTrust(scope));
1102
+ return;
1103
+ }
1104
+ if (state.view === 'help') {
1105
+ const page = Math.max(1, host.rows() - 6);
1106
+ switch (namedKey(key) ?? key) {
1107
+ case 'up':
1108
+ state.helpScroll = Math.max(0, state.helpScroll - 1);
1109
+ return;
1110
+ case 'down':
1111
+ state.helpScroll++;
1112
+ return;
1113
+ case 'pageUp':
1114
+ state.helpScroll = Math.max(0, state.helpScroll - page);
1115
+ return;
1116
+ case 'pageDown':
1117
+ state.helpScroll += page;
1118
+ return;
1119
+ case '\x1b':
1120
+ case '\x03':
1121
+ case '?':
1122
+ case 'q':
1123
+ state.view =
1124
+ state.helpFrom === 'settings' && state.settings !== null ? 'settings' : 'list';
1125
+ return;
1126
+ }
1127
+ return;
1128
+ }
1129
+ if (state.view === 'settings') {
1130
+ handleSettings(key);
1131
+ return;
1132
+ }
1133
+ // While arguments are typed, every key is text or one of the keys that
1134
+ // end it, so no key acts on a list the user is not looking at.
1135
+ if (state.entering) {
1136
+ const entering = state.entering;
1137
+ if (key === '\x1b' || key === '\x03')
1138
+ state.entering = null;
1139
+ else if (key === '\r' || key === '\n') {
1140
+ state.entering = null;
1141
+ run(entering.task, splitArgs(entering.text));
1142
+ }
1143
+ else if (key === '\x7f' || key === '\x08')
1144
+ entering.text = entering.text.slice(0, -1);
1145
+ else if (key === '\x15')
1146
+ entering.text = '';
1147
+ else if (isText(key))
1148
+ entering.text += key;
1149
+ return;
1150
+ }
1151
+ const page = Math.max(1, host.rows() - 7);
1152
+ const move = (n) => {
1153
+ select(cursor() + n);
1154
+ state.message = null;
1155
+ };
1156
+ switch (namedKey(key) ?? key) {
1157
+ case '\x03': // ctrl-c
1158
+ case '\x1b': // esc
1159
+ quit(0);
1160
+ return;
1161
+ case '\r':
1162
+ case '\n': {
1163
+ const entry = entries()[cursor()];
1164
+ if (entry?.skill !== undefined)
1165
+ track(copySkill(entry.skill.skill));
1166
+ else if (entry?.task !== undefined)
1167
+ activate(entry.task.task);
1168
+ return;
1169
+ }
1170
+ case '\x19': {
1171
+ // ctrl-y
1172
+ const entry = entries()[cursor()];
1173
+ if (entry?.skill !== undefined)
1174
+ track(copySkill(entry.skill.skill));
1175
+ else if (entry?.task !== undefined)
1176
+ track(copy(entry.task.task));
1177
+ return;
1178
+ }
1179
+ case '\x05': // ctrl-e
1180
+ state.mode = state.mode === 'fuzzy' ? 'exact' : 'fuzzy';
1181
+ resetSelection();
1182
+ return;
1183
+ case '\x14': // ctrl-t
1184
+ state.servicesOnly = !state.servicesOnly;
1185
+ resetSelection();
1186
+ return;
1187
+ case '\x04': // ctrl-d
1188
+ state.declaredOnly = !state.declaredOnly;
1189
+ resetSelection();
1190
+ return;
1191
+ case '\x0f': // ctrl-o
1192
+ state.scope = (state.scope + 1) % SCOPES.length;
1193
+ resetSelection();
1194
+ return;
1195
+ case ',':
1196
+ track(openSettings());
1197
+ return;
1198
+ case '?':
1199
+ state.helpFrom = 'list';
1200
+ state.view = 'help';
1201
+ state.helpScroll = 0;
1202
+ return;
1203
+ case '\x12': // ctrl-r
1204
+ track(refresh());
1205
+ return;
1206
+ case '\x13': // ctrl-s
1207
+ askTrust();
1208
+ return;
1209
+ case '\t':
1210
+ cycleRunner(1);
1211
+ return;
1212
+ case 'shiftTab':
1213
+ cycleRunner(-1);
1214
+ return;
1215
+ case 'up':
1216
+ case '\x10':
1217
+ move(-1);
1218
+ return;
1219
+ case 'down':
1220
+ case '\x0e':
1221
+ move(1);
1222
+ return;
1223
+ case 'pageUp':
1224
+ move(-page);
1225
+ return;
1226
+ case 'pageDown':
1227
+ move(page);
1228
+ return;
1229
+ case 'home':
1230
+ case '\x01':
1231
+ select(0);
1232
+ return;
1233
+ case 'end':
1234
+ select(entries().length - 1);
1235
+ return;
1236
+ case '\x7f':
1237
+ case '\x08':
1238
+ state.query = state.query.slice(0, -1);
1239
+ resetSelection();
1240
+ return;
1241
+ case '\x15': // ctrl-u
1242
+ state.query = '';
1243
+ resetSelection();
1244
+ return;
1245
+ default:
1246
+ if (isText(key)) {
1247
+ state.query += key;
1248
+ resetSelection();
1249
+ }
1250
+ }
1251
+ }
1252
+ function feed(chunk) {
1253
+ for (const key of splitKeys(chunk)) {
1254
+ handle(key);
1255
+ // Each key acts on the rows the one before it left.
1256
+ recompute();
1257
+ }
1258
+ draw();
1259
+ }
1260
+ return {
1261
+ state,
1262
+ session,
1263
+ frame,
1264
+ handle,
1265
+ feed,
1266
+ recompute,
1267
+ cursor,
1268
+ entries,
1269
+ draw,
1270
+ boot,
1271
+ refresh: () => refresh(),
1272
+ quit,
1273
+ async idle() {
1274
+ while (pending.size > 0)
1275
+ await Promise.allSettled(pending);
1276
+ },
1277
+ };
1278
+ }