@osdlc/wayfinder 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/CONTRIBUTING.md +6 -0
  3. package/README.md +295 -150
  4. package/SECURITY.md +19 -5
  5. package/dist/actions.d.ts +23 -0
  6. package/dist/actions.js +97 -0
  7. package/dist/app.d.ts +1 -13
  8. package/dist/app.js +1 -13
  9. package/dist/args.d.ts +11 -6
  10. package/dist/args.js +25 -7
  11. package/dist/cache.d.ts +2 -4
  12. package/dist/cache.js +5 -10
  13. package/dist/catalog.d.ts +30 -3
  14. package/dist/catalog.js +87 -11
  15. package/dist/clean-command.d.ts +65 -36
  16. package/dist/clean-command.js +372 -226
  17. package/dist/cli.d.ts +24 -57
  18. package/dist/cli.js +139 -568
  19. package/dist/commands/browse.d.ts +128 -0
  20. package/dist/commands/browse.js +151 -0
  21. package/dist/commands/index.d.ts +25 -0
  22. package/dist/commands/index.js +71 -0
  23. package/dist/commands/list.d.ts +208 -0
  24. package/dist/commands/list.js +127 -0
  25. package/dist/commands/query.d.ts +166 -0
  26. package/dist/commands/query.js +73 -0
  27. package/dist/commands/run.d.ts +114 -0
  28. package/dist/commands/run.js +139 -0
  29. package/dist/commands/shared.d.ts +152 -0
  30. package/dist/commands/shared.js +209 -0
  31. package/dist/config-command.d.ts +27 -43
  32. package/dist/config-command.js +129 -330
  33. package/dist/config-keys.d.ts +25 -0
  34. package/dist/config-keys.js +29 -0
  35. package/dist/config.d.ts +271 -257
  36. package/dist/config.js +610 -460
  37. package/dist/core/copy-text.d.ts +30 -0
  38. package/dist/core/copy-text.js +50 -0
  39. package/dist/core/filter.d.ts +55 -0
  40. package/dist/core/filter.js +59 -0
  41. package/dist/core/run.d.ts +22 -0
  42. package/dist/core/run.js +59 -0
  43. package/dist/core/saved-view.d.ts +59 -0
  44. package/dist/core/saved-view.js +119 -0
  45. package/dist/core/session.d.ts +262 -0
  46. package/dist/core/session.js +589 -0
  47. package/dist/core/skills.d.ts +53 -0
  48. package/dist/core/skills.js +54 -0
  49. package/dist/core/unknowns.d.ts +72 -0
  50. package/dist/core/unknowns.js +68 -0
  51. package/dist/devlink.d.ts +3 -0
  52. package/dist/devlink.js +5 -2
  53. package/dist/document-schemas.generated.d.ts +22 -0
  54. package/dist/document-schemas.generated.js +916 -0
  55. package/dist/documents.d.ts +432 -0
  56. package/dist/documents.js +163 -0
  57. package/dist/groups.d.ts +22 -26
  58. package/dist/groups.js +13 -29
  59. package/dist/guide.d.ts +26 -13
  60. package/dist/guide.js +119 -103
  61. package/dist/index.d.ts +112 -0
  62. package/dist/index.js +58 -0
  63. package/dist/keys.d.ts +51 -0
  64. package/dist/keys.js +273 -0
  65. package/dist/page.d.ts +18 -8
  66. package/dist/page.js +28 -17
  67. package/dist/providers-command.d.ts +81 -20
  68. package/dist/providers-command.js +33 -75
  69. package/dist/schema.d.ts +48 -0
  70. package/dist/schema.js +61 -0
  71. package/dist/serve/auth.d.ts +46 -0
  72. package/dist/serve/auth.js +82 -0
  73. package/dist/serve/catalog-share.d.ts +51 -0
  74. package/dist/serve/catalog-share.js +116 -0
  75. package/dist/serve/index.d.ts +98 -0
  76. package/dist/serve/index.js +251 -0
  77. package/dist/serve/routes.d.ts +60 -0
  78. package/dist/serve/routes.js +186 -0
  79. package/dist/serve/terminal-input.d.ts +50 -0
  80. package/dist/serve/terminal-input.js +108 -0
  81. package/dist/skills.d.ts +19 -0
  82. package/dist/skills.js +54 -0
  83. package/dist/terminal-text.d.ts +8 -0
  84. package/dist/terminal-text.js +19 -6
  85. package/dist/tool-info.d.ts +24 -0
  86. package/dist/tool-info.js +17 -0
  87. package/dist/trust-command.d.ts +15 -27
  88. package/dist/trust-command.js +110 -208
  89. package/dist/trust-store.d.ts +5 -10
  90. package/dist/trust-store.js +9 -42
  91. package/dist/tui/app.d.ts +180 -0
  92. package/dist/tui/app.js +1278 -0
  93. package/dist/tui/copy.d.ts +29 -0
  94. package/dist/tui/copy.js +39 -0
  95. package/dist/tui/index.d.ts +33 -0
  96. package/dist/tui/index.js +97 -0
  97. package/dist/tui/keys-input.d.ts +27 -0
  98. package/dist/tui/keys-input.js +87 -0
  99. package/dist/tui/settings.d.ts +94 -0
  100. package/dist/tui/settings.js +198 -0
  101. package/dist/tui/style.d.ts +62 -0
  102. package/dist/tui/style.js +77 -0
  103. package/dist/version.d.ts +6 -0
  104. package/dist/version.js +7 -0
  105. package/dist/vocabulary.d.ts +89 -0
  106. package/dist/vocabulary.js +153 -0
  107. package/dist/web/main.js +1965 -568
  108. package/dist/web/page.html +39 -33
  109. package/dist/web/styles.css +457 -329
  110. package/dist/xdg.d.ts +76 -4
  111. package/dist/xdg.js +77 -5
  112. package/package.json +28 -9
  113. package/schema/config.json +133 -0
  114. package/dist/http.d.ts +0 -22
  115. package/dist/http.js +0 -149
  116. package/dist/origin-owner.d.ts +0 -19
  117. package/dist/origin-owner.js +0 -85
  118. package/dist/serve.d.ts +0 -98
  119. package/dist/serve.js +0 -671
  120. package/dist/tui.d.ts +0 -177
  121. package/dist/tui.js +0 -840
