@yunuseon/kayra 0.17.0 → 0.17.1

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 (101) hide show
  1. package/ansible/roles/platform/tasks/main.yml +31 -0
  2. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  3. package/cli/dist/browser/index.html +1 -1
  4. package/cli/dist/clients/api/api.js +138 -218
  5. package/cli/dist/clients/api/auth.js +8 -7
  6. package/cli/dist/clients/api/commands.js +50 -14
  7. package/cli/dist/clients/api/contract.js +8 -6
  8. package/cli/dist/clients/api/discovery.js +7 -2
  9. package/cli/dist/clients/api/live.js +40 -0
  10. package/cli/dist/clients/api/protocol.js +17 -10
  11. package/cli/dist/clients/api/queries.js +3 -3
  12. package/cli/dist/clients/api/runs.js +10 -9
  13. package/cli/dist/clients/api/start.js +97 -0
  14. package/cli/dist/clients/api/status.js +29 -0
  15. package/cli/dist/clients/api/validate.js +13 -0
  16. package/cli/dist/clients/cli/explain.js +12 -10
  17. package/cli/dist/clients/cli/framed.js +12 -9
  18. package/cli/dist/clients/cli/invocation.js +4 -3
  19. package/cli/dist/clients/cli/paint.js +1 -1
  20. package/cli/dist/clients/cli/parser.js +8 -8
  21. package/cli/dist/clients/cli/questions.js +11 -10
  22. package/cli/dist/clients/cli/status.js +75 -0
  23. package/cli/dist/clients/cli/terminal.js +4 -2
  24. package/cli/dist/{core/present → clients/cli}/text.js +15 -24
  25. package/cli/dist/clients/cli/validate.js +32 -0
  26. package/cli/dist/clients/cli/values.js +19 -0
  27. package/cli/dist/{core/present → clients/cli}/views.js +28 -60
  28. package/cli/dist/core/adapters/fs.js +18 -0
  29. package/cli/dist/core/{net.js → adapters/network.js} +20 -5
  30. package/cli/dist/core/adapters/opentofu.js +24 -0
  31. package/cli/dist/core/ctl/answers.js +32 -0
  32. package/cli/dist/core/fleet/brand.js +45 -0
  33. package/cli/dist/core/{schemas.js → fleet/docs.js} +4 -3
  34. package/cli/dist/core/fleet/load.js +44 -0
  35. package/cli/dist/core/fleet/model.js +1 -0
  36. package/cli/dist/core/{fleet.js → fleet/parse.js} +61 -41
  37. package/cli/dist/core/{settings.js → fleet/settings.js} +10 -3
  38. package/cli/dist/core/{validate.js → fleet/shape.js} +6 -5
  39. package/cli/dist/core/{present/progress.js → interpreter/events.js} +27 -31
  40. package/cli/dist/core/interpreter/io.js +18 -0
  41. package/cli/dist/core/interpreter/loop.js +101 -0
  42. package/cli/dist/core/interpreter/needs.js +47 -0
  43. package/cli/dist/core/interpreter/process.js +107 -0
  44. package/cli/dist/core/interpreter/progress.js +15 -0
  45. package/cli/dist/core/interpreter/pty.js +8 -0
  46. package/cli/dist/core/operations/catalog.js +35 -18
  47. package/cli/dist/core/operations/{run.js → dispatch.js} +49 -46
  48. package/cli/dist/core/{plan.js → plan/describe.js} +4 -14
  49. package/cli/dist/core/plan/model.js +14 -0
  50. package/cli/dist/core/{commands → recipes}/app-check.js +11 -16
  51. package/cli/dist/core/recipes/apps.js +63 -0
  52. package/cli/dist/core/recipes/backup.js +34 -0
  53. package/cli/dist/core/recipes/certs.js +4 -0
  54. package/cli/dist/core/{commands → recipes}/doctor.js +20 -35
  55. package/cli/dist/core/recipes/host.js +104 -0
  56. package/cli/dist/core/recipes/ssh.js +20 -0
  57. package/cli/dist/core/recipes/steps.js +82 -0
  58. package/cli/dist/core/status/look.js +55 -0
  59. package/cli/dist/core/status/model.js +6 -0
  60. package/cli/dist/core/status/ports.js +1 -0
  61. package/cli/dist/core/text/plural.js +2 -0
  62. package/cli/dist/core/text/spans.js +22 -0
  63. package/cli/dist/core/text/time.js +12 -0
  64. package/cli/dist/core/validation/facts.js +49 -0
  65. package/cli/dist/core/{commands/validate.js → validation/findings.js} +31 -66
  66. package/cli/dist/deployer/app.js +2 -1
  67. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  68. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  69. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  70. package/cli/dist/deployer/cron.js +2 -2
  71. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  72. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  73. package/cli/dist/deployer/deployer.js +23 -22
  74. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  75. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  76. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  77. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  78. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  79. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  80. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  81. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  82. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  83. package/cli/dist/deployer/main.js +2 -2
  84. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  85. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  86. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  87. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  88. package/cli/dist/main.js +89 -89
  89. package/cli/dist/result.js +11 -1
  90. package/cli/dist/serve.js +2 -2
  91. package/cli/dist/typed.js +2 -0
  92. package/package.json +3 -2
  93. package/cli/dist/browser/assets/index-9a-SE2rU.js +0 -7
  94. package/cli/dist/core/brand.js +0 -39
  95. package/cli/dist/core/commands/server.js +0 -298
  96. package/cli/dist/core/commands/status.js +0 -194
  97. package/cli/dist/core/gather.js +0 -61
  98. package/cli/dist/core/interpret.js +0 -276
  99. package/cli/dist/core/load.js +0 -64
  100. package/cli/dist/core/present/line.js +0 -17
  101. /package/cli/dist/core/{updates.js → status/updates.js} +0 -0
@@ -1,7 +1,8 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
+ import { typed } from "../../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 "../../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 "../../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") } } } } } },
@@ -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);
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The runs of one listener, in one cell replaced whole: no launch shares
3
+ * locks, credentials or sessions with another.
4
+ */
5
+ export const liveRuns = () => {
6
+ // eslint-disable-next-line functional/prefer-immutable-types -- the one state cell of this listener's runs
7
+ const cell = { runs: {} };
8
+ return {
9
+ get: (id) => cell.runs[id],
10
+ all: () => Object.values(cell.runs),
11
+ /** Installed before any asynchronous work: the run's lock. */
12
+ add: (id, live) => {
13
+ // eslint-disable-next-line functional/immutable-data -- replace the one state cell whole
14
+ cell.runs = { ...cell.runs, [id]: live };
15
+ },
16
+ swap: (id, change) => {
17
+ const current = cell.runs[id];
18
+ // eslint-disable-next-line functional/immutable-data -- replace the one state cell whole
19
+ if (current !== undefined)
20
+ cell.runs = { ...cell.runs, [id]: change(current) };
21
+ },
22
+ };
23
+ };
24
+ /** The requests in flight: shutdown waits for them as well as for the runs. */
25
+ export const inFlight = () => {
26
+ // eslint-disable-next-line functional/prefer-immutable-types -- the requests not yet answered
27
+ const cell = { pending: [] };
28
+ return {
29
+ track: (work) => {
30
+ const tracked = work.finally(() => {
31
+ // eslint-disable-next-line functional/immutable-data -- release it once its response completes
32
+ cell.pending = cell.pending.filter((pending) => pending !== tracked);
33
+ });
34
+ // eslint-disable-next-line functional/immutable-data -- one more request in flight
35
+ cell.pending = [...cell.pending, tracked];
36
+ return tracked;
37
+ },
38
+ settled: () => Promise.allSettled(cell.pending),
39
+ };
40
+ };
@@ -1,14 +1,21 @@
1
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"]);
2
+ import { effects, kinds, operationNames, scopes } from "../../core/operations/catalog.js";
3
+ import { serverKinds } from "../../core/fleet/settings.js";
4
+ import { serverTargets } from "../../core/fleet/model.js";
5
+ import { parts } from "../../core/plan/model.js";
6
+ import { stopReasons } from "../../core/interpreter/progress.js";
7
+ import { machineStates, reachStates } from "../../core/status/model.js";
8
+ import { tones } from "../../core/text/spans.js";
9
+ import { verdicts } from "../../core/validation/findings.js";
10
+ import { releasesSchema, runsSchema } from "../../core/ctl/answers.js";
11
+ const tone = z.enum(tones);
5
12
  const span = z.union([z.string(), z.object({ tone: tone.exactOptional(), text: z.string(), href: z.string().exactOptional() })]);
6
13
  const line = z.array(span);
7
14
  const text = z.union([z.string(), line]);
8
- const part = z.enum(["provision", "setup", "apps", "verify", "hosts"]);
15
+ const part = z.enum(parts);
9
16
  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
17
  const invocation = z.object({ command: z.string(), server: z.string().exactOptional(), about: z.array(z.string()) });
11
- const stop = z.enum(["failed", "declined", "interrupted"]);
18
+ const stop = z.enum(stopReasons);
12
19
  const state = z.enum(["running", "passed", "failed", "interrupted", "declined"]);
13
20
  const summary = z.object({ id: z.string(), command: z.string(), server: z.string().exactOptional(), started: z.string(), state, session: z.boolean() });
14
21
  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) });
@@ -22,11 +29,11 @@ const event = z.discriminatedUnion("kind", [
22
29
  z.object({ kind: z.literal("ask"), prompt: text, secret: z.boolean(), expect: z.string().exactOptional() }),
23
30
  z.object({ kind: z.literal("answered") }),
24
31
  ]);
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"]);
32
+ const reach = z.enum(reachStates);
33
+ const verdict = z.enum(verdicts);
27
34
  const serverCommand = z.enum(["up", "provision", "deploy", "setup", "plan", "verify", "apps", "down", "adopt", "backup.test"]);
28
35
  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()),
36
+ name: z.string(), kind: z.enum(serverKinds), target: z.enum(serverTargets), domain: z.string(), apps: z.array(z.string()),
30
37
  commands: z.array(z.union([serverCommand, z.literal("job")])),
31
38
  });
32
39
  export const options = z.strictObject({
@@ -48,13 +55,13 @@ export const schemas = {
48
55
  ReachState: reach,
49
56
  Status: z.object({ servers: z.array(z.object({
50
57
  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() }),
58
+ machine: z.object({ state: z.enum(machineStates), address: z.string().nullable(), from: z.enum(["inventory", "opentofu"]).nullable(), reason: z.string().nullable() }),
52
59
  ssh: z.object({ port: z.number(), state: reach, ms: z.number().nullable(), error: z.string().nullable() }),
53
60
  https: z.object({ url: z.string(), state: reach, status: z.number().nullable(), ms: z.number().nullable(), error: z.string().nullable() }).nullable(),
54
61
  })) }),
55
62
  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
63
  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()) }),
64
+ OperationInfo: z.object({ name: z.enum(operationNames), summary: z.string(), scope: z.enum(scopes), effect: z.enum(effects), kind: z.enum(kinds), input: z.record(z.string(), z.unknown()) }),
58
65
  };
