@yunuseon/kayra 0.16.1 → 0.17.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 (59) hide show
  1. package/README.md +4 -0
  2. package/cli/dist/browser/assets/index-9a-SE2rU.js +7 -0
  3. package/cli/dist/browser/assets/{index-3W_NFATj.css → index-Ct0Eudk4.css} +1 -1
  4. package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
  5. package/cli/dist/browser/index.html +2 -2
  6. package/cli/dist/clients/api/api.js +269 -0
  7. package/cli/dist/{web → clients/api}/auth.js +9 -9
  8. package/cli/dist/clients/api/commands.js +27 -0
  9. package/cli/dist/clients/api/contract.gen.js +1 -0
  10. package/cli/dist/clients/api/contract.js +89 -0
  11. package/cli/dist/clients/api/directories.js +20 -0
  12. package/cli/dist/clients/api/discovery.js +38 -0
  13. package/cli/dist/clients/api/protocol.js +61 -0
  14. package/cli/dist/clients/api/queries.js +20 -0
  15. package/cli/dist/{web → clients/api}/runs.js +4 -2
  16. package/cli/dist/{ui → clients/cli}/explain.js +5 -5
  17. package/cli/dist/clients/cli/framed.js +64 -0
  18. package/cli/dist/clients/cli/invocation.js +83 -0
  19. package/cli/dist/clients/cli/paint.js +23 -0
  20. package/cli/dist/{cli.js → clients/cli/parser.js} +31 -25
  21. package/cli/dist/clients/cli/questions.js +88 -0
  22. package/cli/dist/{ui → clients/cli}/terminal.js +1 -13
  23. package/cli/dist/clients/ui/assets.js +36 -0
  24. package/cli/dist/{brand.js → core/brand.js} +1 -1
  25. package/cli/dist/{commands → core/commands}/app-check.js +1 -1
  26. package/cli/dist/{commands → core/commands}/server.js +26 -17
  27. package/cli/dist/{commands → core/commands}/status.js +3 -3
  28. package/cli/dist/{commands → core/commands}/validate.js +1 -1
  29. package/cli/dist/{fleet.js → core/fleet.js} +1 -1
  30. package/cli/dist/core/interpret.js +276 -0
  31. package/cli/dist/{load.js → core/load.js} +1 -1
  32. package/cli/dist/core/operations/catalog.js +152 -0
  33. package/cli/dist/core/operations/run.js +139 -0
  34. package/cli/dist/{plan.js → core/plan.js} +11 -4
  35. package/cli/dist/core/present/line.js +17 -0
  36. package/cli/dist/{ui → core/present}/progress.js +2 -61
  37. package/cli/dist/{schemas.js → core/schemas.js} +1 -1
  38. package/cli/dist/core/updates.js +13 -0
  39. package/cli/dist/{validate.js → core/validate.js} +1 -1
  40. package/cli/dist/main.js +90 -91
  41. package/cli/dist/serve.js +77 -0
  42. package/package.json +3 -2
  43. package/scripts/agent/guard.sh +9 -2
  44. package/scripts/local/packed-runs.sh +20 -5
  45. package/scripts/local/setup-hosts.sh +9 -2
  46. package/cli/dist/browser/assets/index-DRFX9Q77.js +0 -2
  47. package/cli/dist/commands/index.js +0 -52
  48. package/cli/dist/interpret.js +0 -141
  49. package/cli/dist/ui/line.js +0 -39
  50. package/cli/dist/web/commands.js +0 -102
  51. package/cli/dist/web/contract.js +0 -7
  52. package/cli/dist/web/server.js +0 -336
  53. /package/cli/dist/{web → clients/ui}/opener.js +0 -0
  54. /package/cli/dist/{commands → core/commands}/doctor.js +0 -0
  55. /package/cli/dist/{gather.js → core/gather.js} +0 -0
  56. /package/cli/dist/{net.js → core/net.js} +0 -0
  57. /package/cli/dist/{ui → core/present}/text.js +0 -0
  58. /package/cli/dist/{ui → core/present}/views.js +0 -0
  59. /package/cli/dist/{settings.js → core/settings.js} +0 -0
