@yunuseon/kayra 0.17.0 → 0.17.2

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 (113) hide show
  1. package/agent/skills/kayra-release/SKILL.md +6 -1
  2. package/ansible/roles/platform/tasks/main.yml +40 -1
  3. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  4. package/cli/dist/browser/index.html +1 -1
  5. package/cli/dist/clients/api/api.js +138 -218
  6. package/cli/dist/clients/api/auth.js +8 -7
  7. package/cli/dist/clients/api/commands.js +50 -14
  8. package/cli/dist/clients/api/contract.js +8 -6
  9. package/cli/dist/clients/api/directories.js +1 -1
  10. package/cli/dist/clients/api/discovery.js +8 -3
  11. package/cli/dist/clients/api/live.js +40 -0
  12. package/cli/dist/clients/api/protocol.js +17 -10
  13. package/cli/dist/clients/api/queries.js +4 -4
  14. package/cli/dist/clients/api/runs.js +10 -9
  15. package/cli/dist/clients/api/start.js +97 -0
  16. package/cli/dist/clients/api/status.js +29 -0
  17. package/cli/dist/clients/api/validate.js +13 -0
  18. package/cli/dist/clients/cli/explain.js +12 -10
  19. package/cli/dist/clients/cli/framed.js +12 -9
  20. package/cli/dist/clients/cli/invocation.js +4 -3
  21. package/cli/dist/clients/cli/paint.js +1 -1
  22. package/cli/dist/clients/cli/parser.js +8 -8
  23. package/cli/dist/clients/cli/questions.js +11 -10
  24. package/cli/dist/clients/cli/status.js +75 -0
  25. package/cli/dist/clients/cli/terminal.js +4 -2
  26. package/cli/dist/{core/present → clients/cli}/text.js +15 -24
  27. package/cli/dist/clients/cli/validate.js +32 -0
  28. package/cli/dist/clients/cli/values.js +19 -0
  29. package/cli/dist/{core/present → clients/cli}/views.js +28 -60
  30. package/cli/dist/core/adapters/fs.js +18 -0
  31. package/cli/dist/core/{net.js → adapters/network.js} +20 -5
  32. package/cli/dist/core/adapters/opentofu.js +24 -0
  33. package/cli/dist/core/ctl/answers.js +32 -0
  34. package/cli/dist/core/fleet/brand.js +54 -0
  35. package/cli/dist/core/{schemas.js → fleet/docs.js} +5 -4
  36. package/cli/dist/core/fleet/load.js +45 -0
  37. package/cli/dist/core/fleet/model.js +1 -0
  38. package/cli/dist/core/fleet/parse.js +144 -0
  39. package/cli/dist/core/{settings.js → fleet/settings.js} +47 -15
  40. package/cli/dist/core/{validate.js → fleet/shape.js} +6 -20
  41. package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
  42. package/cli/dist/core/interpreter/io.js +18 -0
  43. package/cli/dist/core/interpreter/loop.js +101 -0
  44. package/cli/dist/core/interpreter/needs.js +47 -0
  45. package/cli/dist/core/interpreter/process.js +107 -0
  46. package/cli/dist/core/interpreter/progress.js +15 -0
  47. package/cli/dist/core/interpreter/pty.js +8 -0
  48. package/cli/dist/core/operations/catalog.js +35 -18
  49. package/cli/dist/core/operations/{run.js → dispatch.js} +50 -47
  50. package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
  51. package/cli/dist/core/plan/model.js +14 -0
  52. package/cli/dist/core/recipes/app-check.js +27 -0
  53. package/cli/dist/core/recipes/apps.js +63 -0
  54. package/cli/dist/core/recipes/backup.js +34 -0
  55. package/cli/dist/core/recipes/certs.js +4 -0
  56. package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
  57. package/cli/dist/core/recipes/host.js +104 -0
  58. package/cli/dist/core/recipes/ssh.js +20 -0
  59. package/cli/dist/core/recipes/steps.js +82 -0
  60. package/cli/dist/core/status/look.js +55 -0
  61. package/cli/dist/core/status/model.js +6 -0
  62. package/cli/dist/core/status/ports.js +1 -0
  63. package/cli/dist/core/text/plural.js +2 -0
  64. package/cli/dist/core/text/spans.js +22 -0
  65. package/cli/dist/core/text/time.js +12 -0
  66. package/cli/dist/core/validation/facts.js +50 -0
  67. package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
  68. package/cli/dist/deployer/app.js +3 -2
  69. package/cli/dist/deployer/brand.js +1 -1
  70. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  71. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  72. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  73. package/cli/dist/deployer/cron.js +3 -3
  74. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  75. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  76. package/cli/dist/deployer/deployer.js +24 -23
  77. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  78. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  79. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  80. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  81. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  82. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  83. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  84. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  85. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  86. package/cli/dist/deployer/main.js +2 -2
  87. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  88. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  89. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  90. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  91. package/cli/dist/lib/brand.js +2 -0
  92. package/cli/dist/lib/closest.js +17 -0
  93. package/cli/dist/lib/result.js +15 -0
  94. package/cli/dist/lib/schema.js +7 -0
  95. package/cli/dist/lib/typed.js +2 -0
  96. package/cli/dist/lib/yaml.js +21 -0
  97. package/cli/dist/main.js +89 -89
  98. package/cli/dist/serve.js +2 -2
  99. package/package.json +3 -2
  100. package/schema/app.json +4 -2
  101. package/schema/server.json +10 -5
  102. package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
  103. package/cli/dist/core/brand.js +0 -39
  104. package/cli/dist/core/commands/app-check.js +0 -35
  105. package/cli/dist/core/commands/server.js +0 -298
  106. package/cli/dist/core/commands/status.js +0 -194
  107. package/cli/dist/core/fleet.js +0 -156
  108. package/cli/dist/core/gather.js +0 -61
  109. package/cli/dist/core/interpret.js +0 -276
  110. package/cli/dist/core/load.js +0 -64
  111. package/cli/dist/core/present/line.js +0 -17
  112. package/cli/dist/result.js +0 -5
  113. /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
