@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
package/dist/tui.js DELETED
@@ -1,840 +0,0 @@
1
- /**
2
- * The terminal UI: browse every task in a repository, and run one.
3
- *
4
- * Unlike the page, Enter runs the selected task in this shell and hands it the
5
- * terminal. The page can only give you a command to paste.
6
- *
7
- * No dependencies: raw mode, ANSI, and one frame string per keystroke. A TUI
8
- * toolkit would weigh more than the code it saves, and this has to keep
9
- * working from a checkout whose node_modules is what you are trying to repair.
10
- * The CLI sends its output through `CliIo` so `main()` can be tested without
11
- * a real stream. This file writes to `process.stdout` directly, because its
12
- * job is to control the terminal: raw mode, the alternate screen, and handing
13
- * the terminal to a spawned task.
14
- *
15
- * Collection is async, which is what most of the state handling below is for:
16
- * keystrokes arrive during a refresh, and a row can be stale.
17
- */
18
- import { spawnRunner, streamRunner } from '@osdlc/command-seam';
19
- import { tasks as allTasks, } from '@osdlc/system-model/detect';
20
- import { humanAge, humanMs } from '@osdlc/system-model/duration';
21
- import { matchEntry, terms as splitTerms } from '@osdlc/system-model/match';
22
- import { paramShape } from '@osdlc/system-model/params';
23
- import { APP, BIN } from "./app.js";
24
- import { runArgv, splitArgs } from "./args.js";
25
- import { cacheDir } from "./cache.js";
26
- import { collectAndCache, freshStates, fromStore, makeProject, orderedCatalog, readCachedCatalog, } from "./catalog.js";
27
- import { loadConfig } from "./config.js";
28
- import { appTrustStore } from "./trust-store.js";
29
- import { groupOf, runnerLabel } from "./groups.js";
30
- import { terminalSafe } from "./terminal-text.js";
31
- // ---------------------------------------------------------------- ansi
32
- const ALT_ON = '\x1b[?1049h';
33
- const ALT_OFF = '\x1b[?1049l';
34
- const HIDE = '\x1b[?25l';
35
- const SHOW = '\x1b[?25h';
36
- const HOME = '\x1b[H';
37
- const CLEAR_EOL = '\x1b[K';
38
- const CLEAR_BELOW = '\x1b[J';
39
- const COLOR = !process.env['NO_COLOR'] && process.stdout.isTTY;
40
- const sgr = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
41
- const dim = sgr('2');
42
- const bold = sgr('1');
43
- const green = sgr('32');
44
- const cyan = sgr('36');
45
- const yellow = sgr('33');
46
- const red = sgr('31');
47
- const invert = sgr('7');
48
- const hit = sgr('1;33');
49
- /**
50
- * Compose chunks into one line of exactly `width` columns. Truncation happens
51
- * on the PLAIN text — measuring a string that already carries escape sequences
52
- * counts the escapes as columns and wraps the line. Every chunk's text goes
53
- * through {@link terminalSafe} first, so repository text never writes a
54
- * control sequence; only `paint` adds escapes.
55
- */
56
- function line(chunks, width) {
57
- let used = 0;
58
- let out = '';
59
- for (const chunk of chunks) {
60
- if (used >= width)
61
- break;
62
- let text = terminalSafe(chunk.text);
63
- if (used + text.length > width)
64
- text = text.slice(0, Math.max(0, width - used - 1)) + '…';
65
- used += text.length;
66
- out += chunk.paint ? chunk.paint(text) : text;
67
- }
68
- return out + CLEAR_EOL;
69
- }
70
- // ---------------------------------------------------------------- state
71
- const ALL = 'all';
72
- /**
73
- * The module singleton.
74
- *
75
- * Exported for one reason. `runTui` takes over a real terminal and never
76
- * returns, so the selection rule (the selection must survive a refresh that
77
- * reorders or drops rows under the cursor) can only be tested through this
78
- * and {@link recompute}. Nothing outside a test writes to it.
79
- */
80
- export const state = {
81
- catalog: null,
82
- project: makeProject(),
83
- projectToolsPending: false,
84
- root: process.cwd(),
85
- options: {},
86
- runnerOrder: undefined,
87
- env: undefined,
88
- home: undefined,
89
- store: '',
90
- cache: [],
91
- runner: ALL,
92
- query: '',
93
- mode: 'fuzzy',
94
- servicesOnly: false,
95
- selectedId: null,
96
- scroll: 0,
97
- message: '',
98
- loading: false,
99
- gate: null,
100
- confirmingTrust: false,
101
- entering: null,
102
- settings: null,
103
- generation: 0,
104
- inFlight: null,
105
- rows: [],
106
- };
107
- function reportFor(runner) {
108
- return state.catalog?.reports.find((r) => r.runner === runner);
109
- }
110
- /** How many runners were not collected for lack of trust; 0 when trust is not the reason. */
111
- function withheldForTrust() {
112
- if (state.gate?.reason !== 'untrusted')
113
- return 0;
114
- return state.catalog?.reports.filter((r) => r.skippedForExec).length ?? 0;
115
- }
116
- function tabs() {
117
- return [ALL, ...(state.catalog?.reports ?? []).map((r) => r.runner)];
118
- }
119
- /** The cache verdict for one runner, or undefined when nothing describes it. */
120
- function cacheFor(runner) {
121
- return state.cache.find((c) => c.runner === runner);
122
- }
123
- /** Every runner whose rows on screen came out of the store and are out of date. */
124
- function staleRunners() {
125
- return state.cache.filter((c) => c.state === 'stale');
126
- }
127
- /**
128
- * What the status line says about the rows on screen, in three states.
129
- *
130
- * Fresh says nothing. A line that is always shown is a line nobody reads,
131
- * and there is nothing to report.
132
- *
133
- * Stale and slow is kept apart from ordinary stale because it is the case the
134
- * cache exists for. A runner measured at several seconds in this repository
135
- * is why the screen would otherwise be empty. Showing it the same way as a
136
- * 200ms refresh would hide the one warning that matters. Slowness is
137
- * measured, never assumed: a runner that is quick here is not called slow
138
- * because it is slow elsewhere.
139
- */
140
- export function refreshNote(rows, loading) {
141
- const stale = rows.filter((r) => r.state === 'stale');
142
- if (stale.length === 0)
143
- return null;
144
- const named = (r) => r.estimateMs === null
145
- ? `${r.runner} (never timed here)`
146
- : `${r.runner} (~${humanMs(r.estimateMs)})`;
147
- const slow = stale.filter((r) => r.slow);
148
- if (!loading) {
149
- // The refresh is over and these rows are still what the store held: it
150
- // failed, or it has not been asked for yet. "re-probing" would be untrue.
151
- return {
152
- slow: slow.length > 0,
153
- text: `cached rows: ${stale.map((r) => `${r.runner} ${humanAge(r.ageMs)}`).join(', ')} — ^r to re-probe`,
154
- };
155
- }
156
- if (slow.length > 0) {
157
- const rest = stale.filter((r) => !slow.includes(r));
158
- return {
159
- slow: true,
160
- text: `cached rows — ${slow.map(named).join(', ')} ` +
161
- `${slow.length === 1 ? 'is' : 'are'} slow to probe here, so this takes a moment` +
162
- (rest.length > 0 ? `; also re-probing ${rest.map(named).join(', ')}` : ''),
163
- };
164
- }
165
- return { slow: false, text: `cached rows — re-probing ${stale.map(named).join(', ')}` };
166
- }
167
- function chainOf(runner) {
168
- return reportFor(runner)?.chain ?? [];
169
- }
170
- function inScope() {
171
- const catalog = state.catalog;
172
- if (catalog === null)
173
- return [];
174
- return state.runner === ALL ? allTasks(catalog) : (reportFor(state.runner)?.tasks ?? []);
175
- }
176
- function visibleRows() {
177
- const queryTerms = splitTerms(state.query);
178
- const rows = [];
179
- for (const task of inScope()) {
180
- if (state.servicesOnly && !task.persistent.value)
181
- continue;
182
- if (queryTerms.length === 0) {
183
- rows.push({ task, score: 0, labelHits: null });
184
- continue;
185
- }
186
- const m = matchEntry(task, queryTerms, state.mode);
187
- if (m)
188
- rows.push({ task, score: m.score, labelHits: m.labelHits });
189
- }
190
- if (queryTerms.length)
191
- rows.sort((a, b) => b.score - a.score);
192
- return rows;
193
- }
194
- /** Index of the selected task, or 0 when its id is no longer present. */
195
- export function cursor() {
196
- if (state.selectedId === null)
197
- return 0;
198
- const at = state.rows.findIndex((r) => r.task.id === state.selectedId);
199
- return at === -1 ? 0 : at;
200
- }
201
- function select(index) {
202
- const clamped = Math.max(0, Math.min(index, state.rows.length - 1));
203
- state.selectedId = state.rows[clamped]?.task.id ?? null;
204
- }
205
- // ---------------------------------------------------------------- render
206
- /** The chain, dimmed except for the leaf, with matched characters picked out. */
207
- function chainChunks(row) {
208
- const { path } = row.task;
209
- const marks = new Set(row.labelHits ?? []);
210
- const chunks = [];
211
- let at = 0;
212
- for (let p = 0; p < path.length; p++) {
213
- const leaf = p === path.length - 1;
214
- let run = '';
215
- let marked = marks.has(at);
216
- for (const ch of path[p]) {
217
- const on = marks.has(at);
218
- if (on !== marked) {
219
- chunks.push({ text: run, paint: marked ? hit : leaf ? bold : dim });
220
- run = '';
221
- marked = on;
222
- }
223
- run += ch;
224
- at++;
225
- }
226
- if (run)
227
- chunks.push({ text: run, paint: marked ? hit : leaf ? bold : dim });
228
- if (!leaf) {
229
- chunks.push({ text: ' > ', paint: dim });
230
- at++; // the " " the label was joined on
231
- }
232
- }
233
- return chunks;
234
- }
235
- /**
236
- * The whole screen as one string.
237
- *
238
- * Exported with {@link state} and {@link recompute} so tests can check the
239
- * three cache states in the rendered lines, not only in the helper that
240
- * builds them. The user reads the status line, and a correct note placed in
241
- * the wrong line helps nobody.
242
- */
243
- export function frame(width, height) {
244
- const out = [];
245
- const total = inScope().length;
246
- const at = cursor();
247
- // 1. tabs
248
- const tabChunks = [];
249
- for (const name of tabs()) {
250
- const count = name === ALL
251
- ? (state.catalog?.reports ?? []).reduce((n, r) => n + r.tasks.length, 0)
252
- : (reportFor(name)?.tasks.length ?? 0);
253
- // Marked on the tab, not per row. All of a runner's rows are the same age,
254
- // so a per-row mark would repeat one fact many times, and the row
255
- // renderer would have to know about the cache. A leading `~` reads as
256
- // "about" and still shows under NO_COLOR.
257
- const stale = name === ALL ? staleRunners().length > 0 : cacheFor(name)?.state === 'stale';
258
- // A bar between groups: tasks, then dependencies, tools and git hooks.
259
- const prev = tabs()[tabs().indexOf(name) - 1];
260
- if (name !== ALL && prev !== undefined && prev !== ALL && groupOf(prev) !== groupOf(name)) {
261
- tabChunks.push({ text: '│', paint: dim });
262
- }
263
- const label = name === ALL ? ALL : runnerLabel(name);
264
- tabChunks.push({
265
- text: ` ${stale ? '~' : ''}${label} ${count} `,
266
- paint: name === state.runner ? invert : stale ? yellow : dim,
267
- });
268
- }
269
- const flags = `${state.mode}${state.servicesOnly ? ' services' : ''}${state.catalog?.allowExec ? ' exec' : ''}`;
270
- const used = tabChunks.reduce((n, c) => n + c.text.length, 0);
271
- tabChunks.push({ text: ' '.repeat(Math.max(1, width - used - flags.length - 1)) });
272
- tabChunks.push({ text: flags, paint: dim });
273
- out.push(line(tabChunks, width));
274
- // 2. query
275
- out.push(line([{ text: '> ', paint: cyan }, { text: state.query }, { text: '█', paint: cyan }], width));
276
- // 3. counts, clock, transient message, probe failures
277
- out.push(line([
278
- { text: `${state.rows.length}/${total}`, paint: dim },
279
- {
280
- text: state.catalog
281
- ? ` checked ${new Date(state.catalog.generatedAt).toLocaleTimeString()}`
282
- : ' collecting',
283
- paint: dim,
284
- },
285
- ...(state.loading && refreshNote(state.cache, true) === null
286
- ? [{ text: ' refreshing', paint: yellow }]
287
- : []),
288
- // The cache's three states. Fresh returns null and shows nothing.
289
- // Stale and slow is red, so it stands apart from an ordinary
290
- // refresh note.
291
- ...(() => {
292
- const note = refreshNote(state.cache, state.loading);
293
- return note === null ? [] : [{ text: ` ${note.text}`, paint: note.slow ? red : yellow }];
294
- })(),
295
- ...(state.message ? [{ text: ` ${state.message}`, paint: yellow }] : []),
296
- // A note beside the counts, not a modal, since you may only want to
297
- // look at what is already collected.
298
- ...(state.confirmingTrust
299
- ? [{ text: ' trust this repository? y/n', paint: yellow }]
300
- : withheldForTrust() > 0
301
- ? [
302
- {
303
- text: ` ${withheldForTrust()} hidden — repo not trusted (^s to trust)`,
304
- paint: yellow,
305
- },
306
- ]
307
- : []),
308
- ...(state.catalog?.reports ?? [])
309
- .filter((r) => r.status === 'error')
310
- .map((r) => ({ text: ` ${r.runner} failed`, paint: red })),
311
- ], width));
312
- // 4a. the settings screen, which replaces the list while it is open. It is
313
- // a separate view, not an overlay, so nothing below it renders.
314
- if (state.settings !== null) {
315
- const room = Math.max(1, height - out.length - 2);
316
- for (let i = 0; i < room; i++) {
317
- const text = state.settings[i];
318
- out.push(text === undefined
319
- ? CLEAR_EOL
320
- : line([{ text, paint: text.startsWith(' ') ? undefined : bold }], width));
321
- }
322
- out.push(line([{ text: '─'.repeat(width) }], width));
323
- out.push(line([{ text: `reading only — edit with \`${BIN} config set\` esc back`, paint: dim }], width));
324
- return HOME + out.join('\r\n') + CLEAR_BELOW;
325
- }
326
- // 4. the list, in the rows left over. The entry line takes one more row
327
- // than the key hints it replaces, so the list gives up a row while
328
- // arguments are typed, and the bottom line stays on screen.
329
- const listHeight = Math.max(1, height - out.length - (state.entering ? 5 : 4));
330
- clampScroll(at, listHeight);
331
- for (let i = 0; i < listHeight; i++) {
332
- const row = state.rows[state.scroll + i];
333
- if (!row) {
334
- out.push(CLEAR_EOL);
335
- continue;
336
- }
337
- out.push(line([
338
- { text: state.scroll + i === at ? '> ' : ' ', paint: cyan },
339
- { text: row.task.persistent.value ? '* ' : ' ', paint: green },
340
- ...chainChunks(row),
341
- ], width));
342
- }
343
- // 5. what Enter would run, always on screen
344
- const current = state.rows[at];
345
- out.push(line([{ text: '-'.repeat(width), paint: dim }], width));
346
- if (current) {
347
- const shape = chainOf(current.task.runner)
348
- .map((c) => c.label)
349
- .join(' > ');
350
- const gap = width - current.task.display.length - shape.length - 1;
351
- out.push(line(gap >= 3
352
- ? [
353
- { text: current.task.display, paint: bold },
354
- { text: ' '.repeat(gap) },
355
- { text: shape, paint: dim },
356
- ]
357
- : [{ text: current.task.display, paint: bold }], width));
358
- out.push(line([{ text: current.task.doc ?? current.task.detail ?? '', paint: dim }], width));
359
- }
360
- else {
361
- out.push(line([{ text: state.query ? 'no match' : 'nothing collected', paint: dim }], width));
362
- out.push(line([], width));
363
- }
364
- // 6. keys, or the entry line in their place while arguments are typed. It
365
- // replaces the key hints rather than sitting above them, because the only
366
- // keys that matter while typing are the two this line names, and an extra
367
- // row would push the list up.
368
- if (state.entering) {
369
- const { task, text } = state.entering;
370
- const shape = paramShape(task.parameters);
371
- out.push(line([
372
- { text: '$ ', paint: dim },
373
- { text: task.argv.join(' ') + ' ', paint: bold },
374
- { text },
375
- { text: '█', paint: cyan },
376
- ], width));
377
- out.push(line([{ text: ` takes ${shape} enter run esc back`, paint: dim }], width));
378
- }
379
- else {
380
- out.push(line([
381
- {
382
- text: 'enter run ^y copy tab runner ^e exact ^t services ^s trust ^r refresh , settings esc quit',
383
- paint: dim,
384
- },
385
- ], width));
386
- }
387
- return HOME + out.join('\r\n') + CLEAR_BELOW;
388
- }
389
- function clampScroll(at, listHeight) {
390
- if (at < state.scroll)
391
- state.scroll = at;
392
- if (at >= state.scroll + listHeight)
393
- state.scroll = at - listHeight + 1;
394
- if (state.scroll < 0)
395
- state.scroll = 0;
396
- }
397
- /**
398
- * Rebuild the visible rows and re-anchor the selection onto a task that is
399
- * still there.
400
- *
401
- * Split out of {@link draw} so it can be tested without a terminal. This is
402
- * why selection is held by task id: a refresh reorders and drops rows, and an
403
- * index would silently point at a different task, so the same keystroke
404
- * would run the wrong command.
405
- */
406
- export function recompute() {
407
- state.rows = visibleRows();
408
- if (state.selectedId !== null && !state.rows.some((r) => r.task.id === state.selectedId)) {
409
- state.selectedId = state.rows[0]?.task.id ?? null;
410
- }
411
- }
412
- function draw() {
413
- recompute();
414
- process.stdout.write(frame(process.stdout.columns || 100, process.stdout.rows || 30));
415
- }
416
- /**
417
- * The settings screen, as text: the same four sections the page shows, in
418
- * the config schema's key order, so both describe a project the same way.
419
- *
420
- * Read only, and it says so on screen. The page can edit because it has a
421
- * server to POST to and a pointer to click with. Editing here would need an
422
- * input mode per field, which is more than showing the configuration needs.
423
- * The screen points to `way config set` for edits.
424
- */
425
- async function settingsLines() {
426
- const loaded = await loadConfig(state.root, state.env, state.home);
427
- const where = (key) => {
428
- const layer = loaded.sources.get(key) ?? 'default';
429
- return layer === 'project' ? 'this project' : layer === 'user' ? 'your user config' : 'default';
430
- };
431
- const runners = (loaded.effective.runners ?? {});
432
- const disabled = new Set(runners.disabled ?? []);
433
- const known = [
434
- ...new Set([...(state.catalog?.reports ?? []).map((r) => r.runner), ...disabled]),
435
- ].sort();
436
- const out = [];
437
- out.push(`RUNNERS (${where('runners.disabled')})`);
438
- if (known.length === 0)
439
- out.push(' no runners detected');
440
- for (const name of known) {
441
- out.push(` ${disabled.has(name) ? '[ ]' : '[x]'} ${name}${disabled.has(name) ? ' not collected' : ''}`);
442
- }
443
- const order = runners.order ?? [];
444
- out.push(` order: ${order.length === 0 ? 'alphabetical' : order.join(' ')} (${where('runners.order')})`);
445
- out.push('');
446
- out.push(`EXECUTION (trust store)`);
447
- out.push(state.gate?.trusted === true
448
- ? ' trusted — runners may spawn probes'
449
- : withheldForTrust() > 0
450
- ? ' not trusted — runners that must be run to be read were skipped (^s to trust)'
451
- : ' execution is off for this project');
452
- out.push(` allowExec: ${String(loaded.effective.allowExec === true)} (${where('allowExec')})`);
453
- out.push(' a project file can only turn execution OFF; turning it on is the trust grant');
454
- out.push('');
455
- out.push(`DISCOVERY (${where('discovery')})`);
456
- out.push(` ${String(loaded.effective.discovery)}`);
457
- out.push('');
458
- out.push(`EXCLUDED PATHS (${where('excludePaths')})`);
459
- const excluded = loaded.effective.excludePaths ?? [];
460
- if (excluded.length === 0)
461
- out.push(' none');
462
- for (const path of excluded)
463
- out.push(` ${path}`);
464
- out.push('');
465
- out.push(`file: ${loaded.locations.project}`);
466
- for (const warning of loaded.warnings)
467
- out.push(`warning: ${warning}`);
468
- return out;
469
- }
470
- // ---------------------------------------------------------------- actions
471
- /**
472
- * Put a task's command on the clipboard.
473
- *
474
- * What is copied is not always `display`. A task bound to its own directory
475
- * gets the `cd` that makes it run, quoted where the directory needs it -
476
- * without it the paste fails. Enter is unaffected: `runAndExit` spawns with
477
- * the directory already. The web page's copy buttons apply the same rule
478
- * (`copyText` in web/view.ts).
479
- */
480
- function copy(task) {
481
- const dir = /^[\w.\-/@+]+$/.test(task.cwd) ? task.cwd : `'${task.cwd.replace(/'/g, "'\\''")}'`;
482
- // The text shown, so a control character in it cannot reach the paste.
483
- const text = terminalSafe(task.cwd === '.' ? task.display : `cd ${dir} && ${task.display}`);
484
- const bin = process.platform === 'darwin' ? 'pbcopy' : 'xclip';
485
- const args = process.platform === 'darwin' ? [] : ['-selection', 'clipboard'];
486
- const res = spawnRunner(bin, { absolutePathOnly: true }).run(args, {
487
- input: text,
488
- cwd: state.root,
489
- });
490
- return res.exitCode === 0;
491
- }
492
- let restored = false;
493
- /** Idempotent: both `runAndExit` and the exit hook call it. */
494
- function restoreTerminal() {
495
- if (restored)
496
- return;
497
- restored = true;
498
- if (process.stdin.isTTY)
499
- process.stdin.setRawMode(false);
500
- process.stdout.write(SHOW + ALT_OFF);
501
- }
502
- /**
503
- * Hand the terminal to the selected task and exit when it finishes. It
504
- * streams through `@osdlc/command-seam`, so the task has the terminal while
505
- * it runs.
506
- *
507
- * `argv` is spawned without a shell. Running `display` would be wrong: for a
508
- * recipe with parameters it has `<placeholders>`, which a shell reads as
509
- * redirections.
510
- */
511
- function runAndExit(task, args = []) {
512
- // Abandon any in-flight probe before the terminal changes hands.
513
- state.inFlight?.abort();
514
- restoreTerminal();
515
- // Print what actually runs, not `display`. For a task with parameters they
516
- // differ, and printing the placeholder form would misstate what ran.
517
- let argv;
518
- try {
519
- argv = runArgv(state.project, task, args);
520
- }
521
- catch (err) {
522
- process.stderr.write(`${APP}: ${terminalSafe(err instanceof Error ? err.message : String(err))}\n`);
523
- process.exit(1);
524
- }
525
- process.stdout.write(`${dim('$')} ${bold(terminalSafe(argv.join(' ')))}\n`);
526
- // Show the parameters only when none were given. A task run with its
527
- // arguments has just shown them on the line above.
528
- if (task.parameters.length > 0 && args.length === 0) {
529
- process.stdout.write(`${dim(` takes ${terminalSafe(paramShape(task.parameters))}`)}\n`);
530
- }
531
- const [binary, ...rest] = argv;
532
- const res = streamRunner(binary).run(rest, {
533
- cwd: task.cwd === '.' ? state.root : `${state.root}/${task.cwd}`,
534
- quiet: true,
535
- });
536
- // The spawn never started: no such binary, or no such directory. The row may
537
- // be out of date. It came from the store, and its task may have been
538
- // renamed or deleted since. Saying so gives the user something to act on.
539
- if (res.reason === 'spawn') {
540
- process.stderr.write(terminalSafe(`${APP}: ${binary}: ${res.error ?? 'could not start'}`) + '\n');
541
- const from = cacheFor(task.runner);
542
- if (from !== undefined && from.state === 'stale') {
543
- process.stderr.write(`${APP}: that row came from a cached listing of ${terminalSafe(task.runner)} taken ${humanAge(from.ageMs)}` +
544
- ` — the task may no longer exist; start ${BIN} again to re-probe\n`);
545
- }
546
- }
547
- process.exit(res.exitCode);
548
- }
549
- /**
550
- * Re-probe, with three protections: one probe in flight at a time, a
551
- * generation number so an older result is discarded, and an abort signal so
552
- * an abandoned probe stops.
553
- */
554
- async function refresh() {
555
- if (state.loading)
556
- return;
557
- const generation = ++state.generation;
558
- const controller = new AbortController();
559
- state.inFlight = controller;
560
- state.loading = true;
561
- state.message = '';
562
- draw();
563
- try {
564
- // Always a real probe, never a cache read. ^r means "ask again", and an
565
- // answer from the store would look the same as doing nothing. The probe
566
- // writes the store, so the next start still shows rows at once.
567
- const collected = await collectAndCache(state.project, state.root, { ...state.options, signal: controller.signal }, state.store);
568
- if (generation !== state.generation)
569
- return; // a newer refresh won
570
- state.catalog = orderedCatalog(collected, state.runnerOrder);
571
- // Everything on screen was measured just now, so nothing is stale.
572
- state.cache = freshStates(collected);
573
- }
574
- catch (err) {
575
- if (generation === state.generation) {
576
- state.message = `refresh failed: ${err instanceof Error ? err.message : String(err)}`;
577
- }
578
- }
579
- finally {
580
- if (generation === state.generation) {
581
- state.loading = false;
582
- state.inFlight = null;
583
- }
584
- }
585
- }
586
- /**
587
- * Grant trust, then re-probe in place so the runners appear where the note was.
588
- *
589
- * The hint is dropped at the same time. It tells the user to trust the
590
- * repository, which they just did.
591
- */
592
- async function grantTrust() {
593
- try {
594
- await appTrustStore({
595
- ...(state.env !== undefined ? { env: state.env } : {}),
596
- ...(state.home !== undefined ? { home: state.home } : {}),
597
- }).trust(state.root);
598
- }
599
- catch (err) {
600
- // Never silent. If the grant failed, the user must know why the runners
601
- // are still hidden.
602
- state.message = `trust failed: ${err instanceof Error ? err.message : String(err)}`;
603
- return;
604
- }
605
- const { execWithheldHint: _dropped, ...rest } = state.options;
606
- state.options = { ...rest, allowExec: true };
607
- if (state.gate)
608
- state.gate = { ...state.gate, allowExec: true, trusted: true, reason: 'allowed' };
609
- // Tool modules are code; they load at the next start, not mid-session.
610
- state.message = state.projectToolsPending
611
- ? `trusted — re-probing; the project's tools load the next time ${BIN} starts with execution allowed`
612
- : 'trusted — re-probing';
613
- // A probe started before the grant runs with the old settings, and
614
- // `refresh` ignores a call while one is running, so the grant would be
615
- // announced and never used. Abandon that probe first. `refresh` increases
616
- // the generation synchronously, so the abandoned probe cannot overwrite
617
- // the new result or its state.
618
- state.inFlight?.abort();
619
- state.inFlight = null;
620
- state.loading = false;
621
- await refresh();
622
- }
623
- function cycleRunner(step) {
624
- const names = tabs();
625
- const at = names.indexOf(state.runner);
626
- state.runner = names[(at + step + names.length) % names.length];
627
- state.selectedId = null;
628
- state.scroll = 0;
629
- }
630
- // ---------------------------------------------------------------- input
631
- /**
632
- * One keystroke.
633
- *
634
- * Exported for the same reason `state` is. `runTui` takes over a real
635
- * terminal and never returns, so tests reach the keys that touch disk
636
- * (settings, trust) only through this.
637
- */
638
- export function handle(key) {
639
- const listHeight = Math.max(1, (process.stdout.rows || 30) - 7);
640
- const move = (n) => {
641
- select(cursor() + n);
642
- state.message = '';
643
- };
644
- // The trust prompt takes exactly one keystroke. `y` grants. Any other key
645
- // cancels and is consumed, so it does not also do its usual job.
646
- if (state.confirmingTrust) {
647
- state.confirmingTrust = false;
648
- state.message = '';
649
- if (key === 'y' || key === 'Y')
650
- void grantTrust().finally(draw);
651
- return;
652
- }
653
- // The settings screen takes all keys while it is open, as the entry line
654
- // does, because the keys below act on a list that is not on screen.
655
- if (state.settings !== null) {
656
- if (key === '\x1b' || key === '\x03' || key === ',' || key === 'q')
657
- state.settings = null;
658
- return;
659
- }
660
- // While arguments are typed, every key is text or one of the two that end
661
- // it. This comes before the switch so ^y, tab and the arrows cannot act on
662
- // a list the user is no longer looking at.
663
- if (state.entering) {
664
- const entering = state.entering;
665
- if (key === '\x1b' || key === '\x03') {
666
- state.entering = null;
667
- return;
668
- }
669
- if (key === '\r' || key === '\n') {
670
- state.entering = null;
671
- runAndExit(entering.task, splitArgs(entering.text));
672
- return;
673
- }
674
- if (key === '\x7f' || key === '\x08') {
675
- entering.text = entering.text.slice(0, -1);
676
- return;
677
- }
678
- if (key === '\x15') {
679
- entering.text = '';
680
- return;
681
- } // ctrl-u
682
- if (key.length >= 1 && key >= ' ' && !key.startsWith('\x1b'))
683
- entering.text += key;
684
- return;
685
- }
686
- switch (key) {
687
- case '\x03': // ctrl-c
688
- case '\x1b': // esc
689
- restoreTerminal();
690
- process.exit(0);
691
- break;
692
- case '\r':
693
- case '\n': {
694
- const row = state.rows[cursor()];
695
- if (!row)
696
- break;
697
- // A recipe with parameters asks for its arguments first. Running it here
698
- // would spawn the command without them and hand over the terminal, so
699
- // the mistake could not be reported.
700
- if (row.task.parameters.length > 0)
701
- state.entering = { task: row.task, text: '' };
702
- else
703
- runAndExit(row.task);
704
- break;
705
- }
706
- case '\x19': {
707
- // ctrl-y
708
- const row = state.rows[cursor()];
709
- state.message = row ? (copy(row.task) ? 'copied' : 'clipboard unavailable') : '';
710
- break;
711
- }
712
- case '\x05': // ctrl-e
713
- state.mode = state.mode === 'fuzzy' ? 'exact' : 'fuzzy';
714
- state.selectedId = null;
715
- break;
716
- case '\x14': // ctrl-t
717
- state.servicesOnly = !state.servicesOnly;
718
- state.selectedId = null;
719
- break;
720
- case ',':
721
- // Loaded on open, not on every frame, because it reads from disk. A
722
- // config that will not parse throws, and without the catch that would
723
- // be an unhandled rejection instead of a message.
724
- void settingsLines()
725
- .then((lines) => {
726
- state.settings = lines;
727
- })
728
- .catch((err) => {
729
- state.message = `settings unavailable: ${err instanceof Error ? err.message : String(err)}`;
730
- })
731
- .finally(draw);
732
- break;
733
- case '\x12': // ctrl-r
734
- void refresh().finally(draw);
735
- break;
736
- case '\x13': // ctrl-s
737
- // Arms the question; `y` answers it. Nothing is written here.
738
- if (withheldForTrust() > 0)
739
- state.confirmingTrust = true;
740
- else
741
- state.message = 'nothing is withheld';
742
- break;
743
- case '\t':
744
- cycleRunner(1);
745
- break;
746
- case '\x1b[Z': // shift-tab
747
- cycleRunner(-1);
748
- break;
749
- case '\x1b[A':
750
- case '\x10':
751
- move(-1);
752
- break;
753
- case '\x1b[B':
754
- case '\x0e':
755
- move(1);
756
- break;
757
- case '\x1b[5~':
758
- move(-listHeight);
759
- break;
760
- case '\x1b[6~':
761
- move(listHeight);
762
- break;
763
- case '\x1b[H':
764
- case '\x01':
765
- select(0);
766
- break;
767
- case '\x1b[F':
768
- select(state.rows.length - 1);
769
- break;
770
- case '\x7f':
771
- case '\x08':
772
- state.query = state.query.slice(0, -1);
773
- state.selectedId = null;
774
- break;
775
- case '\x15': // ctrl-u
776
- state.query = '';
777
- state.selectedId = null;
778
- break;
779
- default:
780
- if (key.length >= 1 && key >= ' ' && !key.startsWith('\x1b')) {
781
- state.query += key;
782
- state.selectedId = null;
783
- }
784
- }
785
- }
786
- export async function runTui({ project, projectToolsPending, root, options, runnerOrder, gate, env, home, }) {
787
- if (!process.stdin.isTTY) {
788
- process.stderr.write(`${APP}: the terminal UI needs a TTY; use --serve for the page, or --json for data.\n`);
789
- return 2;
790
- }
791
- state.project = project;
792
- state.projectToolsPending = projectToolsPending ?? false;
793
- state.root = root;
794
- state.options = options;
795
- state.runnerOrder = runnerOrder;
796
- state.gate = gate ?? null;
797
- state.env = env;
798
- state.home = home;
799
- state.store = cacheDir(env, home);
800
- process.stdout.write(ALT_ON + HIDE);
801
- process.stdin.setRawMode(true);
802
- process.stdin.resume();
803
- process.stdin.setEncoding('utf8');
804
- process.on('exit', restoreTerminal);
805
- process.on('SIGINT', () => {
806
- restoreTerminal();
807
- process.exit(0);
808
- });
809
- process.stdout.on('resize', draw);
810
- process.stdin.on('data', (chunk) => {
811
- // A paste or a fast key repeat arrives as one chunk; escape sequences must
812
- // stay whole, so split on ESC rather than per character.
813
- for (const key of chunk.split(/(?=\x1b)/)) {
814
- if (key.startsWith('\x1b') || key.length === 1)
815
- handle(key);
816
- else
817
- for (const ch of key)
818
- handle(ch);
819
- }
820
- draw();
821
- });
822
- // Show the store, then refresh. The first frame costs a few file hashes
823
- // rather than a full probe, so even when the slowest runner takes seconds
824
- // the tasks show at once, marked as cached, instead of an empty frame. When
825
- // the probe finishes, the rows update in place.
826
- const stored = await readCachedCatalog(project, root, options, state.store);
827
- // Shown only when something came from the store. With execution off, an
828
- // empty store still returns withheld reports, which would look like an
829
- // empty answer.
830
- if (stored.catalog !== null && fromStore(stored)) {
831
- state.catalog = orderedCatalog(stored.catalog, runnerOrder);
832
- state.cache = stored.runners;
833
- }
834
- draw();
835
- await refresh();
836
- draw();
837
- // The stdin handler drives everything from here; this promise never settles,
838
- // because every exit path calls `process.exit`.
839
- return new Promise(() => { });
840
- }