@@ -1,336 +0,0 @@
1
- import { randomBytes } from "node:crypto";
2
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
3
- import { createServer } from "node:http";
4
- import { extname, join, normalize, sep } from "node:path";
5
- import { within } from "../brand.js";
6
- import { planFor } from "../commands/index.js";
7
- import { look, opentofu, statusJson } from "../commands/status.js";
8
- import { findings, validateJson } from "../commands/validate.js";
9
- import { json, send } from "../deployer/http.js";
10
- import { gather } from "../gather.js";
11
- import { capture, interpret } from "../interpret.js";
12
- import { needsTerminal } from "../plan.js";
13
- import { err, flatMap, ok } from "../result.js";
14
- import { listed, reporting } from "../ui/progress.js";
15
- import { follow } from "../ui/terminal.js";
16
- import { parsed, releasesSchema, runsSchema } from "../ui/views.js";
17
- import { admit, cookieName, tokenIn } from "./auth.js";
18
- import { changes, commandInput, facts, targetOf, toPlanned, words } from "./commands.js";
19
- import { busy, readRecord, recordLine, runId, stateOf, summary } from "./runs.js";
20
- /** kayra ui's one mutable cell: the runs it started, swapped whole on every change. */
21
- // eslint-disable-next-line functional/prefer-immutable-types -- kayra ui's state lives here, nowhere else
22
- const cell = { live: {} };
23
- const swap = (id, change) => {
24
- const current = cell.live[id];
25
- // eslint-disable-next-line functional/immutable-data -- kayra ui's state lives here, nowhere else
26
- if (current !== undefined)
27
- cell.live = { ...cell.live, [id]: change(current) };
28
- };
29
- const runsDir = (fleet) => within(fleet.root, ".cache", "ui", "runs");
30
- const recorded = (fleet) => {
31
- const dir = runsDir(fleet);
32
- if (!existsSync(dir))
33
- return [];
34
- return readdirSync(dir)
35
- .filter((name) => name.endsWith(".jsonl"))
36
- .flatMap((name) => {
37
- const run = readRecord(readFileSync(join(dir, name), "utf8"));
38
- return run === undefined ? [] : [run];
39
- });
40
- };
41
- /** Every run kayra ui knows: those it runs now, and those its records keep. */
42
- const allRuns = (fleet) => {
43
- const live = Object.values(cell.live).map((each) => each.run);
44
- return [...live, ...recorded(fleet).filter((run) => !live.some((each) => each.id === run.id))].toSorted((a, b) => b.id.localeCompare(a.id));
45
- };
46
- /** Ansible colours its output for a terminal only; the browser draws the colours too. */
47
- const coloured = (plan) => plan.map((step) => (step.kind === "run" ? { ...step, env: { ...step.env, ANSIBLE_FORCE_COLOR: "1" } } : step));
48
- /** A server-sent stream; `end` says everything is said, so the browser closes instead of reconnecting. */
49
- const sse = (response) => {
50
- response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
51
- return {
52
- say: (data) => {
53
- response.write(`data: ${JSON.stringify(data)}\n\n`);
54
- },
55
- end: () => {
56
- response.end("event: end\ndata: {}\n\n");
57
- },
58
- };
59
- };
60
- const answerJson = (response, status, value) => {
61
- send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
62
- };
63
- const invocationOf = (ui, input) => flatMap(targetOf(ui.fleet, input), (target) => ok({
64
- command: words(input),
65
- ...(target === undefined ? {} : { server: target.name }),
66
- about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${ui.version}`],
67
- }));
68
- const planOf = (ui, input) => flatMap(toPlanned(ui.fleet, input), (planned) => planFor({ kayra: ui.kayra, fleet: ui.fleet.root }, ui.fleet, planned));
69
- const preview = (ui, input) => flatMap(planOf(ui, input), (plan) => flatMap(invocationOf(ui, input), (invocation) => ok({ invocation, steps: listed(plan, ui.short), changes: changes(input) })));
70
- /** Starts a run, or says why it cannot: one per server, a terminal it needs, a real server not confirmed. */
71
- const start = (ui, input, confirm) => {
72
- const target = targetOf(ui.fleet, input);
73
- const plan = planOf(ui, input);
74
- const invocation = invocationOf(ui, input);
75
- if (!target.ok || !plan.ok || !invocation.ok)
76
- return err([400, [target, plan, invocation].flatMap((each) => (each.ok ? [] : [each.error])).join("; ")]);
77
- const server = target.value;
78
- if (needsTerminal(plan.value))
79
- return err([400, "its vault password is asked on a terminal: run it there, or give the server a vault_password_file"]);
80
- if (busy(allRuns(ui.fleet), server?.name))
81
- return err([409, `a run on ${server?.name ?? ""} has not ended`]);
82
- if (changes(input) && server !== undefined && server.target !== "multipass" && confirm !== server.name)
83
- return err([403, `this changes ${server.name}: confirm with its name`]);
84
- const started = new Date().toISOString();
85
- const id = runId(started, randomBytes(3).toString("hex"));
86
- const run = { id, command: words(input), ...(server === undefined ? {} : { server: server.name }), started, events: [] };
87
- const file = join(runsDir(ui.fleet), `${id}.jsonl`);
88
- mkdirSync(runsDir(ui.fleet), { recursive: true });
89
- appendFileSync(file, recordLine({ id: run.id, command: run.command, ...(server === undefined ? {} : { server: server.name }), started }));
90
- // eslint-disable-next-line functional/immutable-data -- kayra ui's state lives here, nowhere else
91
- cell.live = { ...cell.live, [id]: { run, listeners: [], stop: new AbortController(), answer: undefined } };
92
- const emit = (event) => {
93
- appendFileSync(file, recordLine(event));
94
- swap(id, (live) => ({ ...live, run: { ...live.run, events: [...live.run.events, event] } }));
95
- cell.live[id]?.listeners.forEach((listener) => {
96
- listener(event);
97
- });
98
- };
99
- const stop = cell.live[id]?.stop;
100
- const io = {
101
- out: (text) => {
102
- emit({ kind: "said", stream: "out", text });
103
- },
104
- err: (text) => {
105
- emit({ kind: "said", stream: "err", text });
106
- },
107
- ask: (prompt) => new Promise((resolve) => {
108
- swap(id, (live) => ({
109
- ...live,
110
- answer: (text) => {
111
- swap(id, (after) => ({ ...after, answer: undefined }));
112
- emit({ kind: "answered" });
113
- resolve(text);
114
- },
115
- }));
116
- emit({ kind: "ask", prompt });
117
- }),
118
- output: (chunk, stream) => {
119
- emit({ kind: "output", stream, chunk });
120
- },
121
- ...(stop === undefined ? {} : { signal: stop.signal }),
122
- };
123
- void interpret(coloured(plan.value), io, reporting(emit, invocation.value, ui.short), () => stop?.signal.aborted === true);
124
- return ok(id);
125
- };
126
- /** A run's events from the start, then each as it happens, until it has ended. */
127
- const watchRun = (ui, id, response) => {
128
- const live = cell.live[id];
129
- const run = live?.run ?? recorded(ui.fleet).find((each) => each.id === id);
130
- if (run === undefined) {
131
- send(response, 404, `no run ${id}\n`);
132
- return;
133
- }
134
- const { say, end } = sse(response);
135
- run.events.forEach(say);
136
- if (live === undefined || stateOf(run.events) !== "running") {
137
- end();
138
- return;
139
- }
140
- const listener = (event) => {
141
- say(event);
142
- if (event.kind === "ended")
143
- end();
144
- };
145
- swap(id, (current) => ({ ...current, listeners: [...current.listeners, listener] }));
146
- response.on("close", () => {
147
- swap(id, (current) => ({ ...current, listeners: current.listeners.filter((each) => each !== listener) }));
148
- });
149
- };
150
- /** What a deployer's ctl answers, captured over SSH as `kayra app …` asks it. */
151
- const ctl = async (ui, input) => {
152
- const server = ui.fleet.servers.find((each) => each.name === input.server);
153
- if (server === undefined)
154
- return err(`no server '${input.server}'`);
155
- const app = server.apps.find((each) => each.name === input.app);
156
- if (app === undefined)
157
- return err(`'${input.app}' is not an app of ${server.name}`);
158
- const plan = planFor({ kayra: ui.kayra, fleet: ui.fleet.root }, ui.fleet, { name: input.name, server: server.name, app: app.name, more: input.more });
159
- if (!plan.ok)
160
- return plan;
161
- const [step] = plan.value;
162
- if (step?.kind !== "run")
163
- return err("the deployer's plan has no step");
164
- const [program, ...args] = step.argv;
165
- const argv = args.flatMap((arg) => (typeof arg === "string" ? [arg] : []));
166
- const exit = await capture([program, ...argv], "capture");
167
- return exit.code === 0 ? ok(exit.stdout) : err(exit.stderr.trim() === "" ? `exit ${String(exit.code)}` : exit.stderr.trim());
168
- };
169
- const types = {
170
- ".html": "text/html; charset=utf-8",
171
- ".js": "text/javascript; charset=utf-8",
172
- ".css": "text/css; charset=utf-8",
173
- ".svg": "image/svg+xml",
174
- ".png": "image/png",
175
- ".ico": "image/x-icon",
176
- ".woff2": "font/woff2",
177
- ".json": "application/json; charset=utf-8",
178
- };
179
- const unbuilt = `<!doctype html><meta charset="utf-8"><title>kayra ui</title>
180
- <body style="font:15px system-ui;margin:3rem auto;max-width:40rem"><h1>kayra ui</h1>
181
- <p>The browser side is not built in this checkout:</p><pre>npm --prefix web ci &amp;&amp; npm --prefix web run build</pre>
182
- <p>The API is up at <code>/api/fleet</code>.</p></body>`;
183
- /** The built browser side; a path that is no file is the app's own route, answered by its index. */
184
- const asset = (ui, path, response) => {
185
- if (ui.assets === undefined) {
186
- send(response, 200, unbuilt, "text/html; charset=utf-8");
187
- return;
188
- }
189
- const file = normalize(join(ui.assets, decodeURIComponent(path)));
190
- const inside = file.startsWith(ui.assets + sep) && existsSync(file) && statSync(file).isFile();
191
- const chosen = inside ? file : join(ui.assets, "index.html");
192
- response.writeHead(200, {
193
- "Content-Type": types[extname(chosen)] ?? "application/octet-stream",
194
- "Cache-Control": chosen.includes(`${sep}assets${sep}`) ? "public, max-age=31536000, immutable" : "no-cache",
195
- });
196
- response.end(readFileSync(chosen));
197
- };
198
- const route = async (ui, port, token, request, response) => {
199
- const url = new URL(request.url ?? "/", `http://127.0.0.1:${String(port)}`);
200
- const path = url.pathname;
201
- const method = request.method ?? "GET";
202
- const admission = admit({ method, path, host: request.headers.host, origin: request.headers.origin, cookie: request.headers.cookie }, port, token);
203
- if (!admission.admitted) {
204
- send(response, admission.status, `${admission.why}\n`);
205
- return;
206
- }
207
- if (path === "/login") {
208
- if (!tokenIn(url.searchParams, token)) {
209
- send(response, 401, "not this launch's token: open the URL kayra ui printed\n");
210
- return;
211
- }
212
- response.writeHead(303, { "Set-Cookie": `${cookieName(port)}=${token}; HttpOnly; SameSite=Strict; Path=/`, Location: "/" });
213
- response.end();
214
- return;
215
- }
216
- if (!path.startsWith("/api/")) {
217
- asset(ui, path, response);
218
- return;
219
- }
220
- const app = /^\/api\/servers\/([^/]+)\/apps\/([^/]+)\/(runs|releases|logs)(?:\/([^/]+))?$/.exec(path);
221
- const runPath = /^\/api\/runs\/([^/]+)\/(events|answer|cancel)$/.exec(path);
222
- if (method === "GET" && path === "/api/fleet") {
223
- const fleetFacts = { fleet: ui.fleet.root.split(sep).at(-1) ?? "", version: ui.version, servers: ui.fleet.servers.map(facts) };
224
- answerJson(response, 200, fleetFacts);
225
- }
226
- else if (method === "GET" && path === "/api/status") {
227
- const { say, end } = sse(response);
228
- const { initial, updates } = look(ui.fleet, opentofu, ui.network);
229
- await follow(initial, updates, (looks) => {
230
- const status = statusJson(looks);
231
- say(status);
232
- });
233
- end();
234
- }
235
- else if (method === "GET" && path === "/api/validate") {
236
- const reports = await Promise.all(ui.fleet.servers.map(async (server) => ({ server, findings: findings(await gather(ui.fleet.root, server)) })));
237
- const validation = validateJson(reports);
238
- answerJson(response, 200, validation);
239
- }
240
- else if (method === "GET" && app !== null) {
241
- const [, server = "", name = "", what, more] = app;
242
- const asked = { server: decodeURIComponent(server), app: decodeURIComponent(name) };
243
- const answer = await ctl(ui, {
244
- ...asked,
245
- name: what === "runs" ? "app runs" : what === "releases" ? "app rollback" : "app logs",
246
- ...(more === undefined ? {} : { more: decodeURIComponent(more) }),
247
- });
248
- if (!answer.ok)
249
- send(response, 502, `${answer.error}\n`);
250
- else if (what === "logs")
251
- send(response, 200, answer.value);
252
- else {
253
- const value = what === "runs" ? parsed(runsSchema, answer.value) : parsed(releasesSchema, answer.value);
254
- if (value === undefined)
255
- send(response, 502, "the server's deployer answered in a form this kayra does not read: deploy it with this kayra\n");
256
- else
257
- answerJson(response, 200, value);
258
- }
259
- }
260
- else if (method === "POST" && path === "/api/plan") {
261
- const input = commandInput.safeParse(await json(request));
262
- const shown = input.success ? preview(ui, input.data) : err(input.error.issues.at(0)?.message ?? "not a command");
263
- if (shown.ok)
264
- answerJson(response, 200, shown.value);
265
- else
266
- send(response, 400, `${shown.error}\n`);
267
- }
268
- else if (method === "GET" && path === "/api/runs") {
269
- const runs = allRuns(ui.fleet).slice(0, 50).map(summary);
270
- answerJson(response, 200, runs);
271
- }
272
- else if (method === "POST" && path === "/api/runs") {
273
- const body = await json(request);
274
- const input = commandInput.safeParse(typeof body === "object" && body !== null && "command" in body ? body.command : undefined);
275
- const confirm = typeof body === "object" && body !== null && "confirm" in body ? body.confirm : undefined;
276
- const started = input.success ? start(ui, input.data, confirm) : err([400, input.error.issues.at(0)?.message ?? "not a command"]);
277
- if (started.ok)
278
- answerJson(response, 201, { id: started.value });
279
- else
280
- send(response, started.error[0], `${started.error[1]}\n`);
281
- }
282
- else if (runPath !== null) {
283
- const [, id = "", what] = runPath;
284
- const live = cell.live[id];
285
- if (method === "GET" && what === "events")
286
- watchRun(ui, id, response);
287
- else if (method === "POST" && what === "cancel" && live !== undefined) {
288
- live.stop.abort();
289
- send(response, 202, "stopping\n");
290
- }
291
- else if (method === "POST" && what === "answer" && live?.answer !== undefined) {
292
- const body = await json(request);
293
- live.answer(typeof body === "object" && body !== null && "text" in body && typeof body.text === "string" ? body.text : "");
294
- send(response, 204, "");
295
- }
296
- else
297
- send(response, 404, `nothing to ${what ?? ""} for run ${id}\n`);
298
- }
299
- else
300
- send(response, 404, "not found\n");
301
- };
302
- /** kayra ui: listens on 127.0.0.1 only; the URL it returns carries this launch's token. */
303
- export const serveUi = (ui, port) => {
304
- const token = randomBytes(32).toString("base64url");
305
- return new Promise((resolve, reject) => {
306
- const server = createServer((request, response) => {
307
- route(ui, listening(), token, request, response).catch((error) => {
308
- if (!response.headersSent)
309
- send(response, 500, `${error instanceof Error ? error.message : String(error)}\n`);
310
- else
311
- response.end();
312
- });
313
- });
314
- const listening = () => {
315
- const address = server.address();
316
- return typeof address === "object" && address !== null ? address.port : port;
317
- };
318
- server.once("error", reject);
319
- server.listen(port, "127.0.0.1", () => {
320
- const actual = listening();
321
- resolve({
322
- url: `http://127.0.0.1:${String(actual)}/login?token=${token}`,
323
- port: actual,
324
- close: () => new Promise((done) => {
325
- Object.values(cell.live).forEach((live) => {
326
- live.stop.abort();
327
- });
328
- server.closeAllConnections();
329
- server.close(() => {
330
- done();
331
- });
332
- }),
333
- });
334
- });
335
- });
336
- };
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes