@yunuseon/kayra 0.16.1 → 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 (117) hide show
  1. package/README.md +4 -0
  2. package/ansible/roles/platform/tasks/main.yml +31 -0
  3. package/cli/dist/browser/assets/{index-3W_NFATj.css → index-Ct0Eudk4.css} +1 -1
  4. package/cli/dist/browser/assets/index-hcyM6f6T.js +7 -0
  5. package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
  6. package/cli/dist/browser/index.html +2 -2
  7. package/cli/dist/clients/api/api.js +189 -0
  8. package/cli/dist/clients/api/auth.js +37 -0
  9. package/cli/dist/clients/api/commands.js +63 -0
  10. package/cli/dist/clients/api/contract.gen.js +1 -0
  11. package/cli/dist/clients/api/contract.js +91 -0
  12. package/cli/dist/clients/api/directories.js +20 -0
  13. package/cli/dist/clients/api/discovery.js +43 -0
  14. package/cli/dist/clients/api/live.js +40 -0
  15. package/cli/dist/clients/api/protocol.js +68 -0
  16. package/cli/dist/clients/api/queries.js +20 -0
  17. package/cli/dist/{web → clients/api}/runs.js +14 -11
  18. package/cli/dist/clients/api/start.js +97 -0
  19. package/cli/dist/clients/api/status.js +29 -0
  20. package/cli/dist/clients/api/validate.js +13 -0
  21. package/cli/dist/{ui → clients/cli}/explain.js +10 -8
  22. package/cli/dist/clients/cli/framed.js +67 -0
  23. package/cli/dist/clients/cli/invocation.js +84 -0
  24. package/cli/dist/clients/cli/paint.js +23 -0
  25. package/cli/dist/{cli.js → clients/cli/parser.js} +38 -32
  26. package/cli/dist/clients/cli/questions.js +89 -0
  27. package/cli/dist/clients/cli/status.js +75 -0
  28. package/cli/dist/{ui → clients/cli}/terminal.js +5 -15
  29. package/cli/dist/{ui → clients/cli}/text.js +15 -24
  30. package/cli/dist/clients/cli/validate.js +32 -0
  31. package/cli/dist/clients/cli/values.js +19 -0
  32. package/cli/dist/{ui → clients/cli}/views.js +28 -60
  33. package/cli/dist/clients/ui/assets.js +36 -0
  34. package/cli/dist/core/adapters/fs.js +18 -0
  35. package/cli/dist/{net.js → core/adapters/network.js} +20 -5
  36. package/cli/dist/core/adapters/opentofu.js +24 -0
  37. package/cli/dist/core/ctl/answers.js +32 -0
  38. package/cli/dist/core/fleet/brand.js +45 -0
  39. package/cli/dist/{schemas.js → core/fleet/docs.js} +4 -3
  40. package/cli/dist/core/fleet/load.js +44 -0
  41. package/cli/dist/core/fleet/model.js +1 -0
  42. package/cli/dist/{fleet.js → core/fleet/parse.js} +61 -41
  43. package/cli/dist/{settings.js → core/fleet/settings.js} +10 -3
  44. package/cli/dist/{validate.js → core/fleet/shape.js} +6 -5
  45. package/cli/dist/core/interpreter/events.js +81 -0
  46. package/cli/dist/core/interpreter/io.js +18 -0
  47. package/cli/dist/core/interpreter/loop.js +101 -0
  48. package/cli/dist/core/interpreter/needs.js +47 -0
  49. package/cli/dist/core/interpreter/process.js +107 -0
  50. package/cli/dist/core/interpreter/progress.js +15 -0
  51. package/cli/dist/core/interpreter/pty.js +8 -0
  52. package/cli/dist/core/operations/catalog.js +169 -0
  53. package/cli/dist/core/operations/dispatch.js +142 -0
  54. package/cli/dist/{plan.js → core/plan/describe.js} +13 -16
  55. package/cli/dist/core/plan/model.js +14 -0
  56. package/cli/dist/{commands → core/recipes}/app-check.js +11 -16
  57. package/cli/dist/core/recipes/apps.js +63 -0
  58. package/cli/dist/core/recipes/backup.js +34 -0
  59. package/cli/dist/core/recipes/certs.js +4 -0
  60. package/cli/dist/{commands → core/recipes}/doctor.js +20 -35
  61. package/cli/dist/core/recipes/host.js +104 -0
  62. package/cli/dist/core/recipes/ssh.js +20 -0
  63. package/cli/dist/core/recipes/steps.js +82 -0
  64. package/cli/dist/core/status/look.js +55 -0
  65. package/cli/dist/core/status/model.js +6 -0
  66. package/cli/dist/core/status/ports.js +1 -0
  67. package/cli/dist/core/status/updates.js +13 -0
  68. package/cli/dist/core/text/plural.js +2 -0
  69. package/cli/dist/core/text/spans.js +22 -0
  70. package/cli/dist/core/text/time.js +12 -0
  71. package/cli/dist/core/validation/facts.js +49 -0
  72. package/cli/dist/{commands/validate.js → core/validation/findings.js} +31 -66
  73. package/cli/dist/deployer/app.js +2 -1
  74. package/cli/dist/deployer/{builder.js → build/builder.js} +14 -13
  75. package/cli/dist/deployer/{bundle.js → build/bundle.js} +8 -7
  76. package/cli/dist/deployer/{compose.js → build/compose.js} +8 -7
  77. package/cli/dist/deployer/cron.js +2 -2
  78. package/cli/dist/deployer/{answers.js → ctl/answers.js} +5 -4
  79. package/cli/dist/deployer/{ctl.js → ctl/ctl.js} +3 -3
  80. package/cli/dist/deployer/deployer.js +23 -22
  81. package/cli/dist/deployer/{forge.js → forges/forge.js} +2 -1
  82. package/cli/dist/deployer/{forgejo.js → forges/forgejo.js} +2 -2
  83. package/cli/dist/deployer/{github.js → forges/github.js} +2 -2
  84. package/cli/dist/deployer/{gitlab.js → forges/gitlab.js} +2 -2
  85. package/cli/dist/deployer/{github-issues.js → forges/issues.js} +5 -4
  86. package/cli/dist/deployer/{notify.js → forges/notify.js} +9 -8
  87. package/cli/dist/deployer/{http.js → http/http.js} +1 -0
  88. package/cli/dist/deployer/{page.js → http/page.js} +1 -1
  89. package/cli/dist/deployer/{webhook.js → http/webhook.js} +2 -1
  90. package/cli/dist/deployer/main.js +2 -2
  91. package/cli/dist/deployer/{queue.js → runs/queue.js} +4 -3
  92. package/cli/dist/deployer/{records.js → runs/records.js} +9 -8
  93. package/cli/dist/deployer/{run.js → runs/run.js} +10 -9
  94. package/cli/dist/deployer/{store.js → runs/store.js} +9 -8
  95. package/cli/dist/main.js +98 -99
  96. package/cli/dist/result.js +11 -1
  97. package/cli/dist/serve.js +77 -0
  98. package/cli/dist/typed.js +2 -0
  99. package/package.json +4 -2
  100. package/scripts/agent/guard.sh +9 -2
  101. package/scripts/local/packed-runs.sh +20 -5
  102. package/scripts/local/setup-hosts.sh +9 -2
  103. package/cli/dist/brand.js +0 -39
  104. package/cli/dist/browser/assets/index-DRFX9Q77.js +0 -2
  105. package/cli/dist/commands/index.js +0 -52
  106. package/cli/dist/commands/server.js +0 -289
  107. package/cli/dist/commands/status.js +0 -194
  108. package/cli/dist/gather.js +0 -61
  109. package/cli/dist/interpret.js +0 -141
  110. package/cli/dist/load.js +0 -64
  111. package/cli/dist/ui/line.js +0 -39
  112. package/cli/dist/ui/progress.js +0 -144
  113. package/cli/dist/web/auth.js +0 -36
  114. package/cli/dist/web/commands.js +0 -102
  115. package/cli/dist/web/contract.js +0 -7
  116. package/cli/dist/web/server.js +0 -336
  117. /package/cli/dist/{web → clients/ui}/opener.js +0 -0