@@ -1,23 +1,20 @@
1
- import { randomBytes } from "node:crypto";
2
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
3
- import { join, sep } from "node:path";
1
+ import { sep } from "node:path";
4
2
  import { z } from "zod";
5
- import { within } from "../../core/brand.js";
6
- import { verbose } from "../../core/commands/server.js";
7
- import { opentofu, statusJson } from "../../core/commands/status.js";
8
- import { interpret } from "../../core/interpret.js";
9
- import { operation, isOperation } from "../../core/operations/catalog.js";
10
- import { invocation, hasPlan, isQuery, isStream, planOf, serverOf, stream } from "../../core/operations/run.js";
11
- import { listed, reporting } from "../../core/present/progress.js";
12
- import { follow } from "../../core/updates.js";
13
- import { err, ok } from "../../result.js";
14
- import { json, send } from "../../deployer/http.js";
3
+ import { within } from "../../core/fleet/brand.js";
4
+ import { opentofu } from "../../core/adapters/opentofu.js";
5
+ import { isOperation, operation } from "../../core/operations/catalog.js";
6
+ import { contextFor, invocation, isQuery, isStream, stream } from "../../core/operations/dispatch.js";
7
+ import { follow } from "../../core/status/updates.js";
8
+ import { json, send } from "../../deployer/http/http.js";
9
+ import { facts } from "./commands.js";
15
10
  import { catalog, openapi } from "./contract.js";
16
11
  import { directories } from "./directories.js";
17
- import { facts, words } from "./commands.js";
18
- import { answer as queryAnswer } from "./queries.js";
12
+ import { inFlight, liveRuns } from "./live.js";
19
13
  import { options, requestBody } from "./protocol.js";
20
- import { busy, readRecord, recordLine, runId, stateOf, summary } from "./runs.js";
14
+ import { answer as queryAnswer } from "./queries.js";
15
+ import { stateOf, summary } from "./runs.js";
16
+ import { allRuns, preview, start } from "./start.js";
17
+ import { statusJson } from "./status.js";
21
18
  const answerJson = (response, status, value) => {
22
19
  send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
23
20
  };
@@ -29,115 +26,124 @@ const events = (response, ndjson = false) => {
29
26
  end: () => { response.end(ndjson ? "" : "event: end\ndata: {}\n\n"); },
30
27
  };
31
28
  };