59
66
  export const querySchemas = {
60
67
  validate: schemas.Validation, version: z.string(), "app.runs": schemas.AppRuns, "app.releases": schemas.AppReleases, "app.log": z.string(),
@@ -1,7 +1,7 @@
1
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";
2
+ import { query } from "../../core/operations/dispatch.js";
3
+ import { validateJson } from "./validate.js";
4
+ import { parsed, releasesSchema, runsSchema } from "../../core/ctl/answers.js";
5
5
  import { err, map, ok } from "../../result.js";
6
6
  // eslint-disable-next-line functional/prefer-immutable-types -- Zod schemas are immutable; each method returns a new schema
7
7
  const data = (schema, text) => {
@@ -1,16 +1,17 @@
1
+ import { typed } from "../../typed.js";
1
2
  /** Sortable by time (an ISO 8601 instant), unique by its tail. */
2
3
  export const runId = (iso, random) => `${iso.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${random}`;
3
4
  export const stateOf = (events) => {
4
5
  const ended = events.findLast((event) => event.kind === "ended");
5
6
  if (ended?.kind !== "ended")
6
- return "running";
7
+ return typed("running");
7
8
  if (ended.stop?.why === "interrupted")
8
- return "interrupted";
9
+ return typed("interrupted");
9
10
  if (ended.stop?.why === "declined")
10
- return "declined";
11
- return ended.failures === 0 ? "passed" : "failed";
11
+ return typed("declined");
12
+ return typed(ended.failures === 0 ? "passed" : "failed");
12
13
  };
13
- export const summary = (run) => ({
14
+ export const summary = (run) => typed({
14
15
  id: run.id,
15
16
  command: run.command,
16
17
  ...(run.server === undefined ? {} : { server: run.server }),
@@ -28,24 +29,24 @@ export const readRecord = (text) => {
28
29
  .filter((line) => line !== "")
29
30
  .flatMap((line) => {
30
31
  try {
31
- return [JSON.parse(line)];
32
+ return typed([JSON.parse(line)]);
32
33
  }
33
34
  catch {
34
- return [];
35
+ return typed([]);
35
36
  }
36
37
  });
37
38
  if (!isObject(head) || typeof head["id"] !== "string" || typeof head["command"] !== "string" || typeof head["started"] !== "string")
38
39
  return undefined;
39
40
  // Written by this kayra, the lines are its own events.
40
41
  const events = rest.filter((each) => isObject(each) && typeof each["kind"] === "string");
41
- return {
42
+ return typed({
42
43
  id: head["id"],
43
44
  command: head["command"],
44
45
  ...(typeof head["server"] === "string" ? { server: head["server"] } : {}),
45
46
  started: head["started"],
46
47
  events,
47
48
  session: head["session"] === true,
48
- };
49
+ });
49
50
  };
50
51
  /** A server is busy while a run on it has not ended: one at a time, as on the command line. */
51
52
  export const busy = (runs, server) => server !== undefined && runs.some((run) => run.server === server && stateOf(run.events) === "running");
@@ -0,0 +1,97 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { z } from "zod";
5
+ import { milliseconds } from "../../core/fleet/brand.js";
6
+ import { heading, listed, reporting } from "../../core/interpreter/events.js";
7
+ import { interpret } from "../../core/interpreter/loop.js";
8
+ import { operation } from "../../core/operations/catalog.js";
9
+ import { hasPlan, planOf, serverOf } from "../../core/operations/dispatch.js";
10
+ import { verbose } from "../../core/recipes/steps.js";
11
+ import { err, ok } from "../../result.js";
12
+ import { typed } from "../../typed.js";
13
+ import { words } from "./commands.js";
14
+ import { busy, readRecord, recordLine, runId } from "./runs.js";
15
+ /** Every run there is: the live ones, then those recorded, newest first. */
16
+ export const allRuns = (served) => {
17
+ const live = served.runs.all().map((each) => each.run);
18
+ const records = existsSync(served.dir)
19
+ ? readdirSync(served.dir).filter((name) => name.endsWith(".jsonl")).flatMap((name) => {
20
+ const run = readRecord(readFileSync(join(served.dir, name), "utf8"));
21
+ return run === undefined || live.some((each) => each.id === run.id) ? [] : [run];
22
+ })
23
+ : [];
24
+ return Object.freeze([...live, ...records].toSorted((a, b) => b.id.localeCompare(a.id)));
25
+ };
26
+ const about = (served, call) => heading(words(call), serverOf(served.context, call), served.api.version);
27
+ const recipe = (served, call, settings) => {
28
+ if (!hasPlan(call))
29
+ return err(`${call.name} has no plan`);
30
+ const plan = planOf(served.context, call);
31
+ return plan.ok && settings.verbose ? ok(verbose(plan.value)) : plan;
32
+ };
33
+ /** The plan an operation would run, as the browser lists it. */
34
+ export const preview = (served, call, settings) => {
35
+ const plan = recipe(served, call, settings);
36
+ return plan.ok
37
+ ? ok({ invocation: about(served, call), steps: listed(plan.value, served.api.short), changes: operation(call.name).effect !== "reads" })
38
+ : plan;
39
+ };
40
+ /**
41
+ * A plan or a session, started: recorded as it goes, its questions and input
42
+ * answered over HTTP. A change to a server that is not multipass needs its
43
+ * name in `confirm`; one run per server at a time.
44
+ */
45
+ export const start = (served, call, settings, confirm) => {
46
+ const { runs } = served;
47
+ if (served.shutdown.signal.aborted)
48
+ return err(typed([503, "kayra is stopping"]));
49
+ const plan = recipe(served, call, settings);
50
+ if (!plan.ok)
51
+ return err(typed([400, plan.error]));
52
+ const server = serverOf(served.context, call);
53
+ if (busy(runs.all().map((live) => live.run), server?.name))
54
+ return err(typed([409, `a run on ${server?.name ?? ""} has not ended`]));
55
+ if (operation(call.name).effect !== "reads" && server !== undefined && server.target !== "multipass" && confirm !== server.name)
56
+ return err(typed([403, `this changes ${server.name}: confirm with its name`]));
57
+ const started = new Date().toISOString();
58
+ const id = runId(started, randomBytes(6).toString("hex"));
59
+ const session = operation(call.name).kind === "session";
60
+ const run = { id, command: words(call), started, events: [], session, ...(server === undefined ? {} : { server: server.name }) };
61
+ mkdirSync(served.dir, { recursive: true });
62
+ const file = join(served.dir, `${id}.jsonl`);
63
+ appendFileSync(file, recordLine({ id, command: run.command, started, session, ...(server === undefined ? {} : { server: server.name }) }));
64
+ const stop = new AbortController();
65
+ runs.add(id, { run, stop, listeners: [], answer: undefined, input: undefined, done: Promise.resolve() });
66
+ const emit = (event) => {
67
+ appendFileSync(file, recordLine(event));
68
+ runs.swap(id, (live) => ({ ...live, run: { ...live.run, events: [...live.run.events, event] } }));
69
+ runs.get(id)?.listeners.forEach((listener) => { listener(event); });
70
+ };
71
+ const io = {
72
+ out: (text) => { emit({ kind: "said", stream: "out", text }); },
73
+ err: (text) => { emit({ kind: "said", stream: "err", text }); },
74
+ ask: (question) => new Promise((resolve) => {
75
+ runs.swap(id, (live) => ({ ...live, answer: (text) => {
76
+ runs.swap(id, (after) => ({ ...after, answer: undefined }));
77
+ emit({ kind: "answered" });
78
+ resolve(text);
79
+ } }));
80
+ emit({ kind: "ask", prompt: question.text, secret: question.kind === "secret", ...(question.kind === "confirm" ? { expect: question.expect } : {}) });
81
+ }),
82
+ output: (chunk, stream) => { emit({ kind: "output", stream, chunk }); },
83
+ input: (deliver) => {
84
+ runs.swap(id, (live) => ({ ...live, input: deliver }));
85
+ return () => { runs.swap(id, (live) => ({ ...live, input: undefined })); };
86
+ },
87
+ size: { columns: settings.columns, rows: settings.rows },
88
+ signal: stop.signal,
89
+ };
90
+ const coloured = plan.value.map((step) => (step.kind === "run" ? { ...step, env: { ...step.env, ANSIBLE_FORCE_COLOR: "1" } } : step));
91
+ const done = interpret(coloured, io, reporting(emit, about(served, call), served.api.short)).catch(() => {
92
+ emit({ kind: "said", stream: "err", text: "The run could not finish; check the local kayra process." });
93
+ emit({ kind: "ended", failures: 1, ms: milliseconds(Date.now() - Date.parse(started)), footer: [] });
94
+ }).finally(() => { runs.swap(id, (live) => ({ ...live, answer: undefined, input: undefined })); });
95
+ runs.swap(id, (live) => ({ ...live, done }));
96
+ return ok(id);
97
+ };
@@ -0,0 +1,29 @@
1
+ import { authUrl, sshPort } from "../../core/status/look.js";
2
+ export const ms = (reach) => ("ms" in reach ? reach.ms : null);
3
+ const error = (reach) => ("code" in reach ? reach.code : null);
4
+ /** `kayra status --json`: the shape cli.md documents. */
5
+ export const statusJson = (looks) => ({
6
+ servers: looks.map(({ server, machine, ssh, https }) => ({
7
+ name: server.name,
8
+ kind: server.kind,
9
+ target: server.target,
10
+ domain: server.domain,
11
+ apps: server.apps.map((app) => app.name),
12
+ machine: {
13
+ state: machine.kind,
14
+ address: machine.kind === "found" ? (machine.address ?? null) : null,
15
+ from: machine.kind === "found" ? machine.from : null,
16
+ reason: machine.kind === "unreadable" ? machine.reason : null,
17
+ },
18
+ ssh: { port: Number(sshPort(server)), state: ssh.kind, ms: ms(ssh), error: error(ssh) },
19
+ https: https === undefined
20
+ ? null
21
+ : {
22
+ url: `${authUrl(server)}api/health`,
23
+ state: https.kind,
24
+ status: https.kind === "answered" ? https.status : null,
25
+ ms: ms(https),
26
+ error: error(https),
27
+ },
28
+ })),
29
+ });
@@ -0,0 +1,13 @@
1
+ import { overall, tally } from "../../core/validation/findings.js";
2
+ /** `kayra validate --json`: the shape cli.md documents. */
3
+ export const validateJson = (reports) => ({
4
+ result: overall(reports.flatMap((report) => report.findings)),
5
+ ...tally(reports),
6
+ servers: reports.map((report) => ({
7
+ name: report.server.name,
8
+ kind: report.server.kind,
9
+ target: report.server.target,
10
+ result: overall(report.findings),
11
+ findings: report.findings.map((each) => ({ result: each.result, text: each.text, hint: each.hint ?? null })),
12
+ })),
13
+ });
@@ -1,8 +1,10 @@
1
- import { commandOf, kindOf, titleOf } from "../../core/plan.js";
2
- import { accent, active, bad, muted, strong, warn } from "../../core/present/line.js";
3
- import { position, steps as count } from "../../core/present/progress.js";
4
- import { wrap } from "../../core/present/text.js";
5
- import { drawnAs } from "../../core/present/views.js";
1
+ import { commandOf, kindOf, titleOf } from "../../core/plan/describe.js";
2
+ import { accent, active, bad, muted, strong, warn } from "../../core/text/spans.js";
3
+ import { position } from "../../core/interpreter/progress.js";
4
+ import { steps as count } from "../../core/interpreter/events.js";
5
+ import { wrap } from "./text.js";
6
+ import { drawnAs } from "./views.js";
7
+ import { typed } from "../../typed.js";
6
8
  const kinds = { guard: warn, check: active, run: active, confirm: bad, note: muted };
7
9
  const tag = (step) => {
8
10
  const kind = kindOf(step);
@@ -19,19 +21,19 @@ export const explain = (invocation, plan, short, columns) => {
19
21
  const steps = plan.flatMap((step, index) => {
20
22
  const { opens } = position(plan, index);
21
23
  const command = commandOf(step);
22
- return [
24
+ return typed([
23
25
  ...(opens === undefined ? [] : index === 0 ? [[accent(opens)]] : [[], [accent(opens)]]),
24
26
  [" ", muted(String(index + 1).padStart(digits)), " ", tag(step), " ", strong(titleOf(step))],
25
27
  ...(step.kind === "confirm" ? [[indent, muted(`asks for '${step.expect}' to be typed, or stops`)]] : []),
26
28
  ...(command === undefined
27
29
  ? []
28
- : wrap(short(command).split(" "), Math.max(40, Math.min(columns, 120) - indent.length - 2)).map((line, at) => [indent, muted(at === 0 ? line : ` ${line}`)])),
30
+ : wrap(short(command).split(" "), Math.max(40, Math.min(columns, 120) - indent.length - 2)).map((line, at) => typed([indent, muted(at === 0 ? line : ` ${line}`)]))),
29
31
  ...(step.kind === "run" && typeof step.stdout === "object" ? [[indent, muted(`→ ${drawnAs(step.stdout)}`)]] : []),
30
- ];
32
+ ]);
31
33
  });
32
- return [
34
+ return typed([
33
35
  [strong(invocation.command), muted([...invocation.about, count(plan), "dry run: nothing runs"].map((each) => ` · ${each}`).join(""))],
34
36
  [],
35
37
  ...steps,
36
- ];
38
+ ]);
37
39
  };
@@ -1,9 +1,12 @@
1
- import { titleOf } from "../../core/plan.js";
2
- import { accent, active, bad, muted, ok, strong } from "../../core/present/line.js";
3
- import { footer, steps } from "../../core/present/progress.js";
4
- import { duration, spread, truncate } from "../../core/present/text.js";
1
+ import { titleOf } from "../../core/plan/describe.js";
2
+ import { accent, active, bad, muted, ok, strong } from "../../core/text/spans.js";
3
+ import { footer, steps } from "../../core/interpreter/events.js";
4
+ import { duration } from "../../core/text/time.js";
5
+ import { spread, truncate } from "./text.js";
5
6
  import { paint } from "./paint.js";
6
7
  import { escapes, spinner } from "./terminal.js";
8
+ import { milliseconds } from "../../core/fleet/brand.js";
9
+ import { typed } from "../../typed.js";
7
10
  /** A run of this long earns a notification when it ends: the operator has looked away. */
8
11
  const worthNotifying = 30_000;
9
12
  /** Frames on stderr: a heading, each step as it runs and how it went, a footer; on a terminal also spinners, the window title, a notification. */
@@ -16,14 +19,14 @@ export const framed = (screen, write, invocation) => {
16
19
  if (when)
17
20
  write(raw);
18
21
  };
19
- return {
22
+ return typed({
20
23
  plan: async (plan, work) => {
21
24
  const started = performance.now();
22
25
  tell(escapes.pushTitle + escapes.title(invocation.command), screen.title);
23
26
  say([strong(invocation.command), muted([...invocation.about, steps(plan)].map((each) => ` · ${each}`).join(""))]);
24
27
  say("");
25
28
  const ended = await work();
26
- const ms = performance.now() - started;
29
+ const ms = milliseconds(performance.now() - started);
27
30
  say("");
28
31
  footer(invocation, plan, ended, ms).forEach(say);
29
32
  tell(escapes.popTitle, screen.title);
@@ -48,7 +51,7 @@ export const framed = (screen, write, invocation) => {
48
51
  if (shown)
49
52
  say(spread([" ", active("◆"), " ", strong(title)], [muted(counter)], columns));
50
53
  const stop = !shown && screen.live
51
- ? spinner(write, (frame, ms) => paint(spread(truncate([" ", active(frame), " ", title], columns - 8), [muted(duration(ms))], columns), screen.colors))
54
+ ? spinner(write, (frame, ms) => paint(spread(truncate([" ", active(frame), " ", title], columns - 8), [muted(duration(milliseconds(ms)))], columns), screen.colors))
52
55
  : () => undefined;
53
56
  const started = performance.now();
54
57
  const done = await work();
@@ -56,9 +59,9 @@ export const framed = (screen, write, invocation) => {
56
59
  // A diagnosis reports itself on stdout: that line is doctor's output.
57
60
  if (step.kind === "check" && step.onFailure === "continue")
58
61
  return done;
59
- const took = duration(performance.now() - started);
62
+ const took = duration(milliseconds(performance.now() - started));
60
63
  say(spread([" ", done.failed ? bad("✗") : ok("✓"), " ", title], [muted(done.why === undefined ? took : `${done.why} · ${took}`)], columns));
61
64
  return done;
62
65
  },
63
- };
66
+ });
64
67
  };
@@ -1,9 +1,10 @@
1
+ import { typed } from "../../typed.js";
1
2
  /**
2
3
  * The parsed command line as the operation it names. `app rollback` without a
3
4
  * commit lists the releases (`app.releases`), with one it rolls back.
4
5
  */
5
6
  export const fromCommand = (command) => {
6
- const plainly = (invocation) => ({ invocation, json: false });
7
+ const plainly = (invocation) => typed({ invocation, json: false });
7
8
  switch (command.name) {
8
9
  case "up":
9
10
  case "provision":
@@ -37,9 +38,9 @@ export const fromCommand = (command) => {
37
38
  case "job":
38
39
  return plainly({ name: "job", input: { server: command.server, job: command.job, noPrs: command.noPrs } });
39
40
  case "status":
40
- return { invocation: { name: "status", input: { offline: command.offline } }, json: command.json };
41
+ return typed({ invocation: { name: "status", input: { offline: command.offline } }, json: command.json });
41
42
  case "validate":
42
- return { invocation: { name: "validate", input: command.server === undefined ? {} : { server: command.server } }, json: command.json };
43
+ return typed({ invocation: { name: "validate", input: command.server === undefined ? {} : { server: command.server } }, json: command.json });
43
44
  case "doctor":
44
45
  return plainly({ name: "doctor", input: {} });
45
46
  case "certs":
@@ -1,5 +1,5 @@
1
1
  import { styleText } from "node:util";
2
- import { spans } from "../../core/present/line.js";
2
+ import { spans } from "../../core/text/spans.js";
3
3
  import { escapes } from "./terminal.js";
4
4
  const looks = {
5
5
  ok: ["green"],