@@ -1,49 +1,52 @@
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 }),
17
18
  started: run.started,
19
+ session: run.session,
18
20
  state: stateOf(run.events),
19
21
  });
20
22
  /** What a run's record holds: the run, then each event, one JSON value per line. */
21
23
  export const recordLine = (value) => `${JSON.stringify(value)}\n`;
22
24
  const isObject = (value) => typeof value === "object" && value !== null;
23
- /** A record as kayra ui wrote it; a run killed mid-write keeps what it had, and what it had says "running". */
25
+ /** A record as kayra wrote it; a run killed mid-write keeps what it had, and what it had says "running". */
24
26
  export const readRecord = (text) => {
25
27
  const [head, ...rest] = text
26
28
  .split("\n")
27
29
  .filter((line) => line !== "")
28
30
  .flatMap((line) => {
29
31
  try {
30
- return [JSON.parse(line)];
32
+ return typed([JSON.parse(line)]);
31
33
  }
32
34
  catch {
33
- return [];
35
+ return typed([]);
34
36
  }
35
37
  });
36
38
  if (!isObject(head) || typeof head["id"] !== "string" || typeof head["command"] !== "string" || typeof head["started"] !== "string")
37
39
  return undefined;
38
- // Written by this kayra ui, the lines are its own events.
40
+ // Written by this kayra, the lines are its own events.
39
41
  const events = rest.filter((each) => isObject(each) && typeof each["kind"] === "string");
40
- return {
42
+ return typed({
41
43
  id: head["id"],
42
44
  command: head["command"],
43
45
  ...(typeof head["server"] === "string" ? { server: head["server"] } : {}),
44
46
  started: head["started"],
45
47
  events,
46
- };
48
+ session: head["session"] === true,
49
+ });
47
50
  };