32
- export const createApi = (api) => {
33
- // eslint-disable-next-line functional/prefer-immutable-types -- per-listener state; no launch shares locks, credentials or sessions
34
- const cell = { live: {}, pending: [] };
35
- const shutdown = new AbortController();
36
- const swap = (id, change) => {
37
- const current = cell.live[id];
38
- // eslint-disable-next-line functional/immutable-data -- replace the one state cell whole
39
- if (current !== undefined)
40
- cell.live = { ...cell.live, [id]: change(current) };
41
- };
42
- const context = {
43
- engine: { kayra: api.kayra, fleet: api.fleet.root }, fleet: api.fleet, version: api.version, here: api.fleet.root,
44
- read: (path) => existsSync(path) ? readFileSync(path, "utf8") : undefined,
45
- network: api.network, tofu: api.tofu ?? opentofu, signal: shutdown.signal,
46
- };
47
- const dir = within(api.fleet.root, ".cache", "ui", "runs");
48
- const allRuns = () => {
49
- const live = Object.values(cell.live).map((each) => each.run);
50
- const records = existsSync(dir) ? readdirSync(dir).filter((name) => name.endsWith(".jsonl")).flatMap((name) => {
51
- const run = readRecord(readFileSync(join(dir, name), "utf8"));
52
- return run === undefined || live.some((each) => each.id === run.id) ? [] : [run];
53
- }) : [];
54
- return [...live, ...records].toSorted((a, b) => b.id.localeCompare(a.id));
55
- };
56
- const about = (call) => {
57
- const target = serverOf(context, call);
58
- return { command: words(call), about: [...(target === undefined ? [] : [`${target.kind} on ${target.target}`, target.domain]), `kayra ${api.version}`], ...(target === undefined ? {} : { server: target.name }) };
59
- };
60
- const recipe = (call, settings) => {
61
- if (!hasPlan(call))
62
- return err(`${call.name} has no plan`);
63
- const plan = planOf(context, call);
64
- return plan.ok && settings.verbose ? ok(verbose(plan.value)) : plan;
65
- };
66
- const preview = (call, settings) => {
67
- const plan = recipe(call, settings);
68
- return plan.ok ? ok({ invocation: about(call), steps: listed(plan.value, api.short), changes: operation(call.name).effect !== "reads" }) : plan;
69
- };
70
- const start = (call, settings, confirm) => {
71
- if (shutdown.signal.aborted)
72
- return err([503, "kayra is stopping"]);
73
- const plan = recipe(call, settings);
74
- if (!plan.ok)
75
- return err([400, plan.error]);
76
- const server = serverOf(context, call);
77
- if (busy(Object.values(cell.live).map((live) => live.run), server?.name))
78
- return err([409, `a run on ${server?.name ?? ""} has not ended`]);
79
- if (operation(call.name).effect !== "reads" && server !== undefined && server.target !== "multipass" && confirm !== server.name)
80
- return err([403, `this changes ${server.name}: confirm with its name`]);
81
- const started = new Date().toISOString();
82
- const id = runId(started, randomBytes(6).toString("hex"));
83
- const session = operation(call.name).kind === "session";
84
- const run = { id, command: words(call), started, events: [], session, ...(server === undefined ? {} : { server: server.name }) };
85
- mkdirSync(dir, { recursive: true });
86
- const file = join(dir, `${id}.jsonl`);
87
- appendFileSync(file, recordLine({ id, command: run.command, started, session, ...(server === undefined ? {} : { server: server.name }) }));
88
- const stop = new AbortController();
89
- // eslint-disable-next-line functional/immutable-data -- install the lock before any asynchronous work
90
- cell.live = { ...cell.live, [id]: { run, stop, listeners: [], answer: undefined, input: undefined, done: Promise.resolve() } };
91
- const emit = (event) => {
92
- appendFileSync(file, recordLine(event));
93
- swap(id, (live) => ({ ...live, run: { ...live.run, events: [...live.run.events, event] } }));
94
- cell.live[id]?.listeners.forEach((listener) => { listener(event); });
95
- };
96
- const io = {
97
- out: (text) => { emit({ kind: "said", stream: "out", text }); },
98
- err: (text) => { emit({ kind: "said", stream: "err", text }); },
99
- ask: (question) => new Promise((resolve) => {
100
- swap(id, (live) => ({ ...live, answer: (text) => {
101
- swap(id, (after) => ({ ...after, answer: undefined }));
102
- emit({ kind: "answered" });
103
- resolve(text);
104
- } }));
105
- emit({ kind: "ask", prompt: question.text, secret: question.kind === "secret", ...(question.kind === "confirm" ? { expect: question.expect } : {}) });
106
- }),
107
- output: (chunk, stream) => { emit({ kind: "output", stream, chunk }); },
108
- input: (deliver) => {
109
- swap(id, (live) => ({ ...live, input: deliver }));
110
- return () => { swap(id, (live) => ({ ...live, input: undefined })); };
111
- },
112
- size: { columns: settings.columns, rows: settings.rows }, signal: stop.signal,
113
- };
114
- const coloured = plan.value.map((step) => step.kind === "run" ? { ...step, env: { ...step.env, ANSIBLE_FORCE_COLOR: "1" } } : step);
115
- const done = interpret(coloured, io, reporting(emit, about(call), api.short)).catch(() => {
116
- emit({ kind: "said", stream: "err", text: "The run could not finish; check the local kayra process." });
117
- emit({ kind: "ended", failures: 1, ms: Date.now() - Date.parse(started), footer: [] });
118
- }).finally(() => { swap(id, (live) => ({ ...live, answer: undefined, input: undefined })); });
119
- swap(id, (live) => ({ ...live, done }));
120
- return ok(id);
121
- };
122
- const watch = (id, response, ndjson, session = false) => {
123
- const live = cell.live[id];
124
- const run = live?.run ?? allRuns().find((each) => each.id === id);
125
- if (run === undefined || (session && !run.session)) {
126
- send(response, 404, "no run or session\n");
127
- return;
29
+ /** A run's events as they come, after those it has had: until it ends, or the client goes. */
30
+ const watch = (served, id, response, ndjson, session = false) => {
31
+ const live = served.runs.get(id);
32
+ const run = live?.run ?? allRuns(served).find((each) => each.id === id);
33
+ if (run === undefined || (session && !run.session)) {
34
+ send(response, 404, "no run or session\n");
35
+ return;
36
+ }
37
+ const { say, end } = events(response, ndjson);
38
+ run.events.forEach(say);
39
+ if (live === undefined || stateOf(run.events) !== "running") {
40
+ end();
41
+ return;
42
+ }
43
+ const listener = (event) => { say(event); if (event.kind === "ended")
44
+ end(); };
45
+ served.runs.swap(id, (current) => ({ ...current, listeners: [...current.listeners, listener] }));
46
+ response.on("close", () => { served.runs.swap(id, (current) => ({ ...current, listeners: current.listeners.filter((each) => each !== listener) })); });
47
+ };
48
+ /** POST /api/operations/<name>[/preview]: a plan previewed or started, a session started, a query answered, a stream followed. */
49
+ const operate = async (served, request, response, named, previewing, ndjson) => {
50
+ const name = decodeURIComponent(named);
51
+ if (!isOperation(name)) {
52
+ send(response, 404, "no such operation\n");
53
+ return;
54
+ }
55
+ const body = requestBody.safeParse(await json(request));
56
+ if (!body.success) {
57
+ send(response, 400, "expected {input, options?, confirm?}\n");
58
+ return;
59
+ }
60
+ const call = invocation(name, body.data.input);
61
+ const settings = options.parse(body.data.options ?? {});
62
+ if (!call.ok) {
63
+ send(response, 400, `${call.error}\n`);
64
+ return;
65
+ }
66
+ const kind = operation(call.value.name).kind;
67
+ if (previewing || settings.dryRun) {
68
+ const shown = preview(served, call.value, settings);
69
+ if (shown.ok)
70
+ answerJson(response, 200, shown.value);
71
+ else
72
+ send(response, 400, `${shown.error}\n`);
73
+ }
74
+ else if (kind === "plan" || kind === "session") {
75
+ const started = start(served, call.value, settings, body.data.confirm);
76
+ if (!started.ok)
77
+ send(response, started.error[0], `${started.error[1]}\n`);
78
+ else
79
+ answerJson(response, kind === "session" ? 201 : 202, { [kind === "session" ? "session" : "run"]: started.value });
80
+ }
81
+ else if (isStream(call.value)) {
82
+ const { initial, updates } = stream(served.context, call.value.name, call.value.input);
83
+ const sink = events(response, ndjson);
84
+ await follow(initial, updates, (looks) => { const value = statusJson(looks); sink.say(value); });
85
+ sink.end();
86
+ }
87
+ else if (isQuery(call.value)) {
88
+ const result = await queryAnswer(served.context, call.value.name, call.value.input);
89
+ if (result.ok)
90
+ answerJson(response, 200, result.value);
91
+ else
92
+ send(response, call.value.name === "validate" ? 400 : 502, `${result.error}\n`);
93
+ }
94
+ };
95
+ /** /api/runs/<id>[/events|answers|cancel] and /api/sessions/<id>[/output|input]: follow, answer, stop. */
96
+ const steer = async (served, request, response, id, action, session, ndjson) => {
97
+ const method = request.method ?? "GET";
98
+ const live = served.runs.get(id);
99
+ if (session && live?.run.session !== true && !allRuns(served).some((each) => each.id === id && each.session)) {
100
+ send(response, 404, "no session\n");
101
+ return;
102
+ }
103
+ if (method === "GET" && (action === "events" || action === "output"))
104
+ watch(served, id, response, ndjson, session);
105
+ else if (method === "GET" && action === undefined && !session) {
106
+ const run = allRuns(served).find((each) => each.id === id);
107
+ if (run === undefined)
108
+ send(response, 404, "no run\n");
109
+ else {
110
+ const value = { ...summary(run), events: run.events };
111
+ answerJson(response, 200, value);
128
112
  }
129
- const { say, end } = events(response, ndjson);
130
- run.events.forEach(say);
131
- if (live === undefined || stateOf(run.events) !== "running") {
132
- end();
113
+ }
114
+ else if (((method === "POST" && action === "cancel") || (session && method === "DELETE" && action === undefined)) && live !== undefined && stateOf(live.run.events) === "running") {
115
+ live.stop.abort();
116
+ send(response, 204, "");
117
+ }
118
+ else if (method === "POST" && (action === "answers" || action === "input")) {
119
+ const deliver = action === "answers" ? live?.answer : session ? live?.input : undefined;
120
+ if (deliver === undefined || live?.stop.signal.aborted === true) {
121
+ send(response, 404, "nothing waiting for input\n");
133
122
  return;
134
123
  }
135
- const listener = (event) => { say(event); if (event.kind === "ended")
136
- end(); };
137
- swap(id, (current) => ({ ...current, listeners: [...current.listeners, listener] }));
138
- response.on("close", () => { swap(id, (current) => ({ ...current, listeners: current.listeners.filter((each) => each !== listener) })); });
124
+ const body = z.strictObject({ text: z.string() }).safeParse(await json(request));
125
+ if (!body.success)
126
+ send(response, 400, "expected {text: string}\n");
127
+ else {
128
+ deliver(body.data.text);
129
+ send(response, 204, "");
130
+ }
131
+ }
132
+ else
133
+ send(response, 404, "no active resource\n");
134
+ };
135
+ /** The API of one listener: its requests routed, and a stop that waits for runs and requests to end. */
136
+ export const createApi = (api) => {
137
+ const shutdown = new AbortController();
138
+ const served = {
139
+ api,
140
+ context: contextFor({ kayra: api.kayra, fleet: api.fleet, version: api.version, here: api.fleet.root, network: api.network, tofu: api.tofu ?? opentofu, signal: shutdown.signal }),
141
+ runs: liveRuns(),
142
+ dir: within(api.fleet.root, ".cache", "ui", "runs"),
143
+ shutdown,
139
144
  };
140
- const dispatch = async (request, response, url) => {
145
+ const requests = inFlight();
146
+ const route = async (request, response, url) => {
141
147
  const method = request.method ?? "GET";
142
148
  const path = url.pathname;
143
149
  const named = /^\/api\/operations\/([^/]+)(\/preview)?$/.exec(path);
@@ -159,111 +165,25 @@ export const createApi = (api) => {
159
165
  const factsOfFleet = { fleet: api.fleet.root.split(sep).at(-1) ?? "", version: api.version, servers: api.fleet.servers.map(facts) };
160
166
  answerJson(response, 200, factsOfFleet);
161
167
  }
162
- else if (method === "POST" && named !== null) {
163
- const name = decodeURIComponent(named[1] ?? "");
164
- if (!isOperation(name)) {
165
- send(response, 404, "no such operation\n");
166
- return;
167
- }
168
- const body = requestBody.safeParse(await json(request));
169
- if (!body.success) {
170
- send(response, 400, "expected {input, options?, confirm?}\n");
171
- return;
172
- }
173
- const call = invocation(name, body.data.input);
174
- const settings = options.parse(body.data.options ?? {});
175
- if (!call.ok) {
176
- send(response, 400, `${call.error}\n`);
177
- return;
178
- }
179
- const kind = operation(call.value.name).kind;
180
- if (named[2] !== undefined || settings.dryRun) {
181
- const shown = preview(call.value, settings);
182
- if (shown.ok)
183
- answerJson(response, 200, shown.value);
184
- else
185
- send(response, 400, `${shown.error}\n`);
186
- }
187
- else if (kind === "plan" || kind === "session") {
188
- const started = start(call.value, settings, body.data.confirm);
189
- if (!started.ok)
190
- send(response, started.error[0], `${started.error[1]}\n`);
191
- else
192
- answerJson(response, kind === "session" ? 201 : 202, { [kind === "session" ? "session" : "run"]: started.value });
193
- }
194
- else if (isStream(call.value)) {
195
- const { initial, updates } = stream(context, call.value.name, call.value.input);
196
- const sink = events(response, ndjson);
197
- await follow(initial, updates, (looks) => { const value = statusJson(looks); sink.say(value); });
198
- sink.end();
199
- }
200
- else if (isQuery(call.value)) {
201
- const result = await queryAnswer(context, call.value.name, call.value.input);
202
- if (result.ok)
203
- answerJson(response, 200, result.value);
204
- else
205
- send(response, call.value.name === "validate" ? 400 : 502, `${result.error}\n`);
206
- }
207
- }
168
+ else if (method === "POST" && named !== null)
169
+ await operate(served, request, response, named[1] ?? "", named[2] !== undefined, ndjson);
208
170
  else if (method === "GET" && path === "/api/runs") {
209
- const runs = allRuns().map(summary);
171
+ const runs = allRuns(served).map(summary);
210
172
  answerJson(response, 200, runs);
211
173
  }
212
174
  else if (runPath !== null || sessionPath !== null) {
213
175
  const [, id = "", action] = runPath ?? sessionPath ?? [];
214
- const live = cell.live[id];
215
- const session = sessionPath !== null;
216
- if (session && live?.run.session !== true && !allRuns().some((each) => each.id === id && each.session)) {
217
- send(response, 404, "no session\n");
218
- return;
219
- }
220
- if (method === "GET" && (action === "events" || action === "output"))
221
- watch(id, response, ndjson, session);
222
- else if (method === "GET" && action === undefined && !session) {
223
- const run = allRuns().find((each) => each.id === id);
224
- if (run === undefined)
225
- send(response, 404, "no run\n");
226
- else {
227
- const value = { ...summary(run), events: run.events };
228
- answerJson(response, 200, value);
229
- }
230
- }
231
- else if (((method === "POST" && action === "cancel") || (session && method === "DELETE" && action === undefined)) && live !== undefined && stateOf(live.run.events) === "running") {
232
- live.stop.abort();
233
- send(response, 204, "");
234
- }
235
- else if (method === "POST" && (action === "answers" || action === "input")) {
236
- const deliver = action === "answers" ? live?.answer : session ? live?.input : undefined;
237
- if (deliver === undefined || live?.stop.signal.aborted === true) {
238
- send(response, 404, "nothing waiting for input\n");
239
- return;
240
- }
241
- const body = z.strictObject({ text: z.string() }).safeParse(await json(request));
242
- if (!body.success)
243
- send(response, 400, "expected {text: string}\n");
244
- else {
245
- deliver(body.data.text);
246
- send(response, 204, "");
247
- }
248
- }
249
- else
250
- send(response, 404, "no active resource\n");
176
+ await steer(served, request, response, id, action, sessionPath !== null, ndjson);
251
177
  }
252
178
  else
253
179
  send(response, 404, "not found\n");
254
180
  };
255
- const handle = (request, response, url) => {
256
- const work = dispatch(request, response, url).finally(() => {
257
- // eslint-disable-next-line functional/immutable-data -- release this request after its response completes
258
- cell.pending = cell.pending.filter((pending) => pending !== work);
259
- });
260
- // eslint-disable-next-line functional/immutable-data -- shutdown waits for in-flight requests as well as runs
261
- cell.pending = [...cell.pending, work];
262
- return work;
263
- };
264
- return { handle, stop: async () => {
181
+ return {
182
+ handle: (request, response, url) => requests.track(route(request, response, url)),
183
+ stop: async () => {
265
184
  shutdown.abort();
266
- Object.values(cell.live).forEach((live) => { live.stop.abort(); });
267
- await Promise.allSettled([...cell.pending, ...Object.values(cell.live).map((live) => live.done)]);
268
- } };
185
+ served.runs.all().forEach((live) => { live.stop.abort(); });
186
+ await Promise.allSettled([requests.settled(), ...served.runs.all().map((live) => live.done)]);
187
+ },
188
+ };
269
189
  };
@@ -1,7 +1,8 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
+ import { typed } from "../../lib/typed.js";
2
3
  /** Cookies are shared by every port of a host: the name carries the port, so another local server's cookie is not ours. */
3
4
  export const cookieName = (port) => `kayra_ui_${String(port)}`;
4
- const origins = (port) => [`127.0.0.1:${String(port)}`, `localhost:${String(port)}`];
5
+ const origins = (port) => typed([`127.0.0.1:${String(port)}`, `localhost:${String(port)}`]);
5
6
  const same = (a, b) => {
6
7
  const left = Buffer.from(a);
7
8
  const right = Buffer.from(b);
@@ -9,25 +10,25 @@ const same = (a, b) => {
9
10
  };
10
11
  const cookieValue = (header, name) => header
11
12
  ?.split(";")
12
- .map((pair) => pair.trim().split("="))
13
+ .map((pair) => Object.freeze(pair.trim().split("=")))
13
14
  .find(([key]) => key === name)?.[1];
14
- const refuse = (status, why) => ({ admitted: false, status, why });
15
+ const refuse = (status, why) => typed({ admitted: false, status, why });
15
16
  /** Host always, the launch token on API calls, and the exact Origin on cookie writes. */
16
17
  export const admit = (asked, port, token, enabled = { ui: true, api: false }) => {
17
- if (asked.host === undefined || !origins(port).includes(asked.host))
18
+ if (asked.host === undefined || !origins(port).some((origin) => origin === asked.host))
18
19
  return refuse(403, "not this listener's host");
19
20
  if (asked.authorization !== undefined) {
20
21
  const bearer = asked.authorization.startsWith("Bearer ") ? asked.authorization.slice(7) : "";
21
- return enabled.api && same(bearer, token) ? { admitted: true } : refuse(401, "invalid bearer token");
22
+ return enabled.api && same(bearer, token) ? typed({ admitted: true }) : refuse(401, "invalid bearer token");
22
23
  }
23
24
  const writes = asked.method !== "GET" && asked.method !== "HEAD";
24
25
  // Cookie credentials are ambient: the request must originate at the host it names.
25
26
  if (writes && asked.origin !== `http://${asked.host}`)
26
27
  return refuse(403, "not this listener's origin");
27
28
  if (!asked.path.startsWith("/api/"))
28
- return { admitted: true };
29
+ return typed({ admitted: true });
29
30
  const presented = cookieValue(asked.cookie, cookieName(port));
30
- return enabled.ui && presented !== undefined && same(presented, token) ? { admitted: true } : refuse(401, "no token: open the URL kayra serve printed, or use its API token");
31
+ return enabled.ui && presented !== undefined && same(presented, token) ? typed({ admitted: true }) : refuse(401, "no token: open the URL kayra serve printed, or use its API token");
31
32
  };
32
33
  /** The token the opened URL carries, if it is this launch's. */
33
34
  export const tokenIn = (query, token) => {
@@ -1,27 +1,63 @@
1
- export const offered = (server) => [
1
+ import { typed } from "../../lib/typed.js";
2
+ export const offered = (server) => typed([
2
3
  ...(server.kind === "platform" ? ["deploy", "apps", "verify"] : []),
3
4
  "setup", "plan",
4
5
  ...(server.target === "multipass" && server.kind === "platform" ? ["up"] : []),
5
- ...(server.terraform || server.vm ? ["provision"] : []),
6
+ ...(server.hasTerraform || server.buildsVm ? ["provision"] : []),
6
7
  ...(server.backupDir === undefined ? [] : ["backup.test"]),
7
8
  ...(server.kind === "platform" ? ["job"] : []),
8
9
  ...(server.target === "multipass" ? [] : ["adopt"]),
9
- ...(server.terraform ? ["down"] : []),
10
- ];
11
- export const facts = (server) => ({
10
+ ...(server.hasTerraform ? ["down"] : []),
11
+ ]);
12
+ export const facts = (server) => typed({
12
13
  name: server.name, kind: server.kind, target: server.target, domain: server.domain,
13
14
  apps: server.apps.map((app) => app.name), commands: offered(server),
14
15
  });
16
+ /** What follows the server and the app on the command line, by operation. */
17
+ const extra = (call) => {
18
+ switch (call.name) {
19
+ case "ssh.exec":
20
+ return ["--", ...call.input.command];
21
+ case "job":
22
+ return [call.input.job, ...(call.input.noPrs ? ["--no-prs"] : [])];
23
+ case "app.rollback":
24
+ return [call.input.sha];
25
+ case "app.deploy":
26
+ return call.input.ref === undefined ? [] : [call.input.ref];
27
+ case "app.log":
28
+ return call.input.run === undefined ? [] : [call.input.run];
29
+ case "app.check":
30
+ return [call.input.dir];
31
+ case "certs":
32
+ return [call.input.domain, ...call.input.subdomains];
33
+ case "up":
34
+ case "provision":
35
+ case "deploy":
36
+ case "setup":
37
+ case "plan":
38
+ case "verify":
39
+ case "apps":
40
+ case "hosts":
41
+ case "ssh":
42
+ case "down":
43
+ case "adopt":
44
+ case "backup.test":
45
+ case "app.purge":
46
+ case "app.runs":
47
+ case "app.releases":
48
+ case "status":
49
+ case "validate":
50
+ case "doctor":
51
+ case "version":
52
+ return [];
53
+ }
54
+ };
55
+ /** How the command line spells an operation where its words are not its name's. */
56
+ const spelled = { "ssh.exec": "ssh", "app.releases": "app rollback", "app.log": "app logs" };
57
+ /** The command's words, as typed on the command line. */
15
58
  export const words = (call) => {
16
59
  const { input } = call;
17
60
  const scope = ["server" in input ? input.server : undefined, "app" in input ? input.app : undefined];
18
- const more = "command" in input ? ["--", ...input.command]
19
- : "job" in input ? [input.job, ...(input.noPrs ? ["--no-prs"] : [])]
20
- : "sha" in input ? [input.sha]
21
- : "ref" in input ? [input.ref]
22
- : "run" in input ? [input.run]
23
- : "dir" in input ? [input.dir]
24
- : "domain" in input ? [input.domain, ...input.subdomains] : [];
25
- const name = call.name === "ssh.exec" ? "ssh" : call.name === "app.releases" ? "app rollback" : call.name === "app.log" ? "app logs" : call.name.replaceAll(".", " ");
26
- return ["kayra", name, ...scope, ...more].filter((word) => word !== undefined).join(" ");
61
+ const name = spelled[call.name] ?? call.name.replaceAll(".", " ");
62
+ return ["kayra", name, ...scope, ...extra(call)].filter((word) => word !== undefined).join(" ");
27
63
  };
@@ -1,14 +1,16 @@
1
1
  import { z } from "zod";
2
2
  import { operations, operationNames } from "../../core/operations/catalog.js";
3
3
  import { options, schemas, querySchemas } from "./protocol.js";
4
- export const catalog = () => operationNames.map((name) => {
4
+ import { typed } from "../../lib/typed.js";
5
+ export const catalog = () => Object.freeze(operationNames.map((name) => {
5
6
  const { summary, scope, effect, kind, input } = operations[name];
6
7
  return { name, summary, scope, effect, kind, input: z.toJSONSchema(input, { io: "input" }) };
7
- });
8
+ }));
8
9
  const isObject = (value) => typeof value === "object" && value !== null;
9
- const object = (value) => isObject(value) ? value : {};
10
- const list = (value) => Array.isArray(value) ? value : [];
10
+ const object = (value) => isObject(value) ? value : typed({});
11
+ const list = (value) => typed(Array.isArray(value) ? value : []);
11
12
  const literal = (value) => JSON.stringify(value);
13
+ // Recursive: TypeScript cannot infer what it returns.
12
14
  const typescript = (value) => {
13
15
  const schema = object(value);
14
16
  if ("const" in schema)
@@ -67,13 +69,13 @@ export const openapi = (version) => ({
67
69
  "/openapi.json": { get: { responses: { "200": response("This OpenAPI document", { type: "object" }) } } },
68
70
  "/fleet": { get: { responses: { "200": response("The fleet", ref("FleetFacts")) } } },
69
71
  "/directories": { get: { summary: "Browse local directories for app.check", parameters: [{ name: "path", in: "query", schema: { type: "string", default: "." } }], responses: { "200": response("Directories only, relative paths resolved from the fleet", ref("DirectoryListing")), "400": { description: "Directory cannot be read" } } } },
70
- ...Object.fromEntries(catalog().flatMap(({ name, summary, kind, input }) => [
72
+ ...Object.fromEntries(catalog().flatMap(({ name, summary, kind, input }) => typed([
71
73
  [`/operations/${name}`, { post: { summary, operationId: name, requestBody: request(input), responses: kind === "plan" || kind === "session" ? {
72
74
  [kind === "session" ? "201" : "202"]: response("Started", { type: "object", properties: { [kind === "session" ? "session" : "run"]: { type: "string" } }, required: [kind === "session" ? "session" : "run"] }),
73
75
  "200": response("Dry run", ref("Preview")), "400": { description: "Invalid input" }, "403": { description: "Real server not confirmed" }, "409": { description: "Server busy" },
74
76
  } : { "200": response(summary, kind === "stream" ? ref("Status") : resultOf(name), kind === "stream" ? "text/event-stream" : "application/json") } } }],
75
77
  ...(kind === "plan" || kind === "session" ? [[`/operations/${name}/preview`, { post: { summary: `Preview: ${summary}`, requestBody: request(input), responses: { "200": response("Plan preview", ref("Preview")) } } }]] : []),
76
- ])),
78
+ ]))),
77
79
  "/runs": { get: { responses: { "200": response("Runs from this fleet", { type: "array", items: ref("RunSummary") }) } } },
78
80
  "/runs/{id}": { get: { parameters: [id], responses: { "200": response("A recorded run", ref("Run")), "404": { description: "No run" } } } },
79
81
  "/runs/{id}/events": { get: { parameters: [id], responses: { "200": { description: "Events replayed from the start, then followed until the run ends", content: { "text/event-stream": { schema: ref("RunEvent") }, "application/x-ndjson": { schema: ref("RunEvent") } } } } } },
@@ -1,6 +1,6 @@
1
1
  import { readdir, realpath, stat } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
- import { err, ok } from "../../result.js";
3
+ import { err, ok } from "../../lib/result.js";
4
4
  export const directories = async (path, root) => {
5
5
  try {
6
6
  const absolute = await realpath(resolve(root, path));
@@ -1,7 +1,7 @@
1
1
  import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { z } from "zod";
4
- import { err, ok } from "../../result.js";
4
+ import { err, ok } from "../../lib/result.js";
5
5
  const entry = z.object({ url: z.string(), token: z.string(), pid: z.number().int().positive() });
6
6
  const alive = (pid) => {
7
7
  try {
@@ -29,8 +29,13 @@ export const discover = (file, url, token) => {
29
29
  }
30
30
  }
31
31
  const contents = `${JSON.stringify({ url, token, pid: process.pid })}\n`;
32
- mkdirSync(dirname(file), { recursive: true });
33
- writeFileSync(file, contents, { mode: 0o600, flag: "wx" });
32
+ try {
33
+ mkdirSync(dirname(file), { recursive: true });
34
+ writeFileSync(file, contents, { mode: 0o600, flag: "wx" });
35
+ }
36
+ catch (error) {
37
+ return err(`${file} could not be written: ${error instanceof Error ? error.message : String(error)}`);
38
+ }
34
39
  return ok({ remove: () => {
35
40
  if (existsSync(file) && readFileSync(file, "utf8") === contents)
36
41
  unlinkSync(file);