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