48
51
  /** A server is busy while a run on it has not ended: one at a time, as on the command line. */
49
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 "../plan.js";
2
- import { accent, active, bad, muted, strong, warn } from "./line.js";
3
- import { position, steps as count } from "./progress.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";
4
5
  import { wrap } from "./text.js";
5
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
  };
@@ -0,0 +1,67 @@
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";
6
+ import { paint } from "./paint.js";
7
+ import { escapes, spinner } from "./terminal.js";
8
+ import { milliseconds } from "../../core/fleet/brand.js";
9
+ import { typed } from "../../typed.js";
10
+ /** A run of this long earns a notification when it ends: the operator has looked away. */
11
+ const worthNotifying = 30_000;
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. */
13
+ export const framed = (screen, write, invocation) => {
14
+ const columns = Math.min(screen.columns, 80);
15
+ const say = (text) => {
16
+ write(`${paint(text, screen.colors)}\n`);
17
+ };
18
+ const tell = (raw, when) => {
19
+ if (when)
20
+ write(raw);
21
+ };
22
+ return typed({
23
+ plan: async (plan, work) => {
24
+ const started = performance.now();
25
+ tell(escapes.pushTitle + escapes.title(invocation.command), screen.title);
26
+ say([strong(invocation.command), muted([...invocation.about, steps(plan)].map((each) => ` · ${each}`).join(""))]);
27
+ say("");
28
+ const ended = await work();
29
+ const ms = milliseconds(performance.now() - started);
30
+ say("");
31
+ footer(invocation, plan, ended, ms).forEach(say);
32
+ tell(escapes.popTitle, screen.title);
33
+ tell(escapes.progressDone, screen.progressBar);
34
+ const failed = ended.failures > 0 || ended.stop?.why === "failed";
35
+ tell(escapes.notify(`${invocation.command} ${failed ? "failed" : "is done"} after ${duration(ms)}`), screen.notifications && ms >= worthNotifying);
36
+ return ended;
37
+ },
38
+ step: async (step, at, work) => {
39
+ if (step.kind === "confirm" || step.kind === "note")
40
+ return work();
41
+ if (at.opens !== undefined) {
42
+ if (at.index > 0)
43
+ say("");
44
+ say([accent(at.opens)]);
45
+ }
46
+ const title = titleOf(step);
47
+ const counter = `${String(at.index + 1)}/${String(at.total)}`;
48
+ tell(escapes.title(`${invocation.command} · ${counter} ${title}`), screen.title);
49
+ tell(escapes.progress((at.index / at.total) * 100), screen.progressBar);
50
+ const shown = step.kind === "run" && step.stdout === "show";
51
+ if (shown)
52
+ say(spread([" ", active("◆"), " ", strong(title)], [muted(counter)], columns));
53
+ const stop = !shown && screen.live
54
+ ? spinner(write, (frame, ms) => paint(spread(truncate([" ", active(frame), " ", title], columns - 8), [muted(duration(milliseconds(ms)))], columns), screen.colors))
55
+ : () => undefined;
56
+ const started = performance.now();
57
+ const done = await work();
58
+ stop();
59
+ // A diagnosis reports itself on stdout: that line is doctor's output.
60
+ if (step.kind === "check" && step.onFailure === "continue")
61
+ return done;
62
+ const took = duration(milliseconds(performance.now() - started));
63
+ say(spread([" ", done.failed ? bad("✗") : ok("✓"), " ", title], [muted(done.why === undefined ? took : `${done.why} · ${took}`)], columns));
64
+ return done;
65
+ },
66
+ });
67
+ };
@@ -0,0 +1,84 @@
1
+ import { typed } from "../../typed.js";
2
+ /**
3
+ * The parsed command line as the operation it names. `app rollback` without a
4
+ * commit lists the releases (`app.releases`), with one it rolls back.
5
+ */
6
+ export const fromCommand = (command) => {
7
+ const plainly = (invocation) => typed({ invocation, json: false });
8
+ switch (command.name) {
9
+ case "up":
10
+ case "provision":
11
+ case "deploy":
12
+ case "setup":
13
+ case "plan":
14
+ case "verify":
15
+ case "apps":
16
+ case "hosts":
17
+ case "down":
18
+ case "adopt":
19
+ return plainly({ name: command.name, input: { server: command.server } });
20
+ case "backup test":
21
+ return plainly({ name: "backup.test", input: { server: command.server } });
22
+ case "ssh":
23
+ return plainly(command.remote.length === 0 ? { name: "ssh", input: { server: command.server } } : { name: "ssh.exec", input: { server: command.server, command: command.remote } });
24
+ case "app check":
25
+ return plainly({ name: "app.check", input: { dir: command.dir ?? "." } });
26
+ case "app purge":
27
+ return plainly({ name: "app.purge", input: { server: command.server, app: command.app } });
28
+ case "app runs":
29
+ return plainly({ name: "app.runs", input: { server: command.server, app: command.app } });
30
+ case "app logs":
31
+ return plainly({ name: "app.log", input: { server: command.server, app: command.app, ...(command.more === undefined ? {} : { run: command.more }) } });
32
+ case "app deploy":
33
+ return plainly({ name: "app.deploy", input: { server: command.server, app: command.app, ...(command.more === undefined ? {} : { ref: command.more }) } });
34
+ case "app rollback":
35
+ return plainly(command.more === undefined
36
+ ? { name: "app.releases", input: { server: command.server, app: command.app } }
37
+ : { name: "app.rollback", input: { server: command.server, app: command.app, sha: command.more } });
38
+ case "job":
39
+ return plainly({ name: "job", input: { server: command.server, job: command.job, noPrs: command.noPrs } });
40
+ case "status":
41
+ return typed({ invocation: { name: "status", input: { offline: command.offline } }, json: command.json });
42
+ case "validate":
43
+ return typed({ invocation: { name: "validate", input: command.server === undefined ? {} : { server: command.server } }, json: command.json });
44
+ case "doctor":
45
+ return plainly({ name: "doctor", input: {} });
46
+ case "certs":
47
+ return plainly({ name: "certs", input: { domain: command.domain, subdomains: command.subdomains } });
48
+ }
49
+ };
50
+ /**
51
+ * How the command line reaches each operation: a sample argument list
52
+ * (SERVER and APP stand for a server and an app of the fleet). The compiler
53
+ * refuses a catalog operation the command line does not offer; the parity
54
+ * test parses each and checks it lands on that operation.
55
+ */
56
+ export const reaches = {
57
+ up: ["up", "SERVER"],
58
+ provision: ["provision", "SERVER"],
59
+ deploy: ["deploy", "SERVER"],
60
+ setup: ["setup", "SERVER"],
61
+ plan: ["plan", "SERVER"],
62
+ verify: ["verify", "SERVER"],
63
+ apps: ["apps", "SERVER"],
64
+ hosts: ["hosts", "SERVER"],
65
+ ssh: ["ssh", "SERVER"],
66
+ "ssh.exec": ["ssh", "SERVER", "--", "uptime"],
67
+ down: ["down", "SERVER"],
68
+ adopt: ["adopt", "SERVER"],
69
+ "backup.test": ["backup", "test", "SERVER"],
70
+ "app.check": ["app", "check", "."],
71
+ "app.purge": ["app", "purge", "SERVER", "APP"],
72
+ "app.runs": ["app", "runs", "SERVER", "APP"],
73
+ "app.log": ["app", "logs", "SERVER", "APP"],
74
+ "app.deploy": ["app", "deploy", "SERVER", "APP", "v1.2.0"],
75
+ "app.releases": ["app", "rollback", "SERVER", "APP"],
76
+ "app.rollback": ["app", "rollback", "SERVER", "APP", "0123abc"],
77
+ job: ["job", "SERVER", "gc"],
78
+ status: ["status"],
79
+ validate: ["validate"],
80
+ doctor: ["doctor"],
81
+ certs: ["certs", "shop.test", "www"],
82
+ // Optique's own: `kayra version`, `kayra --version`.
83
+ version: ["--version"],
84
+ };
@@ -0,0 +1,23 @@
1
+ import { styleText } from "node:util";
2
+ import { spans } from "../../core/text/spans.js";
3
+ import { escapes } from "./terminal.js";
4
+ const looks = {
5
+ ok: ["green"],
6
+ bad: ["red"],
7
+ warn: ["yellow"],
8
+ active: ["cyan"],
9
+ muted: ["dim"],
10
+ strong: ["bold"],
11
+ accent: ["magenta", "bold"],
12
+ };
13
+ export const paint = (text, colors, links = false) => spans(text)
14
+ .map((span) => {
15
+ if (typeof span === "string")
16
+ return span;
17
+ const { tone, href } = span;
18
+ const styled = colors && tone !== undefined
19
+ ? looks[tone].reduce((so, format) => styleText(format, so, { validateStream: false }), span.text)
20
+ : span.text;
21
+ return links && href !== undefined ? escapes.link(styled, href) : styled;
22
+ })
23
+ .join("");
@@ -2,22 +2,26 @@ import { command, constant, group, map, merge, multiple, object, option, optiona
2
2
  import { lineBreak, message, text, url } from "@optique/core/message";
3
3
  import { argument } from "@optique/core/primitives";
4
4
  import { choice, integer, string } from "@optique/core/valueparser";
5
- import { appNameParser, domainParser, serverNameParser, subdomainParser } from "./brand.js";
5
+ import { appNameParser, domainParser, serverNameParser, subdomainParser } from "./values.js";
6
+ import { operation } from "../../core/operations/catalog.js";
7
+ /** A command's one line, as the catalog says it: the same words in every client. */
8
+ // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message is readonly only at the top
9
+ const summary = (name) => message `${text(operation(name).summary)}`;
6
10
  /** Command lines, each with what it is for, aligned. Plain text: Optique folds an indent that stands alone before a command line. */
7
11
  const examples = (indent, rows) => {
8
12
  const width = Math.max(...rows.map(([line]) => line.length));
9
- return rows.flatMap(([line, what], index) => [...(index === 0 ? [] : [lineBreak()]), text(`${indent}${line.padEnd(width)} ${what}`)]);
13
+ return Object.freeze(rows.flatMap(([line, what], index) => Object.freeze([...(index === 0 ? [] : [lineBreak()]), text(`${indent}${line.padEnd(width)} ${what}`)])));
10
14
  };
11
15
  const docs = message `Docs: ${url("https://yunuseon.github.io/kayra/")}`;
12
16
  /** A command's examples; Optique shows a command's footer instead of the program's, so the docs follow. */
13
- const footer = (...rows) => [
17
+ const footer = (...rows) => Object.freeze([
14
18
  ...message `Examples:`,
15
19
  lineBreak(),
16
20
  ...examples(" ", rows),
17
21
  lineBreak(),
18
22
  lineBreak(),
19
23
  ...docs,
20
- ];
24
+ ]);
21
25
  const sections = ["On a server", "Apps on a server", "In an app's repository", "The whole fleet", "Options", "Help"];
22
26
  /** Arguments (the untitled section) first, then the sections in the order above. */
23
27
  const sectionOrder = (a, b) => sections.indexOf(a.title ?? "") - sections.indexOf(b.title ?? "");
@@ -28,7 +32,7 @@ const usageLine = [
28
32
  { type: "optional", terms: [{ type: "option", names: ["-v", "--verbose"] }] },
29
33
  ];
30
34
  /** How kayra presents itself: help in sections, examples, the docs; errors without the full usage above them. */
31
- export const runOptions = (version) => ({
35
+ export const runOptions = (version) => Object.freeze(({
32
36
  programName: "kayra",
33
37
  // `kayra help deploy` and `kayra version` work too; listed once, as options.
34
38
  help: { option: { names: ["-h", "--help"], group: "Help" }, command: { hidden: "doc" } },
@@ -53,7 +57,7 @@ export const runOptions = (version) => ({
53
57
  termWidth: "auto",
54
58
  showChoices: true,
55
59
  aboveError: "none",
56
- });
60
+ }));
57
61
  /** The arguments kayra takes; server names are the fleet's, so they complete and are checked while parsing. */
58
62
  export const parser = (fleet) => {
59
63
  const [first, ...rest] = fleet.servers.map((each) => each.name);
@@ -63,55 +67,55 @@ export const parser = (fleet) => {
63
67
  const app = argument(appNameParser, { description: message `An app in the server's server.yml.` });
64
68
  // eslint-disable-next-line functional/prefer-immutable-types -- Optique's Message is readonly only at the top
65
69
  const onServer = (name, brief, more = {}) => command(name, object({ name: constant(name), server }), { brief, ...more });
66
- return merge(group("Options", object({
70
+ return Object.freeze(merge(group("Options", object({
67
71
  dryRun: option("--dry-run", { description: message `Print the plan instead of running it.` }),
68
72
  verbose: option("-v", "--verbose", {
69
73
  description: message `Ansible's own output (with -v) instead of kayra's summary.`,
70
74
  }),
71
- })), map(or(group("On a server", or(onServer("up", message `Provision, set up everything, point /etc/hosts at it.`, {
75
+ })), map(or(group("On a server", or(onServer("up", summary("up"), {
72
76
  description: message `Runs provision, then deploy (setup, apps, verify), then hosts: each part is a command of its own, and a failure names the one to run again.`,
73
77
  footer: footer(["kayra up shop-test", "a test server from nothing"]),
74
- }), onServer("provision", message `Create or update the machine (target home: build the image to import).`), onServer("deploy", message `Host setup and every app, no provisioning.`, {
78
+ }), onServer("provision", summary("provision")), onServer("deploy", summary("deploy"), {
75
79
  description: message `Runs setup, then apps; a platform server is verified at the end, so a deploy that leaves it broken fails. Hetzner and home servers change only from a clean main equal to its remote, with the kayra the fleet pins.`,
76
80
  footer: footer(["kayra deploy shop-prod", "after a new kayra or a fleet change"], ["kayra deploy shop-prod --dry-run", "every step, its command and environment"], ["kayra deploy shop-prod -v", "with Ansible's own output"]),
77
- }), onServer("setup", message `The host layer only: the playbook for the server's kind.`, {
81
+ }), onServer("setup", summary("setup"), {
78
82
  footer: footer(["kayra setup shop-prod", "after a change to vars.yml or secrets.yml"], ["kayra setup shop-prod -v", "with Ansible's own output"]),
79
- }), onServer("plan", message `What provision and setup would change, changing nothing (OpenTofu plan, Ansible check mode).`, {
83
+ }), onServer("plan", summary("plan"), {
80
84
  description: message `OpenTofu's plan, then the playbook in check mode with diffs; files holding secrets only say that they would change. Works from any branch: it previews this checkout against the server.`,
81
85
  footer: footer(["kayra plan shop-prod", "what merging this branch would change on it"]),
82
- }), onServer("verify", message `Whether a platform server works as its users see it: logins, certificates, webhooks, apps, runs, alerts.`, {
86
+ }), onServer("verify", summary("verify"), {
83
87
  description: message `Run by deploy and up at the end. The probes retry for VERIFY_WAIT seconds (150), for certificates still coming.`,
84
- }), onServer("apps", message `Make the server's apps match server.yml: register each, remove the rest (data kept).`, {
88
+ }), onServer("apps", summary("apps"), {
85
89
  footer: footer(["kayra apps shop-prod", "after a change to apps/*.yml"]),
86
- }), onServer("hosts", message `Point the domain at a multipass VM in /etc/hosts (sudo).`), command("ssh", object({
90
+ }), onServer("hosts", summary("hosts")), command("ssh", object({
87
91
  name: constant("ssh"),
88
92
  server,
89
93
  remote: multiple(argument(string({ metavar: "COMMAND" }), { description: message `A command to run there instead of a shell.` })),
90
94
  }), {
91
95
  brief: message `SSH into the server, or run a command there (after --).`,
92
96
  footer: footer(["kayra ssh shop-test", "a shell"], ["kayra ssh shop-test -- df -h /", "one command"]),
93
- }), onServer("down", message `Destroy the machine.`, {
97
+ }), onServer("down", summary("down"), {
94
98
  description: message `OpenTofu destroy; on a Hetzner server only once its name is typed.`,
95
- }), onServer("adopt", message `Once, for a server we did not create: add the deploy user as root.`), command("backup", command("test", object({ name: constant("backup test"), server })), {
96
- brief: message `Restore the latest backup to a scratch dir, check it, delete it.`,
99
+ }), onServer("adopt", summary("adopt")), command("backup", command("test", object({ name: constant("backup test"), server })), {
100
+ brief: summary("backup.test"),
97
101
  footer: footer(["kayra backup test nas", "started on the server, followed over SSH"]),
98
102
  }))), group("Apps on a server", or(command("app", or(group("In an app's repository", command("check", object({
99
103
  name: constant("app check"),
100
104
  dir: optional(argument(string({ metavar: "DIR" }), { description: message `The app's repository; the current directory by default.` })),
101
105
  }), {
102
- brief: message `What the platform checks at deploy (app.yml, images, compose policy). No fleet needed.`,
106
+ brief: summary("app.check"),
103
107
  footer: footer(["kayra app check", "in the app's repository, before a push"]),
104
108
  })), group("On a server", or(command("purge", object({ name: constant("app purge"), server, app }), {
105
- brief: message `Delete a removed app's volumes: its data, irreversibly.`,
109
+ brief: summary("app.purge"),
106
110
  }), command("runs", object({ name: constant("app runs"), server, app }), {
107
- brief: message `What runs now, and the app's latest runs: state, commit, why, when, how long.`,
111
+ brief: summary("app.runs"),
108
112
  }), command("logs", object({
109
113
  name: constant("app logs"),
110
114
  server,
111
115
  app,
112
116
  more: optional(argument(string({ metavar: "RUN" }), { description: message `A run's id from app runs; the newest by default.` })),
113
117
  }), {
114
- brief: message `A run's log, the newest unless named.`,
118
+ brief: summary("app.log"),
115
119
  footer: footer(["kayra app logs shop-prod shop", "the newest run's log"]),
116
120
  }), command("deploy", object({
117
121
  name: constant("app deploy"),
@@ -119,7 +123,7 @@ export const parser = (fleet) => {
119
123
  app,
120
124
  more: optional(argument(string({ metavar: "REF" }), { description: message `A branch, tag or commit; the app's ref by default.` })),
121
125
  }), {
122
- brief: message `Build and deploy a branch, tag or commit (default: the app's ref).`,
126
+ brief: summary("app.deploy"),
123
127
  footer: footer(["kayra app deploy shop-prod shop v1.2.0", "a tag, now"]),
124
128
  }), command("rollback", object({
125
129
  name: constant("app rollback"),
@@ -137,38 +141,40 @@ export const parser = (fleet) => {
137
141
  }),
138
142
  noPrs: option("--no-prs", { description: message `Renovate: log what would change, open no PRs.` }),
139
143
  }), {
140
- brief: message `Run a platform job now: the registry GC or Renovate.`,
144
+ brief: summary("job"),
141
145
  footer: footer(["kayra job shop-prod renovate --no-prs", "what Renovate would change, no PRs"]),
142
146
  }))), group("The whole fleet", or(command("status", object({
143
147
  name: constant("status"),
144
148
  json: option("--json", { description: message `The table as JSON on stdout, nothing on stderr.` }),
145
149
  offline: option("--offline", { description: message `Only what the fleet and OpenTofu's state say: reach no server.` }),
146
150
  }), {
147
- brief: message `Every server: where it is, whether SSH and its login answer.`,
151
+ brief: summary("status"),
148
152
  footer: footer(["kayra status", "every server, asked now"], ["kayra status --offline --json", "the fleet's own view, for a program"]),
149
153
  }), command("validate", object({
150
154
  name: constant("validate"),
151
155
  server: optional(server),
152
156
  json: option("--json", { description: message `The findings as JSON on stdout, nothing on stderr.` }),
153
157
  }), {
154
- brief: message `Check the fleet beyond its schemas: secrets, apps against their contract, stacks, routes.`,
158
+ brief: summary("validate"),
155
159
  footer: footer(["kayra validate", "every server"], ["kayra validate shop-prod", "one"]),
156
160
  }), command("doctor", object({ name: constant("doctor") }), {
157
- brief: message `Check that this Mac can run every command on every server.`,
158
- }), command("ui", object({
159
- name: constant("ui"),
161
+ brief: summary("doctor"),
162
+ }), command("serve", object({
163
+ name: constant("serve"),
164
+ ui: option("--ui", { description: message `Serve the browser interface (the default unless --api alone).` }),
165
+ api: option("--api", { description: message `Allow local programs to use a bearer token; write .cache/serve.json.` }),
160
166
  port: withDefault(option("--port", integer({ min: 0, max: 65_535, metavar: "PORT" }), { description: message `Listen on this port (default: any free one).` }), 0),
161
167
  noOpen: option("--no-open", { description: message `Print the URL, open no browser.` }),
162
168
  }), {
163
- brief: message `The web interface on this Mac: the fleet, its servers and apps, every command with its steps live.`,
169
+ brief: message `The local browser interface and API: the fleet, its servers and apps, every command with its steps live.`,
164
170
  description: message `Listens on 127.0.0.1 only. The URL it prints carries this launch's token; nothing else gets in. Runs the same plans as the command line, with the same guards; a change to a real server asks for its name first.`,
165
- footer: footer(["kayra ui", "open it in the browser"], ["kayra ui --port 7700 --no-open", "for web/'s dev server"]),
171
+ footer: footer(["kayra serve", "open it in the browser"], ["kayra serve --port 7700 --no-open", "for web/'s dev server"]),
166
172
  }), command("certs", object({
167
173
  name: constant("certs"),
168
174
  domain: argument(domainParser, { description: message `The domain the certificates are for.` }),
169
175
  subdomains: multiple(argument(subdomainParser, { description: message `Its subdomains, each with a certificate.` })),
170
176
  }), {
171
- brief: message `mkcert certs for a domain and its subdomains (local dev, multipass).`,
177
+ brief: summary("certs"),
172
178
  footer: footer(["kayra certs shop.test www api", "into the fleet's .cache/certs"]),
173
- })))), (chosen) => ({ command: chosen })));
179
+ })))), (chosen) => ({ command: chosen }))));
174
180
  };