@@ -0,0 +1,251 @@
1
+ /**
2
+ * The web view: the same catalog as a page you can search in a browser.
3
+ *
4
+ * It is a server rather than a generated file, because a file goes out of date
5
+ * as soon as a task is added. The page calls the command tree over cli-tool's
6
+ * HTTP adapter (`routes.ts`), so each request reads the repository as it is
7
+ * now, with the same rules as the command line. The catalog the server holds
8
+ * between those requests is `catalog-share.ts`. The page signs in with a
9
+ * one-shot boot token (`auth.ts`).
10
+ */
11
+ import { createHttpApi, serveHttp } from '@osdlc/cli-tool/http';
12
+ import { commandString, spawnRunnerAsync } from '@osdlc/command-seam';
13
+ import { humanAge } from '@osdlc/system-model/duration';
14
+ import { APP, BIN } from "../app.js";
15
+ import { handOff as defaultHandOff } from "../core/run.js";
16
+ import { catalogDocument } from "../commands/list.js";
17
+ import { buildPage } from "../page.js";
18
+ import { terminalSafe } from "../terminal-text.js";
19
+ import { WITHHELD, runnerLabel, staleLabel } from "../vocabulary.js";
20
+ import { createSignIn } from "./auth.js";
21
+ import { createRoutes } from "./routes.js";
22
+ import { readTerminalLines } from "./terminal-input.js";
23
+ /** The HTTP status for each `run` error code the page can act on. */
24
+ const RUN_STATUS = {
25
+ 'task-not-found': 404,
26
+ 'ambiguous-task': 409,
27
+ 'not-runnable': 422,
28
+ 'bad-arguments': 400,
29
+ // Not 409: the page reads 409 as another run holding the terminal.
30
+ 'task-changed': 412,
31
+ usage: 400,
32
+ };
33
+ /**
34
+ * Bind the port and return the server, without printing or opening anything.
35
+ * Split from {@link serve} so a test can bind a port, send real requests and
36
+ * stop again.
37
+ */
38
+ export async function startServer(options) {
39
+ const { session, app } = options;
40
+ const globals = { ...options.globals, dir: session.root };
41
+ const context = { cwd: options.cwd, env: session.env };
42
+ const runHandOff = options.handOff ?? defaultHandOff;
43
+ let settle = () => { };
44
+ const finished = new Promise((resolve) => {
45
+ settle = resolve;
46
+ });
47
+ // The redeem is refused, so a replay cannot sign in. Warn in case it was
48
+ // not the person, and keep serving the sessions already signed in. There
49
+ // is one bearer token per server, so only a restart signs out whoever
50
+ // redeemed the link first.
51
+ const signIn = createSignIn(Date.now, () => {
52
+ options.stderr(`${BIN}: warning: the sign-in link was used again and refused. ` +
53
+ `If that was not you, stop the server (Ctrl-C) and start it again: ` +
54
+ `a new link does not sign out whoever used this one\n`);
55
+ });
56
+ const resolveRun = async (id, args) => {
57
+ const result = await app.call(['run'],
58
+ // From the saved listing, then its runner probed again, so a task that
59
+ // changed since the page drew it is refused rather than run.
60
+ { id, rest: args, dryRun: true, cached: true, check: true }, context, { surface: 'http', globals });
61
+ if (result.status === 'ok') {
62
+ const doc = result.document;
63
+ return { ok: true, display: doc.display, argv: doc.argv, env: doc.env, cwd: doc.cwd };
64
+ }
65
+ if (result.status === 'refused') {
66
+ return { ok: false, status: 403, error: { kind: 'error', message: result.message } };
67
+ }
68
+ return {
69
+ ok: false,
70
+ status: RUN_STATUS[result.code] ?? 422,
71
+ error: {
72
+ kind: 'error',
73
+ code: result.code,
74
+ message: result.message,
75
+ ...(result.hint !== undefined ? { hint: result.hint } : {}),
76
+ },
77
+ };
78
+ };
79
+ // The API is made once the port is known, so it checks Host against it.
80
+ let handler;
81
+ const server = await serveHttp((request) => handler(request), { port: options.port ?? 0 });
82
+ const api = createHttpApi(app, {
83
+ context,
84
+ prefix: '/api',
85
+ globals,
86
+ port: server.port,
87
+ // A trust grant answers 428 with a nonce, so the page must ask the person
88
+ // before it sends the grant again.
89
+ confirm: [['trust']],
90
+ });
91
+ let stopped = false;
92
+ let markStopped = () => { };
93
+ const stoppedPromise = new Promise((resolve) => {
94
+ markStopped = resolve;
95
+ });
96
+ const stop = async () => {
97
+ if (stopped)
98
+ return;
99
+ stopped = true;
100
+ // A probe still running would share the terminal with a handed-off task.
101
+ options.share?.stop();
102
+ await server.stop();
103
+ markStopped();
104
+ };
105
+ handler = createRoutes({
106
+ api,
107
+ signIn,
108
+ async page(nonce) {
109
+ const theme = await session.reloadSettings().then((s) => s.settings.theme.value, () => 'system');
110
+ return buildPage({ theme, nonce });
111
+ },
112
+ resolveRun,
113
+ handOff(plan) {
114
+ void (async () => {
115
+ await stop();
116
+ options.stderr(`$ ${terminalSafe(commandString(plan.argv))}\n`);
117
+ const ended = runHandOff(plan);
118
+ if (ended.error !== undefined) {
119
+ options.stderr(`${BIN}: ${terminalSafe(plan.argv[0] ?? '')}: ${ended.error}\n`);
120
+ }
121
+ settle(ended.exit);
122
+ })();
123
+ },
124
+ });
125
+ if (options.signal !== undefined) {
126
+ const onAbort = () => {
127
+ void stop().then(() => settle(null));
128
+ };
129
+ if (options.signal.aborted)
130
+ onAbort();
131
+ else
132
+ options.signal.addEventListener('abort', onAbort, { once: true });
133
+ }
134
+ return {
135
+ server,
136
+ signIn,
137
+ finished,
138
+ stopped: stoppedPromise,
139
+ stop: async () => {
140
+ await stop();
141
+ settle(null);
142
+ },
143
+ };
144
+ }
145
+ /**
146
+ * The first lines `serve` prints: the address, the root, what was collected
147
+ * and what came from the store. Repository text in them is terminal-safe.
148
+ */
149
+ export function startupSummary(address, first) {
150
+ // A withheld runner reports `absent`. It is named withheld here, because
151
+ // absent means the repository does not have it.
152
+ const counts = first.catalog.reports
153
+ .map((r) => {
154
+ const state = r.skippedForExec ? WITHHELD : r.status === 'ok' ? r.tasks.length : r.status;
155
+ return `${runnerLabel(r.runner)} ${state}`;
156
+ })
157
+ .join(', ');
158
+ const stale = first.cache.filter((c) => c.state === 'stale');
159
+ let out = `${APP} ${address}\n`;
160
+ out += ` root ${terminalSafe(first.catalog.root)}\n`;
161
+ out += ` collected ${terminalSafe(counts)}\n`;
162
+ if (stale.length > 0) {
163
+ const aged = stale
164
+ .map((c) => `${runnerLabel(c.runner)} (${staleLabel(c.reason, c.ageMs)})`)
165
+ .join(', ');
166
+ out += ` cached ${terminalSafe(aged)}; the page re-reads it\n`;
167
+ }
168
+ else if (first.origin === 'saved') {
169
+ const ages = first.cache.flatMap((c) => (c.ageMs !== undefined ? [c.ageMs] : []));
170
+ const age = ages.length > 0 ? `, ${humanAge(Math.max(...ages))}` : '';
171
+ out += ` cached the last listing${age}; the page re-reads it\n`;
172
+ }
173
+ return out;
174
+ }
175
+ /** How long the browser opener may run before it is left to the browser. */
176
+ const OPENER_TIMEOUT_MS = 10_000;
177
+ /** The program that opens a URL in the default browser on `platform`, before the URL. */
178
+ export function browserOpener(platform) {
179
+ if (platform === 'darwin')
180
+ return { binary: 'open', args: [] };
181
+ if (platform === 'win32')
182
+ return { binary: 'rundll32', args: ['url.dll,FileProtocolHandler'] };
183
+ return { binary: 'xdg-open', args: [] };
184
+ }
185
+ /**
186
+ * Serve the page until the signal aborts or a run takes the terminal. Returns
187
+ * the task's exit code after a run, or null when the server was stopped.
188
+ */
189
+ export async function serve(options) {
190
+ const web = await startServer(options);
191
+ const address = web.server.url;
192
+ const bootUrl = () => `${address}/?boot=${web.signIn.bootToken}`;
193
+ // The saved view when there is one, else the store, so the address shows
194
+ // at once. A probe starts now; the page's first fresh read joins it.
195
+ const session = options.session;
196
+ const first = (await session.savedCatalog()) ?? (await session.catalog({ cached: true }));
197
+ const share = options.share;
198
+ if (share !== undefined) {
199
+ const key = session.viewKey();
200
+ const documentOf = (snapshot) => catalogDocument(snapshot, session.unknowns(snapshot), {}, session.settings().trustedTools);
201
+ share.remember(key, documentOf(first));
202
+ share.activate();
203
+ // It waits on the share's own signal, so it runs to the end unless the
204
+ // server stops, as on a hand-off.
205
+ void share
206
+ .fresh(key, async (signal) => documentOf(await session.catalog({ signal })), {
207
+ join: true,
208
+ signal: share.signal,
209
+ })
210
+ .catch(() => { });
211
+ }
212
+ web.signIn.arm();
213
+ options.stdout(startupSummary(address, first));
214
+ options.stdout(` live the page refreshes on focus and every 15s; Refresh re-reads\n`);
215
+ options.stdout(` stop Ctrl-C\n`);
216
+ /** Open the current link, or print it when there is no browser to open. */
217
+ const show = () => {
218
+ if (options.open === false) {
219
+ options.stdout(` open ${bootUrl()}\n`);
220
+ options.stdout(` signs one browser tab in once; it expires in 60 seconds if unused\n`);
221
+ return;
222
+ }
223
+ // Best effort: a headless or remote shell has no browser. Not awaited: a
224
+ // generic xdg-open can wait on the browser it starts, and the server must
225
+ // answer meanwhile. An opener still running at the deadline is taken to
226
+ // have opened one.
227
+ const url = bootUrl();
228
+ const opener = browserOpener(process.platform);
229
+ void spawnRunnerAsync(opener.binary, { absolutePathOnly: true })
230
+ .run([...opener.args, url], { cwd: options.session.root, timeoutMs: OPENER_TIMEOUT_MS })
231
+ .then((proc) => {
232
+ if (proc.reason !== 'timeout' && proc.exitCode !== 0) {
233
+ options.stdout(` (could not open a browser; visit ${url} within 60 seconds)\n`);
234
+ }
235
+ });
236
+ };
237
+ // Enter prints a new link. Read only in the foreground: see terminal-input.ts.
238
+ const lines = options.input !== undefined
239
+ ? readTerminalLines(options.input, () => {
240
+ web.signIn.renew();
241
+ show();
242
+ }, { foreground: options.foreground, signals: options.jobSignals })
243
+ : undefined;
244
+ // Stop reading before a task gets the terminal, and when the server stops.
245
+ void web.stopped.then(() => lines?.stop());
246
+ if (lines !== undefined && (await lines.ready)) {
247
+ options.stdout(` new tab press Enter here for a new sign-in link\n`);
248
+ }
249
+ show();
250
+ return web.finished;
251
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The web view's routes.
3
+ *
4
+ * | Route | Answers |
5
+ * |---|---|
6
+ * | `/api/...` | cli-tool's HTTP adapter: `GET /api/schema`, `GET /api/help`, `POST /api/commands/<command>` |
7
+ * | `GET /` | the page. It holds no secret, so it needs no token |
8
+ * | `POST /session` | the bearer token, once, for the boot token (see `auth.ts`) |
9
+ * | `POST /run` | hands this server's terminal to a task, then stops the server |
10
+ *
11
+ * Every page action other than Run is a command of the tree, called through
12
+ * `/api/commands`, so the page and the command line do the same thing: the
13
+ * catalog is `list`, a trust grant is `trust`, a saved setting is `config
14
+ * set`. Run is a route of its own because it ends the server: it resolves the
15
+ * task with `run --dry-run`, answers, stops listening and then runs it.
16
+ *
17
+ * Every route passes the adapter's Host and Origin checks first.
18
+ */
19
+ import type { HttpApi } from '@osdlc/cli-tool/http';
20
+ import type { SignIn } from './auth.ts';
21
+ /**
22
+ * The page's content security policy. Only the page's own script runs, and
23
+ * it may talk only to this server. The page builds HTML from repository text,
24
+ * so a missed escape must not run a script that could read the bearer token.
25
+ * Styles stay inline: the page sets `style` attributes as it lays out rows.
26
+ */
27
+ export declare function pagePolicy(nonce: string): string;
28
+ /** What resolving a run answers: the plan, or the error document and its status. */
29
+ export type RunResolution = {
30
+ ok: true;
31
+ display: string;
32
+ argv: string[];
33
+ env: Record<string, string>;
34
+ cwd: string;
35
+ } | {
36
+ ok: false;
37
+ status: number;
38
+ error: Record<string, unknown>;
39
+ };
40
+ /** What {@link createRoutes} needs. */
41
+ export interface RoutesOptions {
42
+ api: HttpApi;
43
+ signIn: SignIn;
44
+ /**
45
+ * The page's HTML, its script tagged with `nonce`. Built per request, so a
46
+ * checkout's edit needs a reload, not a restart.
47
+ */
48
+ page(nonce: string): Promise<string>;
49
+ /** Resolve task `id` with `args` the way `run --dry-run` does. */
50
+ resolveRun(id: string, args: string[]): Promise<RunResolution>;
51
+ /**
52
+ * Called once, after the run's answer is sent, with the plan to run. It
53
+ * stops the server and hands the terminal to the task.
54
+ */
55
+ handOff(plan: Extract<RunResolution, {
56
+ ok: true;
57
+ }>): void;
58
+ }
59
+ /** The request handler for the web view. */
60
+ export declare function createRoutes(opts: RoutesOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,186 @@
1
+ /**
2
+ * The web view's routes.
3
+ *
4
+ * | Route | Answers |
5
+ * |---|---|
6
+ * | `/api/...` | cli-tool's HTTP adapter: `GET /api/schema`, `GET /api/help`, `POST /api/commands/<command>` |
7
+ * | `GET /` | the page. It holds no secret, so it needs no token |
8
+ * | `POST /session` | the bearer token, once, for the boot token (see `auth.ts`) |
9
+ * | `POST /run` | hands this server's terminal to a task, then stops the server |
10
+ *
11
+ * Every page action other than Run is a command of the tree, called through
12
+ * `/api/commands`, so the page and the command line do the same thing: the
13
+ * catalog is `list`, a trust grant is `trust`, a saved setting is `config
14
+ * set`. Run is a route of its own because it ends the server: it resolves the
15
+ * task with `run --dry-run`, answers, stops listening and then runs it.
16
+ *
17
+ * Every route passes the adapter's Host and Origin checks first.
18
+ */
19
+ import { randomBytes } from 'node:crypto';
20
+ const HEADERS = {
21
+ 'cache-control': 'no-store',
22
+ 'x-content-type-options': 'nosniff',
23
+ };
24
+ /** The largest body `/session` and `/run` read. Both take a few short strings. */
25
+ const MAX_BODY = 64 * 1024;
26
+ /**
27
+ * The page's content security policy. Only the page's own script runs, and
28
+ * it may talk only to this server. The page builds HTML from repository text,
29
+ * so a missed escape must not run a script that could read the bearer token.
30
+ * Styles stay inline: the page sets `style` attributes as it lays out rows.
31
+ */
32
+ export function pagePolicy(nonce) {
33
+ return [
34
+ "default-src 'none'",
35
+ `script-src 'nonce-${nonce}'`,
36
+ "style-src 'unsafe-inline'",
37
+ "connect-src 'self'",
38
+ "base-uri 'none'",
39
+ "form-action 'none'",
40
+ "frame-ancestors 'none'",
41
+ ].join('; ');
42
+ }
43
+ function json(body, status = 200) {
44
+ return Response.json(body, { status, headers: HEADERS });
45
+ }
46
+ function text(body, status, extra = {}) {
47
+ return new Response(body, {
48
+ status,
49
+ headers: { ...HEADERS, 'content-type': 'text/plain; charset=utf-8', ...extra },
50
+ });
51
+ }
52
+ /**
53
+ * At most `max` bytes of `request`'s body, or null when it is larger. Read as
54
+ * a stream and given up past `max`: `/session` needs no token, so a chunked
55
+ * body of any size must not be buffered first.
56
+ */
57
+ async function readBody(request, max) {
58
+ if (Number(request.headers.get('content-length') ?? '0') > max)
59
+ return null;
60
+ if (request.body === null)
61
+ return '';
62
+ const reader = request.body.getReader();
63
+ const chunks = [];
64
+ let size = 0;
65
+ for (;;) {
66
+ const { done, value } = await reader.read();
67
+ if (done)
68
+ break;
69
+ size += value.byteLength;
70
+ if (size > max) {
71
+ void reader.cancel().catch(() => { });
72
+ return null;
73
+ }
74
+ chunks.push(value);
75
+ }
76
+ return new TextDecoder().decode(Buffer.concat(chunks));
77
+ }
78
+ /** The JSON body of `request`, or a Response refusing it. */
79
+ async function readJson(request) {
80
+ if (!/^application\/json\b/i.test(request.headers.get('content-type') ?? '')) {
81
+ return text('send application/json', 415);
82
+ }
83
+ const raw = await readBody(request, MAX_BODY);
84
+ if (raw === null)
85
+ return text('the body is too large', 413);
86
+ try {
87
+ return JSON.parse(raw);
88
+ }
89
+ catch {
90
+ return text('the body is not JSON', 400);
91
+ }
92
+ }
93
+ function isRecord(value) {
94
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
95
+ }
96
+ /** The request handler for the web view. */
97
+ export function createRoutes(opts) {
98
+ const { api } = opts;
99
+ /**
100
+ * Set by the first accepted run. There is one terminal, so a second run
101
+ * cannot have it, and gets a 409.
102
+ */
103
+ let handedOff = false;
104
+ const run = async (request) => {
105
+ if (!api.hasToken(request)) {
106
+ return text('unauthorized', 401, { 'www-authenticate': 'Bearer' });
107
+ }
108
+ // Set before the first `await`, so two requests cannot both pass.
109
+ if (handedOff)
110
+ return text('another run already has the terminal', 409);
111
+ handedOff = true;
112
+ let resolved;
113
+ try {
114
+ const body = await readJson(request);
115
+ if (body instanceof Response) {
116
+ handedOff = false;
117
+ return body;
118
+ }
119
+ // An id and trailing arguments, nothing else. The task, from a catalog
120
+ // this server built, supplies the binary, the leading arguments and the
121
+ // cwd, so a caller can at most pass arguments to a task in the catalog.
122
+ const id = isRecord(body) ? body['id'] : undefined;
123
+ const args = isRecord(body) ? (body['args'] ?? []) : undefined;
124
+ if (typeof id !== 'string' ||
125
+ !Array.isArray(args) ||
126
+ !args.every((a) => typeof a === 'string')) {
127
+ handedOff = false;
128
+ return text('expected { id: string, args?: string[] }', 400);
129
+ }
130
+ resolved = await opts.resolveRun(id, args);
131
+ }
132
+ catch (err) {
133
+ handedOff = false;
134
+ throw err;
135
+ }
136
+ if (!resolved.ok) {
137
+ handedOff = false;
138
+ return json(resolved.error, resolved.status);
139
+ }
140
+ const plan = resolved;
141
+ // The answer must reach the browser before the task takes the terminal.
142
+ // One event-loop turn lets it be written, and lets a POST queued on
143
+ // another socket be read and answered 409 rather than reset.
144
+ setTimeout(() => opts.handOff(plan), 0);
145
+ return json({ ok: true, display: plan.display, argv: plan.argv });
146
+ };
147
+ return async (request) => {
148
+ if (api.handles(request))
149
+ return api.fetch(request);
150
+ const refused = api.checkOrigin(request);
151
+ if (refused !== null)
152
+ return refused;
153
+ const path = new URL(request.url).pathname;
154
+ const method = request.method;
155
+ if (path === '/' || path === '/index.html') {
156
+ if (method !== 'GET' && method !== 'HEAD')
157
+ return text('use GET', 405, { allow: 'GET' });
158
+ const nonce = randomBytes(16).toString('base64');
159
+ return new Response(await opts.page(nonce), {
160
+ headers: {
161
+ ...HEADERS,
162
+ 'content-type': 'text/html; charset=utf-8',
163
+ 'content-security-policy': pagePolicy(nonce),
164
+ },
165
+ });
166
+ }
167
+ if (path === '/session') {
168
+ if (method !== 'POST')
169
+ return text('use POST', 405, { allow: 'POST' });
170
+ const body = await readJson(request);
171
+ if (body instanceof Response)
172
+ return body;
173
+ // One answer for every failure, so a caller cannot tell which check failed.
174
+ if (!opts.signIn.redeem(isRecord(body) ? body['boot'] : undefined)) {
175
+ return text('unauthorized', 401);
176
+ }
177
+ return json({ token: api.token });
178
+ }
179
+ if (path === '/run') {
180
+ if (method !== 'POST')
181
+ return text('use POST', 405, { allow: 'POST' });
182
+ return run(request);
183
+ }
184
+ return text('not found', 404);
185
+ };
186
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Enter in the `way serve` terminal. A background job that reads its terminal
3
+ * gets `SIGTTIN`, which stops it, so `way serve &` would stop serving. Lines
4
+ * are read only while the process is in the terminal's foreground process
5
+ * group. Ctrl-Z stops reading before the process stops, and a resume (`fg` or
6
+ * `bg`) checks again. In the background the check repeats, since `fg` on a
7
+ * running job sends no signal.
8
+ */
9
+ /**
10
+ * True when `ps -o tpgid= -o pgid=` output says the process leads the
11
+ * terminal's foreground group: both ids are equal and positive. A process
12
+ * with no terminal has a `tpgid` of 0 or -1.
13
+ */
14
+ export declare function foregroundFromPs(out: string): boolean;
15
+ /**
16
+ * Whether this process is in its terminal's foreground group. Always true on
17
+ * Windows, which has no job control. False when `ps` fails, so the terminal
18
+ * is not read.
19
+ */
20
+ export declare function inForeground(): Promise<boolean>;
21
+ /** The job-control signals the reader follows. Tests pass a stand-in. */
22
+ export interface JobSignals {
23
+ on(signal: 'SIGTSTP' | 'SIGCONT', listener: () => void): unknown;
24
+ off(signal: 'SIGTSTP' | 'SIGCONT', listener: () => void): unknown;
25
+ /** Stop this process, as Ctrl-Z would have. */
26
+ suspend(): void;
27
+ }
28
+ /** The process's own job-control signals. None on Windows. */
29
+ export declare const processJobSignals: JobSignals | null;
30
+ /** What {@link readTerminalLines} needs. */
31
+ export interface TerminalLinesOptions {
32
+ /** Whether the process may read the terminal now. Default {@link inForeground}. */
33
+ foreground?: (() => Promise<boolean>) | undefined;
34
+ /** Default {@link processJobSignals}. */
35
+ signals?: JobSignals | null | undefined;
36
+ /** How often to check again while in the background. Default 1 second. */
37
+ pollMs?: number | undefined;
38
+ }
39
+ /** A running reader. */
40
+ export interface TerminalLines {
41
+ /** Settles after the first foreground check, with whether lines are read. */
42
+ ready: Promise<boolean>;
43
+ /** Stop reading and drop the signal listeners. */
44
+ stop(): void;
45
+ }
46
+ /**
47
+ * Call `onLine` for each Enter typed on `input`, while the process is in the
48
+ * foreground.
49
+ */
50
+ export declare function readTerminalLines(input: NodeJS.ReadableStream, onLine: () => void, options?: TerminalLinesOptions): TerminalLines;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Enter in the `way serve` terminal. A background job that reads its terminal
3
+ * gets `SIGTTIN`, which stops it, so `way serve &` would stop serving. Lines
4
+ * are read only while the process is in the terminal's foreground process
5
+ * group. Ctrl-Z stops reading before the process stops, and a resume (`fg` or
6
+ * `bg`) checks again. In the background the check repeats, since `fg` on a
7
+ * running job sends no signal.
8
+ */
9
+ import { spawnRunnerAsync } from '@osdlc/command-seam';
10
+ /** How long the foreground check may take. */
11
+ const PS_TIMEOUT_MS = 2_000;
12
+ /** How often a background process checks whether it is in the foreground. */
13
+ const POLL_MS = 1_000;
14
+ /**
15
+ * True when `ps -o tpgid= -o pgid=` output says the process leads the
16
+ * terminal's foreground group: both ids are equal and positive. A process
17
+ * with no terminal has a `tpgid` of 0 or -1.
18
+ */
19
+ export function foregroundFromPs(out) {
20
+ const [tpgid, pgid, extra] = out.trim().split(/\s+/);
21
+ if (extra !== undefined || tpgid === undefined || pgid === undefined)
22
+ return false;
23
+ return /^\d+$/.test(tpgid) && Number(tpgid) > 0 && tpgid === pgid;
24
+ }
25
+ /**
26
+ * Whether this process is in its terminal's foreground group. Always true on
27
+ * Windows, which has no job control. False when `ps` fails, so the terminal
28
+ * is not read.
29
+ */
30
+ export async function inForeground() {
31
+ if (process.platform === 'win32')
32
+ return true;
33
+ const proc = await spawnRunnerAsync('ps', { absolutePathOnly: true }).run(['-o', 'tpgid=', '-o', 'pgid=', '-p', String(process.pid)], { cwd: '/', timeoutMs: PS_TIMEOUT_MS });
34
+ return proc.exitCode === 0 && foregroundFromPs(proc.stdout);
35
+ }
36
+ /** The process's own job-control signals. None on Windows. */
37
+ export const processJobSignals = process.platform === 'win32'
38
+ ? null
39
+ : {
40
+ on: (signal, listener) => process.on(signal, listener),
41
+ off: (signal, listener) => process.off(signal, listener),
42
+ suspend: () => process.kill(process.pid, 'SIGSTOP'),
43
+ };
44
+ /**
45
+ * Call `onLine` for each Enter typed on `input`, while the process is in the
46
+ * foreground.
47
+ */
48
+ export function readTerminalLines(input, onLine, options = {}) {
49
+ const foreground = options.foreground ?? inForeground;
50
+ const signals = options.signals === undefined ? processJobSignals : options.signals;
51
+ const pollMs = options.pollMs ?? POLL_MS;
52
+ let reading = false;
53
+ let stopped = false;
54
+ let poll;
55
+ const onData = (chunk) => {
56
+ if (String(chunk).includes('\n'))
57
+ onLine();
58
+ };
59
+ const attach = () => {
60
+ if (reading || stopped)
61
+ return;
62
+ reading = true;
63
+ input.on('data', onData);
64
+ input.resume();
65
+ };
66
+ const detach = () => {
67
+ if (!reading)
68
+ return;
69
+ reading = false;
70
+ input.off('data', onData);
71
+ input.pause();
72
+ };
73
+ const check = async () => {
74
+ clearTimeout(poll);
75
+ const now = await foreground().catch(() => false);
76
+ if (stopped)
77
+ return false;
78
+ if (now)
79
+ attach();
80
+ else {
81
+ detach();
82
+ clearTimeout(poll);
83
+ poll = setTimeout(() => void check(), pollMs);
84
+ poll.unref?.();
85
+ }
86
+ return reading;
87
+ };
88
+ // Stop reading before the stop, so a later `bg` does not read the terminal.
89
+ const onStop = () => {
90
+ detach();
91
+ signals?.suspend();
92
+ };
93
+ const onContinue = () => {
94
+ void check();
95
+ };
96
+ signals?.on('SIGTSTP', onStop);
97
+ signals?.on('SIGCONT', onContinue);
98
+ return {
99
+ ready: check(),
100
+ stop() {
101
+ stopped = true;
102
+ clearTimeout(poll);
103
+ detach();
104
+ signals?.off('SIGTSTP', onStop);
105
+ signals?.off('SIGCONT', onContinue);
106
+ },
107
+ };
108
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Read the agent skills for the Skills group from `@osdlc/detect-harness`.
3
+ * It reads files only. No harness program runs, and no skill runs.
4
+ */
5
+ import type { SkillRow, SkillsSetting } from './core/skills.ts';
6
+ /** What {@link readSkills} needs. */
7
+ export interface ReadSkillsOptions {
8
+ /** Which skills: `project` reads the repository only; `all` adds the home folder's. */
9
+ setting: SkillsSetting;
10
+ home: string;
11
+ env: Record<string, string | undefined>;
12
+ signal?: AbortSignal | undefined;
13
+ }
14
+ /**
15
+ * The skills for `root`, project ones first, then by name. A skill file
16
+ * several agents read is one row that names each of them. `off` reads
17
+ * nothing.
18
+ */
19
+ export declare function readSkills(root: string, opts: ReadSkillsOptions): Promise<SkillRow[]>;