@yunuseon/kayra 0.16.0 → 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.
- package/README.md +4 -0
- package/agent/skills/kayra-release/SKILL.md +8 -0
- package/cli/dist/browser/assets/index-9a-SE2rU.js +7 -0
- package/cli/dist/{web/assets/index-3W_NFATj.css → browser/assets/index-Ct0Eudk4.css} +1 -1
- package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
- package/cli/dist/{web → browser}/index.html +2 -2
- package/cli/dist/clients/api/api.js +269 -0
- package/cli/dist/clients/api/auth.js +36 -0
- package/cli/dist/clients/api/commands.js +27 -0
- package/cli/dist/clients/api/contract.gen.js +1 -0
- package/cli/dist/clients/api/contract.js +89 -0
- package/cli/dist/clients/api/directories.js +20 -0
- package/cli/dist/clients/api/discovery.js +38 -0
- package/cli/dist/clients/api/protocol.js +61 -0
- package/cli/dist/clients/api/queries.js +20 -0
- package/cli/dist/clients/api/runs.js +51 -0
- package/cli/dist/{ui → clients/cli}/explain.js +5 -5
- package/cli/dist/clients/cli/framed.js +64 -0
- package/cli/dist/clients/cli/invocation.js +83 -0
- package/cli/dist/clients/cli/paint.js +23 -0
- package/cli/dist/{cli.js → clients/cli/parser.js} +31 -25
- package/cli/dist/clients/cli/questions.js +88 -0
- package/cli/dist/{ui → clients/cli}/terminal.js +1 -13
- package/cli/dist/clients/ui/assets.js +36 -0
- package/cli/dist/clients/ui/opener.js +9 -0
- package/cli/dist/{brand.js → core/brand.js} +1 -1
- package/cli/dist/{commands → core/commands}/app-check.js +1 -1
- package/cli/dist/{commands → core/commands}/server.js +26 -17
- package/cli/dist/{commands → core/commands}/status.js +3 -3
- package/cli/dist/{commands → core/commands}/validate.js +1 -1
- package/cli/dist/{fleet.js → core/fleet.js} +1 -1
- package/cli/dist/core/interpret.js +276 -0
- package/cli/dist/{load.js → core/load.js} +1 -1
- package/cli/dist/core/operations/catalog.js +152 -0
- package/cli/dist/core/operations/run.js +139 -0
- package/cli/dist/{plan.js → core/plan.js} +11 -4
- package/cli/dist/core/present/line.js +17 -0
- package/cli/dist/{ui → core/present}/progress.js +2 -61
- package/cli/dist/{schemas.js → core/schemas.js} +1 -1
- package/cli/dist/core/updates.js +13 -0
- package/cli/dist/{validate.js → core/validate.js} +1 -1
- package/cli/dist/main.js +92 -93
- package/cli/dist/serve.js +77 -0
- package/package.json +4 -3
- package/scripts/agent/guard.sh +9 -2
- package/scripts/local/packed-runs.sh +43 -0
- package/scripts/local/setup-hosts.sh +9 -2
- package/cli/dist/commands/index.js +0 -52
- package/cli/dist/interpret.js +0 -141
- package/cli/dist/ui/line.js +0 -39
- package/cli/dist/web/assets/index-DRFX9Q77.js +0 -2
- /package/cli/dist/{commands → core/commands}/doctor.js +0 -0
- /package/cli/dist/{gather.js → core/gather.js} +0 -0
- /package/cli/dist/{net.js → core/net.js} +0 -0
- /package/cli/dist/{ui → core/present}/text.js +0 -0
- /package/cli/dist/{ui → core/present}/views.js +0 -0
- /package/cli/dist/{settings.js → core/settings.js} +0 -0
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
<meta name="color-scheme" content="light dark" />
|
|
7
7
|
<title>kayra</title>
|
|
8
8
|
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%235b5bd6'/%3E%3Cpath d='M11 8v16M11 16l9-8M14 13l7 11' stroke='white' stroke-width='3' stroke-linecap='round' fill='none'/%3E%3C/svg%3E" />
|
|
9
|
-
<script type="module" crossorigin src="/assets/index-
|
|
10
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-9a-SE2rU.js"></script>
|
|
10
|
+
<link rel="stylesheet" crossorigin href="/assets/index-Ct0Eudk4.css">
|
|
11
11
|
</head>
|
|
12
12
|
<body>
|
|
13
13
|
<div id="app"></div>
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import { join, sep } from "node:path";
|
|
4
|
+
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";
|
|
15
|
+
import { catalog, openapi } from "./contract.js";
|
|
16
|
+
import { directories } from "./directories.js";
|
|
17
|
+
import { facts, words } from "./commands.js";
|
|
18
|
+
import { answer as queryAnswer } from "./queries.js";
|
|
19
|
+
import { options, requestBody } from "./protocol.js";
|
|
20
|
+
import { busy, readRecord, recordLine, runId, stateOf, summary } from "./runs.js";
|
|
21
|
+
const answerJson = (response, status, value) => {
|
|
22
|
+
send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
|
|
23
|
+
};
|
|
24
|
+
const events = (response, ndjson = false) => {
|
|
25
|
+
response.writeHead(200, { "Content-Type": ndjson ? "application/x-ndjson" : "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
|
|
26
|
+
return {
|
|
27
|
+
say: (value) => { if (!response.destroyed)
|
|
28
|
+
response.write(ndjson ? `${JSON.stringify(value)}\n` : `data: ${JSON.stringify(value)}\n\n`); },
|
|
29
|
+
end: () => { response.end(ndjson ? "" : "event: end\ndata: {}\n\n"); },
|
|
30
|
+
};
|
|
31
|
+
};
|
|
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;
|
|
128
|
+
}
|
|
129
|
+
const { say, end } = events(response, ndjson);
|
|
130
|
+
run.events.forEach(say);
|
|
131
|
+
if (live === undefined || stateOf(run.events) !== "running") {
|
|
132
|
+
end();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
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) })); });
|
|
139
|
+
};
|
|
140
|
+
const dispatch = async (request, response, url) => {
|
|
141
|
+
const method = request.method ?? "GET";
|
|
142
|
+
const path = url.pathname;
|
|
143
|
+
const named = /^\/api\/operations\/([^/]+)(\/preview)?$/.exec(path);
|
|
144
|
+
const runPath = /^\/api\/runs\/([^/]+)(?:\/(events|answers|cancel))?$/.exec(path);
|
|
145
|
+
const sessionPath = /^\/api\/sessions\/([^/]+)(?:\/(output|input))?$/.exec(path);
|
|
146
|
+
const ndjson = request.headers.accept?.includes("application/x-ndjson") === true;
|
|
147
|
+
if (method === "GET" && path === "/api/operations")
|
|
148
|
+
answerJson(response, 200, catalog());
|
|
149
|
+
else if (method === "GET" && path === "/api/openapi.json")
|
|
150
|
+
answerJson(response, 200, openapi(api.version));
|
|
151
|
+
else if (method === "GET" && path === "/api/directories") {
|
|
152
|
+
const result = await directories(url.searchParams.get("path") ?? ".", api.fleet.root);
|
|
153
|
+
if (result.ok)
|
|
154
|
+
answerJson(response, 200, result.value);
|
|
155
|
+
else
|
|
156
|
+
send(response, 400, `${result.error}\n`);
|
|
157
|
+
}
|
|
158
|
+
else if (method === "GET" && path === "/api/fleet") {
|
|
159
|
+
const factsOfFleet = { fleet: api.fleet.root.split(sep).at(-1) ?? "", version: api.version, servers: api.fleet.servers.map(facts) };
|
|
160
|
+
answerJson(response, 200, factsOfFleet);
|
|
161
|
+
}
|
|
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
|
+
}
|
|
208
|
+
else if (method === "GET" && path === "/api/runs") {
|
|
209
|
+
const runs = allRuns().map(summary);
|
|
210
|
+
answerJson(response, 200, runs);
|
|
211
|
+
}
|
|
212
|
+
else if (runPath !== null || sessionPath !== null) {
|
|
213
|
+
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");
|
|
251
|
+
}
|
|
252
|
+
else
|
|
253
|
+
send(response, 404, "not found\n");
|
|
254
|
+
};
|
|
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 () => {
|
|
265
|
+
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
|
+
} };
|
|
269
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
/** Cookies are shared by every port of a host: the name carries the port, so another local server's cookie is not ours. */
|
|
3
|
+
export const cookieName = (port) => `kayra_ui_${String(port)}`;
|
|
4
|
+
const origins = (port) => [`127.0.0.1:${String(port)}`, `localhost:${String(port)}`];
|
|
5
|
+
const same = (a, b) => {
|
|
6
|
+
const left = Buffer.from(a);
|
|
7
|
+
const right = Buffer.from(b);
|
|
8
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
9
|
+
};
|
|
10
|
+
const cookieValue = (header, name) => header
|
|
11
|
+
?.split(";")
|
|
12
|
+
.map((pair) => pair.trim().split("="))
|
|
13
|
+
.find(([key]) => key === name)?.[1];
|
|
14
|
+
const refuse = (status, why) => ({ admitted: false, status, why });
|
|
15
|
+
/** Host always, the launch token on API calls, and the exact Origin on cookie writes. */
|
|
16
|
+
export const admit = (asked, port, token, enabled = { ui: true, api: false }) => {
|
|
17
|
+
if (asked.host === undefined || !origins(port).includes(asked.host))
|
|
18
|
+
return refuse(403, "not this listener's host");
|
|
19
|
+
if (asked.authorization !== undefined) {
|
|
20
|
+
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
|
+
}
|
|
23
|
+
const writes = asked.method !== "GET" && asked.method !== "HEAD";
|
|
24
|
+
// Cookie credentials are ambient: the request must originate at the host it names.
|
|
25
|
+
if (writes && asked.origin !== `http://${asked.host}`)
|
|
26
|
+
return refuse(403, "not this listener's origin");
|
|
27
|
+
if (!asked.path.startsWith("/api/"))
|
|
28
|
+
return { admitted: true };
|
|
29
|
+
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
|
+
};
|
|
32
|
+
/** The token the opened URL carries, if it is this launch's. */
|
|
33
|
+
export const tokenIn = (query, token) => {
|
|
34
|
+
const given = query.get("token");
|
|
35
|
+
return given !== null && same(given, token);
|
|
36
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const offered = (server) => [
|
|
2
|
+
...(server.kind === "platform" ? ["deploy", "apps", "verify"] : []),
|
|
3
|
+
"setup", "plan",
|
|
4
|
+
...(server.target === "multipass" && server.kind === "platform" ? ["up"] : []),
|
|
5
|
+
...(server.terraform || server.vm ? ["provision"] : []),
|
|
6
|
+
...(server.backupDir === undefined ? [] : ["backup.test"]),
|
|
7
|
+
...(server.kind === "platform" ? ["job"] : []),
|
|
8
|
+
...(server.target === "multipass" ? [] : ["adopt"]),
|
|
9
|
+
...(server.terraform ? ["down"] : []),
|
|
10
|
+
];
|
|
11
|
+
export const facts = (server) => ({
|
|
12
|
+
name: server.name, kind: server.kind, target: server.target, domain: server.domain,
|
|
13
|
+
apps: server.apps.map((app) => app.name), commands: offered(server),
|
|
14
|
+
});
|
|
15
|
+
export const words = (call) => {
|
|
16
|
+
const { input } = call;
|
|
17
|
+
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(" ");
|
|
27
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { operations, operationNames } from "../../core/operations/catalog.js";
|
|
3
|
+
import { options, schemas, querySchemas } from "./protocol.js";
|
|
4
|
+
export const catalog = () => operationNames.map((name) => {
|
|
5
|
+
const { summary, scope, effect, kind, input } = operations[name];
|
|
6
|
+
return { name, summary, scope, effect, kind, input: z.toJSONSchema(input, { io: "input" }) };
|
|
7
|
+
});
|
|
8
|
+
const isObject = (value) => typeof value === "object" && value !== null;
|
|
9
|
+
const object = (value) => isObject(value) ? value : {};
|
|
10
|
+
const list = (value) => Array.isArray(value) ? value : [];
|
|
11
|
+
const literal = (value) => JSON.stringify(value);
|
|
12
|
+
const typescript = (value) => {
|
|
13
|
+
const schema = object(value);
|
|
14
|
+
if ("const" in schema)
|
|
15
|
+
return literal(schema["const"]);
|
|
16
|
+
if (Array.isArray(schema["enum"]))
|
|
17
|
+
return schema["enum"].map(literal).join(" | ");
|
|
18
|
+
if (Array.isArray(schema["anyOf"]))
|
|
19
|
+
return schema["anyOf"].map(typescript).join(" | ");
|
|
20
|
+
if (Array.isArray(schema["oneOf"]))
|
|
21
|
+
return schema["oneOf"].map(typescript).join(" | ");
|
|
22
|
+
if (Array.isArray(schema["type"]))
|
|
23
|
+
return schema["type"].map((type) => typescript({ ...schema, type })).join(" | ");
|
|
24
|
+
switch (schema["type"]) {
|
|
25
|
+
case "null": return "null";
|
|
26
|
+
case "string": return "string";
|
|
27
|
+
case "integer":
|
|
28
|
+
case "number": return "number";
|
|
29
|
+
case "boolean": return "boolean";
|
|
30
|
+
case "array": return `readonly (${typescript(schema["items"])})[]`;
|
|
31
|
+
case "object": {
|
|
32
|
+
const properties = Object.entries(object(schema["properties"]));
|
|
33
|
+
const required = list(schema["required"]);
|
|
34
|
+
const fields = properties.map(([key, property]) => `readonly ${literal(key)}${required.includes(key) ? "" : "?"}: ${typescript(property)}`).join("; ");
|
|
35
|
+
if (properties.length === 0 && schema["additionalProperties"] === false)
|
|
36
|
+
return "Readonly<Record<string, never>>";
|
|
37
|
+
return properties.length === 0 ? `Readonly<Record<string, ${typescript(schema["additionalProperties"])}>>` : `{ ${fields} }`;
|
|
38
|
+
}
|
|
39
|
+
default: return "unknown";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
export const contractTypes = () => [
|
|
43
|
+
"// Generated by npm run contract. The pinned kayra version defines this /api contract.",
|
|
44
|
+
...Object.entries(schemas).map(([name, schema]) => `export type ${name} = ${typescript(z.toJSONSchema(schema))};`),
|
|
45
|
+
`export type OperationInputs = { ${operationNames.map((name) => `readonly ${literal(name)}: ${typescript(z.toJSONSchema(operations[name].input, { io: "input" }))}`).join("; ")} };`,
|
|
46
|
+
'export type OperationName = keyof OperationInputs;',
|
|
47
|
+
'export type InputOf<N extends OperationName> = OperationInputs[N];',
|
|
48
|
+
'export type OperationCall = { readonly [N in OperationName]: { readonly name: N; readonly input: InputOf<N> } }[OperationName];',
|
|
49
|
+
`export type RunOptions = ${typescript(z.toJSONSchema(options, { io: "input" }))};`,
|
|
50
|
+
"",
|
|
51
|
+
].join("\n");
|
|
52
|
+
const response = (description, schema, media = "application/json") => ({ description, content: { [media]: { schema } } });
|
|
53
|
+
const ref = (name) => ({ $ref: `#/components/schemas/${name}` });
|
|
54
|
+
const isQueryName = (name) => Object.hasOwn(querySchemas, name);
|
|
55
|
+
const resultOf = (name) => isQueryName(name) ? z.toJSONSchema(querySchemas[name]) : {};
|
|
56
|
+
const request = (input) => ({ required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, properties: { input, options: z.toJSONSchema(options, { io: "input" }), confirm: { type: "string", description: "The real server's name, required before a change" } } } } } });
|
|
57
|
+
const id = { name: "id", in: "path", required: true, schema: { type: "string" } };
|
|
58
|
+
const body = (properties, required) => ({ required: true, content: { "application/json": { schema: { type: "object", properties, required, additionalProperties: false } } } });
|
|
59
|
+
const write = (description) => ({ description, responses: { "204": { description: "Accepted" }, "404": { description: "No active resource" } } });
|
|
60
|
+
export const openapi = (version) => ({
|
|
61
|
+
openapi: "3.1.0",
|
|
62
|
+
info: { title: "kayra local API", version, description: "127.0.0.1 only. Compatibility follows the fleet's pinned kayra version." },
|
|
63
|
+
servers: [{ url: "/api" }],
|
|
64
|
+
security: [{ bearer: [] }, { cookie: [] }],
|
|
65
|
+
paths: {
|
|
66
|
+
"/operations": { get: { responses: { "200": response("The operation catalog", { type: "array", items: ref("OperationInfo") }) } } },
|
|
67
|
+
"/openapi.json": { get: { responses: { "200": response("This OpenAPI document", { type: "object" }) } } },
|
|
68
|
+
"/fleet": { get: { responses: { "200": response("The fleet", ref("FleetFacts")) } } },
|
|
69
|
+
"/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 }) => [
|
|
71
|
+
[`/operations/${name}`, { post: { summary, operationId: name, requestBody: request(input), responses: kind === "plan" || kind === "session" ? {
|
|
72
|
+
[kind === "session" ? "201" : "202"]: response("Started", { type: "object", properties: { [kind === "session" ? "session" : "run"]: { type: "string" } }, required: [kind === "session" ? "session" : "run"] }),
|
|
73
|
+
"200": response("Dry run", ref("Preview")), "400": { description: "Invalid input" }, "403": { description: "Real server not confirmed" }, "409": { description: "Server busy" },
|
|
74
|
+
} : { "200": response(summary, kind === "stream" ? ref("Status") : resultOf(name), kind === "stream" ? "text/event-stream" : "application/json") } } }],
|
|
75
|
+
...(kind === "plan" || kind === "session" ? [[`/operations/${name}/preview`, { post: { summary: `Preview: ${summary}`, requestBody: request(input), responses: { "200": response("Plan preview", ref("Preview")) } } }]] : []),
|
|
76
|
+
])),
|
|
77
|
+
"/runs": { get: { responses: { "200": response("Runs from this fleet", { type: "array", items: ref("RunSummary") }) } } },
|
|
78
|
+
"/runs/{id}": { get: { parameters: [id], responses: { "200": response("A recorded run", ref("Run")), "404": { description: "No run" } } } },
|
|
79
|
+
"/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") } } } } } },
|
|
80
|
+
"/runs/{id}/answers": { post: { ...write("Answer the pending question; answers are never recorded"), parameters: [id], requestBody: body({ text: { type: "string" } }, ["text"]) } },
|
|
81
|
+
"/runs/{id}/cancel": { post: { ...write("Cancel a run"), parameters: [id] } },
|
|
82
|
+
"/sessions/{id}/output": { get: { parameters: [id], responses: { "200": response("Session events", ref("RunEvent"), "text/event-stream") } } },
|
|
83
|
+
"/sessions/{id}/input": { post: { ...write("Send terminal input; input is never recorded"), parameters: [id], requestBody: body({ text: { type: "string" } }, ["text"]) } },
|
|
84
|
+
"/sessions/{id}": { delete: { ...write("Close the session"), parameters: [id] } },
|
|
85
|
+
},
|
|
86
|
+
components: { securitySchemes: { bearer: { type: "http", scheme: "bearer" }, cookie: { type: "apiKey", in: "cookie", name: "kayra_ui_<port>", description: "The browser's per-port cookie, set by the launch URL" } }, schemas: Object.fromEntries(Object.entries(schemas).map(([name, schema]) => {
|
|
87
|
+
return [name, Object.fromEntries(Object.entries(z.toJSONSchema(schema)).filter(([key]) => key !== "$schema"))];
|
|
88
|
+
})) },
|
|
89
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { readdir, realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { err, ok } from "../../result.js";
|
|
4
|
+
export const directories = async (path, root) => {
|
|
5
|
+
try {
|
|
6
|
+
const absolute = await realpath(resolve(root, path));
|
|
7
|
+
const entries = await readdir(absolute, { withFileTypes: true });
|
|
8
|
+
const children = await Promise.all(entries.map(async (entry) => {
|
|
9
|
+
const path = resolve(absolute, entry.name);
|
|
10
|
+
const directory = entry.isDirectory() ||
|
|
11
|
+
(entry.isSymbolicLink() &&
|
|
12
|
+
(await stat(path).then((info) => info.isDirectory(), () => false)));
|
|
13
|
+
return directory ? [{ name: entry.name, path }] : [];
|
|
14
|
+
}));
|
|
15
|
+
return ok({ path: absolute, parent: dirname(absolute), directories: children.flat().toSorted((a, b) => a.name.localeCompare(b.name)) });
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return err("Cannot read that directory. Check its path and permissions.");
|
|
19
|
+
}
|
|
20
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { err, ok } from "../../result.js";
|
|
5
|
+
const entry = z.object({ url: z.string(), token: z.string(), pid: z.number().int().positive() });
|
|
6
|
+
const alive = (pid) => {
|
|
7
|
+
try {
|
|
8
|
+
process.kill(pid, 0);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
return !(error instanceof Error && "code" in error && error.code === "ESRCH");
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
export const discover = (file, url, token) => {
|
|
16
|
+
if (existsSync(file)) {
|
|
17
|
+
if (!lstatSync(file).isFile())
|
|
18
|
+
return err(`${file} is not a regular discovery file`);
|
|
19
|
+
try {
|
|
20
|
+
const previous = entry.safeParse(JSON.parse(readFileSync(file, "utf8")));
|
|
21
|
+
if (!previous.success)
|
|
22
|
+
return err(`${file} is unreadable; remove it before starting kayra serve`);
|
|
23
|
+
if (alive(previous.data.pid))
|
|
24
|
+
return err(`kayra serve is already discoverable for this fleet (pid ${String(previous.data.pid)})`);
|
|
25
|
+
unlinkSync(file);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return err(`${file} is unreadable; remove it before starting kayra serve`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
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" });
|
|
34
|
+
return ok({ remove: () => {
|
|
35
|
+
if (existsSync(file) && readFileSync(file, "utf8") === contents)
|
|
36
|
+
unlinkSync(file);
|
|
37
|
+
} });
|
|
38
|
+
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { operationNames } from "../../core/operations/catalog.js";
|
|
3
|
+
import { releasesSchema, runsSchema } from "../../core/present/views.js";
|
|
4
|
+
const tone = z.enum(["ok", "bad", "warn", "active", "muted", "strong", "accent"]);
|
|
5
|
+
const span = z.union([z.string(), z.object({ tone: tone.exactOptional(), text: z.string(), href: z.string().exactOptional() })]);
|
|
6
|
+
const line = z.array(span);
|
|
7
|
+
const text = z.union([z.string(), line]);
|
|
8
|
+
const part = z.enum(["provision", "setup", "apps", "verify", "hosts"]);
|
|
9
|
+
const listed = z.object({ index: z.number().int(), kind: z.string(), title: z.string(), command: z.string().exactOptional(), part: part.exactOptional(), opens: part.exactOptional() });
|
|
10
|
+
const invocation = z.object({ command: z.string(), server: z.string().exactOptional(), about: z.array(z.string()) });
|
|
11
|
+
const stop = z.enum(["failed", "declined", "interrupted"]);
|
|
12
|
+
const state = z.enum(["running", "passed", "failed", "interrupted", "declined"]);
|
|
13
|
+
const summary = z.object({ id: z.string(), command: z.string(), server: z.string().exactOptional(), started: z.string(), state, session: z.boolean() });
|
|
14
|
+
const ended = z.object({ kind: z.literal("ended"), failures: z.number(), stop: z.object({ index: z.number(), why: stop }).exactOptional(), ms: z.number(), footer: z.array(line) });
|
|
15
|
+
const event = z.discriminatedUnion("kind", [
|
|
16
|
+
z.object({ kind: z.literal("plan"), invocation, steps: z.array(listed) }),
|
|
17
|
+
z.object({ kind: z.literal("started"), index: z.number() }),
|
|
18
|
+
z.object({ kind: z.literal("done"), index: z.number(), failed: z.boolean(), stopped: z.boolean(), why: z.string().exactOptional(), ms: z.number() }),
|
|
19
|
+
ended,
|
|
20
|
+
z.object({ kind: z.literal("output"), stream: z.enum(["stdout", "stderr"]), chunk: z.string() }),
|
|
21
|
+
z.object({ kind: z.literal("said"), stream: z.enum(["out", "err"]), text }),
|
|
22
|
+
z.object({ kind: z.literal("ask"), prompt: text, secret: z.boolean(), expect: z.string().exactOptional() }),
|
|
23
|
+
z.object({ kind: z.literal("answered") }),
|
|
24
|
+
]);
|
|
25
|
+
const reach = z.enum(["pending", "open", "answered", "refused", "no-answer", "unreachable", "unknown-host", "bad-certificate", "failed", "skipped"]);
|
|
26
|
+
const verdict = z.enum(["problem", "unchecked", "passed"]);
|
|
27
|
+
const serverCommand = z.enum(["up", "provision", "deploy", "setup", "plan", "verify", "apps", "down", "adopt", "backup.test"]);
|
|
28
|
+
const serverFacts = z.object({
|
|
29
|
+
name: z.string(), kind: z.enum(["platform", "edge", "nas"]), target: z.enum(["multipass", "hetzner", "home"]), domain: z.string(), apps: z.array(z.string()),
|
|
30
|
+
commands: z.array(z.union([serverCommand, z.literal("job")])),
|
|
31
|
+
});
|
|
32
|
+
export const options = z.strictObject({
|
|
33
|
+
verbose: z.boolean().default(false),
|
|
34
|
+
dryRun: z.boolean().default(false),
|
|
35
|
+
columns: z.number().int().min(1).max(1000).default(120),
|
|
36
|
+
rows: z.number().int().min(1).max(1000).default(32),
|
|
37
|
+
});
|
|
38
|
+
export const requestBody = z.strictObject({ input: z.unknown().exactOptional(), options: options.exactOptional(), confirm: z.string().exactOptional() });
|
|
39
|
+
export const schemas = {
|
|
40
|
+
Tone: tone, Span: span, Line: line, Text: text, Part: part, Listed: listed, Invocation: invocation, Stop: stop, RunState: state,
|
|
41
|
+
RunEvent: event, RunSummary: summary,
|
|
42
|
+
Run: summary.extend({ events: z.array(event) }),
|
|
43
|
+
Preview: z.object({ invocation, steps: z.array(listed), changes: z.boolean() }),
|
|
44
|
+
ServerCommand: serverCommand,
|
|
45
|
+
ServerFacts: serverFacts,
|
|
46
|
+
FleetFacts: z.object({ fleet: z.string(), version: z.string(), servers: z.array(serverFacts) }),
|
|
47
|
+
DirectoryListing: z.object({ path: z.string(), parent: z.string(), directories: z.array(z.object({ name: z.string(), path: z.string() })) }),
|
|
48
|
+
ReachState: reach,
|
|
49
|
+
Status: z.object({ servers: z.array(z.object({
|
|
50
|
+
name: z.string(), kind: z.string(), target: z.string(), domain: z.string(), apps: z.array(z.string()),
|
|
51
|
+
machine: z.object({ state: z.enum(["pending", "found", "not-provisioned", "no-machine", "unreadable"]), address: z.string().nullable(), from: z.enum(["inventory", "opentofu"]).nullable(), reason: z.string().nullable() }),
|
|
52
|
+
ssh: z.object({ port: z.number(), state: reach, ms: z.number().nullable(), error: z.string().nullable() }),
|
|
53
|
+
https: z.object({ url: z.string(), state: reach, status: z.number().nullable(), ms: z.number().nullable(), error: z.string().nullable() }).nullable(),
|
|
54
|
+
})) }),
|
|
55
|
+
Validation: z.object({ result: verdict, servers: z.array(z.object({ name: z.string(), kind: z.string(), target: z.string(), result: verdict, findings: z.array(z.object({ result: verdict, text: z.string(), hint: z.string().nullable() })) })) }),
|
|
56
|
+
AppRuns: runsSchema, AppReleases: releasesSchema,
|
|
57
|
+
OperationInfo: z.object({ name: z.enum(operationNames), summary: z.string(), scope: z.enum(["fleet", "server", "app", "repo"]), effect: z.enum(["reads", "changes", "destroys"]), kind: z.enum(["plan", "query", "stream", "session"]), input: z.record(z.string(), z.unknown()) }),
|
|
58
|
+
};
|
|
59
|
+
export const querySchemas = {
|
|
60
|
+
validate: schemas.Validation, version: z.string(), "app.runs": schemas.AppRuns, "app.releases": schemas.AppReleases, "app.log": z.string(),
|
|
61
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { query } from "../../core/operations/run.js";
|
|
3
|
+
import { validateJson } from "../../core/commands/validate.js";
|
|
4
|
+
import { parsed, releasesSchema, runsSchema } from "../../core/present/views.js";
|
|
5
|
+
import { err, map, ok } from "../../result.js";
|
|
6
|
+
// eslint-disable-next-line functional/prefer-immutable-types -- Zod schemas are immutable; each method returns a new schema
|
|
7
|
+
const data = (schema, text) => {
|
|
8
|
+
if (!text.ok)
|
|
9
|
+
return text;
|
|
10
|
+
const value = parsed(schema, text.value);
|
|
11
|
+
return value === undefined ? err("the deployer returned an unreadable answer") : ok(value);
|
|
12
|
+
};
|
|
13
|
+
const queries = {
|
|
14
|
+
validate: async (context, input) => map(await query(context, "validate", input), validateJson),
|
|
15
|
+
version: (context, input) => query(context, "version", input),
|
|
16
|
+
"app.runs": async (context, input) => data(runsSchema, await query(context, "app.runs", input)),
|
|
17
|
+
"app.releases": async (context, input) => data(releasesSchema, await query(context, "app.releases", input)),
|
|
18
|
+
"app.log": (context, input) => query(context, "app.log", input),
|
|
19
|
+
};
|
|
20
|
+
export const answer = (context, name, input) => queries[name](context, input);
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Sortable by time (an ISO 8601 instant), unique by its tail. */
|
|
2
|
+
export const runId = (iso, random) => `${iso.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${random}`;
|
|
3
|
+
export const stateOf = (events) => {
|
|
4
|
+
const ended = events.findLast((event) => event.kind === "ended");
|
|
5
|
+
if (ended?.kind !== "ended")
|
|
6
|
+
return "running";
|
|
7
|
+
if (ended.stop?.why === "interrupted")
|
|
8
|
+
return "interrupted";
|
|
9
|
+
if (ended.stop?.why === "declined")
|
|
10
|
+
return "declined";
|
|
11
|
+
return ended.failures === 0 ? "passed" : "failed";
|
|
12
|
+
};
|
|
13
|
+
export const summary = (run) => ({
|
|
14
|
+
id: run.id,
|
|
15
|
+
command: run.command,
|
|
16
|
+
...(run.server === undefined ? {} : { server: run.server }),
|
|
17
|
+
started: run.started,
|
|
18
|
+
session: run.session,
|
|
19
|
+
state: stateOf(run.events),
|
|
20
|
+
});
|
|
21
|
+
/** What a run's record holds: the run, then each event, one JSON value per line. */
|
|
22
|
+
export const recordLine = (value) => `${JSON.stringify(value)}\n`;
|
|
23
|
+
const isObject = (value) => typeof value === "object" && value !== null;
|
|
24
|
+
/** A record as kayra wrote it; a run killed mid-write keeps what it had, and what it had says "running". */
|
|
25
|
+
export const readRecord = (text) => {
|
|
26
|
+
const [head, ...rest] = text
|
|
27
|
+
.split("\n")
|
|
28
|
+
.filter((line) => line !== "")
|
|
29
|
+
.flatMap((line) => {
|
|
30
|
+
try {
|
|
31
|
+
return [JSON.parse(line)];
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
if (!isObject(head) || typeof head["id"] !== "string" || typeof head["command"] !== "string" || typeof head["started"] !== "string")
|
|
38
|
+
return undefined;
|
|
39
|
+
// Written by this kayra, the lines are its own events.
|
|
40
|
+
const events = rest.filter((each) => isObject(each) && typeof each["kind"] === "string");
|
|
41
|
+
return {
|
|
42
|
+
id: head["id"],
|
|
43
|
+
command: head["command"],
|
|
44
|
+
...(typeof head["server"] === "string" ? { server: head["server"] } : {}),
|
|
45
|
+
started: head["started"],
|
|
46
|
+
events,
|
|
47
|
+
session: head["session"] === true,
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
/** A server is busy while a run on it has not ended: one at a time, as on the command line. */
|
|
51
|
+
export const busy = (runs, server) => server !== undefined && runs.some((run) => run.server === server && stateOf(run.events) === "running");
|