@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.
Files changed (57) hide show
  1. package/README.md +4 -0
  2. package/agent/skills/kayra-release/SKILL.md +8 -0
  3. package/cli/dist/browser/assets/index-9a-SE2rU.js +7 -0
  4. package/cli/dist/{web/assets/index-3W_NFATj.css → browser/assets/index-Ct0Eudk4.css} +1 -1
  5. package/cli/dist/browser/assets/xterm-CerOhKYV.js +16 -0
  6. package/cli/dist/{web → browser}/index.html +2 -2
  7. package/cli/dist/clients/api/api.js +269 -0
  8. package/cli/dist/clients/api/auth.js +36 -0
  9. package/cli/dist/clients/api/commands.js +27 -0
  10. package/cli/dist/clients/api/contract.gen.js +1 -0
  11. package/cli/dist/clients/api/contract.js +89 -0
  12. package/cli/dist/clients/api/directories.js +20 -0
  13. package/cli/dist/clients/api/discovery.js +38 -0
  14. package/cli/dist/clients/api/protocol.js +61 -0
  15. package/cli/dist/clients/api/queries.js +20 -0
  16. package/cli/dist/clients/api/runs.js +51 -0
  17. package/cli/dist/{ui → clients/cli}/explain.js +5 -5
  18. package/cli/dist/clients/cli/framed.js +64 -0
  19. package/cli/dist/clients/cli/invocation.js +83 -0
  20. package/cli/dist/clients/cli/paint.js +23 -0
  21. package/cli/dist/{cli.js → clients/cli/parser.js} +31 -25
  22. package/cli/dist/clients/cli/questions.js +88 -0
  23. package/cli/dist/{ui → clients/cli}/terminal.js +1 -13
  24. package/cli/dist/clients/ui/assets.js +36 -0
  25. package/cli/dist/clients/ui/opener.js +9 -0
  26. package/cli/dist/{brand.js → core/brand.js} +1 -1
  27. package/cli/dist/{commands → core/commands}/app-check.js +1 -1
  28. package/cli/dist/{commands → core/commands}/server.js +26 -17
  29. package/cli/dist/{commands → core/commands}/status.js +3 -3
  30. package/cli/dist/{commands → core/commands}/validate.js +1 -1
  31. package/cli/dist/{fleet.js → core/fleet.js} +1 -1
  32. package/cli/dist/core/interpret.js +276 -0
  33. package/cli/dist/{load.js → core/load.js} +1 -1
  34. package/cli/dist/core/operations/catalog.js +152 -0
  35. package/cli/dist/core/operations/run.js +139 -0
  36. package/cli/dist/{plan.js → core/plan.js} +11 -4
  37. package/cli/dist/core/present/line.js +17 -0
  38. package/cli/dist/{ui → core/present}/progress.js +2 -61
  39. package/cli/dist/{schemas.js → core/schemas.js} +1 -1
  40. package/cli/dist/core/updates.js +13 -0
  41. package/cli/dist/{validate.js → core/validate.js} +1 -1
  42. package/cli/dist/main.js +92 -93
  43. package/cli/dist/serve.js +77 -0
  44. package/package.json +4 -3
  45. package/scripts/agent/guard.sh +9 -2
  46. package/scripts/local/packed-runs.sh +43 -0
  47. package/scripts/local/setup-hosts.sh +9 -2
  48. package/cli/dist/commands/index.js +0 -52
  49. package/cli/dist/interpret.js +0 -141
  50. package/cli/dist/ui/line.js +0 -39
  51. package/cli/dist/web/assets/index-DRFX9Q77.js +0 -2
  52. /package/cli/dist/{commands → core/commands}/doctor.js +0 -0
  53. /package/cli/dist/{gather.js → core/gather.js} +0 -0
  54. /package/cli/dist/{net.js → core/net.js} +0 -0
  55. /package/cli/dist/{ui → core/present}/text.js +0 -0
  56. /package/cli/dist/{ui → core/present}/views.js +0 -0
  57. /package/cli/dist/{settings.js → core/settings.js} +0 -0
@@ -1,8 +1,8 @@
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";
4
- import { wrap } from "./text.js";
5
- import { drawnAs } from "./views.js";
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";
6
6
  const kinds = { guard: warn, check: active, run: active, confirm: bad, note: muted };
7
7
  const tag = (step) => {
8
8
  const kind = kindOf(step);
@@ -0,0 +1,64 @@
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";
5
+ import { paint } from "./paint.js";
6
+ import { escapes, spinner } from "./terminal.js";
7
+ /** A run of this long earns a notification when it ends: the operator has looked away. */
8
+ const worthNotifying = 30_000;
9
+ /** 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. */
10
+ export const framed = (screen, write, invocation) => {
11
+ const columns = Math.min(screen.columns, 80);
12
+ const say = (text) => {
13
+ write(`${paint(text, screen.colors)}\n`);
14
+ };
15
+ const tell = (raw, when) => {
16
+ if (when)
17
+ write(raw);
18
+ };
19
+ return {
20
+ plan: async (plan, work) => {
21
+ const started = performance.now();
22
+ tell(escapes.pushTitle + escapes.title(invocation.command), screen.title);
23
+ say([strong(invocation.command), muted([...invocation.about, steps(plan)].map((each) => ` · ${each}`).join(""))]);
24
+ say("");
25
+ const ended = await work();
26
+ const ms = performance.now() - started;
27
+ say("");
28
+ footer(invocation, plan, ended, ms).forEach(say);
29
+ tell(escapes.popTitle, screen.title);
30
+ tell(escapes.progressDone, screen.progressBar);
31
+ const failed = ended.failures > 0 || ended.stop?.why === "failed";
32
+ tell(escapes.notify(`${invocation.command} ${failed ? "failed" : "is done"} after ${duration(ms)}`), screen.notifications && ms >= worthNotifying);
33
+ return ended;
34
+ },
35
+ step: async (step, at, work) => {
36
+ if (step.kind === "confirm" || step.kind === "note")
37
+ return work();
38
+ if (at.opens !== undefined) {
39
+ if (at.index > 0)
40
+ say("");
41
+ say([accent(at.opens)]);
42
+ }
43
+ const title = titleOf(step);
44
+ const counter = `${String(at.index + 1)}/${String(at.total)}`;
45
+ tell(escapes.title(`${invocation.command} · ${counter} ${title}`), screen.title);
46
+ tell(escapes.progress((at.index / at.total) * 100), screen.progressBar);
47
+ const shown = step.kind === "run" && step.stdout === "show";
48
+ if (shown)
49
+ say(spread([" ", active("◆"), " ", strong(title)], [muted(counter)], columns));
50
+ const stop = !shown && screen.live
51
+ ? spinner(write, (frame, ms) => paint(spread(truncate([" ", active(frame), " ", title], columns - 8), [muted(duration(ms))], columns), screen.colors))
52
+ : () => undefined;
53
+ const started = performance.now();
54
+ const done = await work();
55
+ stop();
56
+ // A diagnosis reports itself on stdout: that line is doctor's output.
57
+ if (step.kind === "check" && step.onFailure === "continue")
58
+ return done;
59
+ const took = duration(performance.now() - started);
60
+ say(spread([" ", done.failed ? bad("✗") : ok("✓"), " ", title], [muted(done.why === undefined ? took : `${done.why} · ${took}`)], columns));
61
+ return done;
62
+ },
63
+ };
64
+ };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The parsed command line as the operation it names. `app rollback` without a
3
+ * commit lists the releases (`app.releases`), with one it rolls back.
4
+ */
5
+ export const fromCommand = (command) => {
6
+ const plainly = (invocation) => ({ invocation, json: false });
7
+ switch (command.name) {
8
+ case "up":
9
+ case "provision":
10
+ case "deploy":
11
+ case "setup":
12
+ case "plan":
13
+ case "verify":
14
+ case "apps":
15
+ case "hosts":
16
+ case "down":
17
+ case "adopt":
18
+ return plainly({ name: command.name, input: { server: command.server } });
19
+ case "backup test":
20
+ return plainly({ name: "backup.test", input: { server: command.server } });
21
+ case "ssh":
22
+ return plainly(command.remote.length === 0 ? { name: "ssh", input: { server: command.server } } : { name: "ssh.exec", input: { server: command.server, command: command.remote } });
23
+ case "app check":
24
+ return plainly({ name: "app.check", input: { dir: command.dir ?? "." } });
25
+ case "app purge":
26
+ return plainly({ name: "app.purge", input: { server: command.server, app: command.app } });
27
+ case "app runs":
28
+ return plainly({ name: "app.runs", input: { server: command.server, app: command.app } });
29
+ case "app logs":
30
+ return plainly({ name: "app.log", input: { server: command.server, app: command.app, ...(command.more === undefined ? {} : { run: command.more }) } });
31
+ case "app deploy":
32
+ return plainly({ name: "app.deploy", input: { server: command.server, app: command.app, ...(command.more === undefined ? {} : { ref: command.more }) } });
33
+ case "app rollback":
34
+ return plainly(command.more === undefined
35
+ ? { name: "app.releases", input: { server: command.server, app: command.app } }
36
+ : { name: "app.rollback", input: { server: command.server, app: command.app, sha: command.more } });
37
+ case "job":
38
+ return plainly({ name: "job", input: { server: command.server, job: command.job, noPrs: command.noPrs } });
39
+ case "status":
40
+ return { invocation: { name: "status", input: { offline: command.offline } }, json: command.json };
41
+ case "validate":
42
+ return { invocation: { name: "validate", input: command.server === undefined ? {} : { server: command.server } }, json: command.json };
43
+ case "doctor":
44
+ return plainly({ name: "doctor", input: {} });
45
+ case "certs":
46
+ return plainly({ name: "certs", input: { domain: command.domain, subdomains: command.subdomains } });
47
+ }
48
+ };
49
+ /**
50
+ * How the command line reaches each operation: a sample argument list
51
+ * (SERVER and APP stand for a server and an app of the fleet). The compiler
52
+ * refuses a catalog operation the command line does not offer; the parity
53
+ * test parses each and checks it lands on that operation.
54
+ */
55
+ export const reaches = {
56
+ up: ["up", "SERVER"],
57
+ provision: ["provision", "SERVER"],
58
+ deploy: ["deploy", "SERVER"],
59
+ setup: ["setup", "SERVER"],
60
+ plan: ["plan", "SERVER"],
61
+ verify: ["verify", "SERVER"],
62
+ apps: ["apps", "SERVER"],
63
+ hosts: ["hosts", "SERVER"],
64
+ ssh: ["ssh", "SERVER"],
65
+ "ssh.exec": ["ssh", "SERVER", "--", "uptime"],
66
+ down: ["down", "SERVER"],
67
+ adopt: ["adopt", "SERVER"],
68
+ "backup.test": ["backup", "test", "SERVER"],
69
+ "app.check": ["app", "check", "."],
70
+ "app.purge": ["app", "purge", "SERVER", "APP"],
71
+ "app.runs": ["app", "runs", "SERVER", "APP"],
72
+ "app.log": ["app", "logs", "SERVER", "APP"],
73
+ "app.deploy": ["app", "deploy", "SERVER", "APP", "v1.2.0"],
74
+ "app.releases": ["app", "rollback", "SERVER", "APP"],
75
+ "app.rollback": ["app", "rollback", "SERVER", "APP", "0123abc"],
76
+ job: ["job", "SERVER", "gc"],
77
+ status: ["status"],
78
+ validate: ["validate"],
79
+ doctor: ["doctor"],
80
+ certs: ["certs", "shop.test", "www"],
81
+ // Optique's own: `kayra version`, `kayra --version`.
82
+ version: ["--version"],
83
+ };
@@ -0,0 +1,23 @@
1
+ import { styleText } from "node:util";
2
+ import { spans } from "../../core/present/line.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,7 +2,11 @@ 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 "../../core/brand.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));
@@ -68,50 +72,50 @@ export const parser = (fleet) => {
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
179
  })))), (chosen) => ({ command: chosen })));
174
180
  };
@@ -0,0 +1,88 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ /** The command line's questions: secret typing stays unseen, piped answers keep their order. */
3
+ export const questions = (render) => {
4
+ // eslint-disable-next-line functional/prefer-immutable-types -- resources belong to this reader and close with the plan
5
+ const reading = {};
6
+ const piped = async () => {
7
+ if (reading.lines === undefined) {
8
+ const terminal = createInterface({ input: process.stdin });
9
+ // eslint-disable-next-line functional/immutable-data -- keep buffered lines across questions
10
+ reading.lines = terminal[Symbol.asyncIterator]();
11
+ // eslint-disable-next-line functional/immutable-data -- release stdin when the plan ends
12
+ reading.close = () => { terminal.close(); };
13
+ }
14
+ const next = await reading.lines.next();
15
+ return next.done === true ? "" : next.value;
16
+ };
17
+ const typed = (prompt, secret) => {
18
+ const { stdin } = process;
19
+ if (!secret) {
20
+ const terminal = createInterface({ input: stdin, output: process.stderr });
21
+ return new Promise((resolve) => {
22
+ const done = (answer) => {
23
+ resolve(answer);
24
+ terminal.close();
25
+ };
26
+ // eslint-disable-next-line functional/immutable-data -- cancellation closes the outstanding question
27
+ reading.close = () => { done(""); };
28
+ terminal.once("SIGINT", () => { done(""); });
29
+ terminal.once("close", () => { resolve(""); });
30
+ void terminal.question(prompt).then(done, () => { done(""); });
31
+ });
32
+ }
33
+ const wasRaw = stdin.isRaw;
34
+ stdin.setRawMode(true);
35
+ stdin.setEncoding("utf8");
36
+ stdin.resume();
37
+ return new Promise((resolve) => {
38
+ // eslint-disable-next-line functional/prefer-immutable-types -- typed characters until Enter or cancellation
39
+ const state = { text: "", ended: false };
40
+ const done = (answer) => {
41
+ if (state.ended)
42
+ return;
43
+ // eslint-disable-next-line functional/immutable-data -- finish once, even when a paste includes several lines
44
+ state.ended = true;
45
+ stdin.removeListener("data", key);
46
+ stdin.removeListener("end", ended);
47
+ stdin.setRawMode(wasRaw);
48
+ stdin.pause();
49
+ process.stderr.write("\n");
50
+ resolve(answer);
51
+ };
52
+ const ended = () => { done(""); };
53
+ const key = (chunk) => {
54
+ Array.from(chunk).forEach((char) => {
55
+ if (state.ended)
56
+ return;
57
+ if (char === "\r" || char === "\n")
58
+ done(state.text);
59
+ else if (char === "\u0003" || char === "\u0004")
60
+ done("");
61
+ else if (char === "\u007f" || char === "\b") {
62
+ // eslint-disable-next-line functional/immutable-data -- remove one Unicode character
63
+ state.text = Array.from(state.text).slice(0, -1).join("");
64
+ }
65
+ else {
66
+ // eslint-disable-next-line functional/immutable-data -- append a typed character
67
+ state.text += char;
68
+ }
69
+ });
70
+ };
71
+ // eslint-disable-next-line functional/immutable-data -- cancellation restores terminal mode
72
+ reading.close = ended;
73
+ stdin.on("data", key);
74
+ stdin.once("end", ended);
75
+ process.stderr.write(prompt);
76
+ });
77
+ };
78
+ return {
79
+ ask: async (question) => {
80
+ const prompt = render(question.text);
81
+ if (process.stdin.isTTY)
82
+ return typed(prompt, question.kind === "secret");
83
+ process.stderr.write(prompt);
84
+ return piped();
85
+ },
86
+ close: () => { reading.close?.(); },
87
+ };
88
+ };
@@ -59,6 +59,7 @@ export const spinner = (write, draw) => {
59
59
  write(escapes.clearLine);
60
60
  };
61
61
  };
62
+ /** A state change, as an answer brings it. */
62
63
  const tick = (ms) => new Promise((resolve) => {
63
64
  setTimeout(() => {
64
65
  resolve(undefined);
@@ -89,16 +90,3 @@ export const watch = async (write, initial, updates, draw) => {
89
90
  };
90
91
  return go(initial, updates.map((update, id) => ({ id, landed: update.then((done) => ({ id, update: done })) })), 0);
91
92
  };
92
- /** What watch() returns, drawn nowhere: for a stream that is no terminal. */
93
- export const settle = async (initial, updates) => (await Promise.all(updates)).reduce((state, update) => update(state), initial);
94
- /** Each state as the updates land, in the order they land: for a viewer elsewhere (the web interface). */
95
- export const follow = async (initial, updates, each) => {
96
- const go = async (state, waiting) => {
97
- each(state);
98
- if (waiting.length === 0)
99
- return state;
100
- const next = await Promise.race(waiting.map((one) => one.landed));
101
- return go(next.update(state), waiting.filter((one) => one.id !== next.id));
102
- };
103
- return go(initial, updates.map((update, id) => ({ id, landed: update.then((done) => ({ id, update: done })) })));
104
- };
@@ -0,0 +1,36 @@
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { extname, join, normalize, sep } from "node:path";
3
+ const types = {
4
+ ".html": "text/html; charset=utf-8",
5
+ ".js": "text/javascript; charset=utf-8",
6
+ ".css": "text/css; charset=utf-8",
7
+ ".svg": "image/svg+xml",
8
+ ".png": "image/png",
9
+ ".ico": "image/x-icon",
10
+ ".woff2": "font/woff2",
11
+ ".json": "application/json; charset=utf-8",
12
+ };
13
+ const unbuilt = `<!doctype html><meta charset="utf-8"><title>kayra</title>
14
+ <body style="font:15px system-ui;margin:3rem auto;max-width:40rem"><h1>kayra</h1>
15
+ <p>The browser side is not built in this checkout:</p><pre>npm --prefix web ci &amp;&amp; npm --prefix web run build</pre>
16
+ <p>The API is up at <code>/api/fleet</code>.</p></body>`;
17
+ /**
18
+ * The built browser side (web/dist in a checkout, cli/dist/browser in the
19
+ * package); a path that is no file is the app's own route, answered by its
20
+ * index; without a build, a page saying how to make one.
21
+ */
22
+ export const serveAsset = (assets, path, response) => {
23
+ if (assets === undefined) {
24
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
25
+ response.end(unbuilt);
26
+ return;
27
+ }
28
+ const file = normalize(join(assets, decodeURIComponent(path)));
29
+ const inside = file.startsWith(assets + sep) && existsSync(file) && statSync(file).isFile();
30
+ const chosen = inside ? file : join(assets, "index.html");
31
+ response.writeHead(200, {
32
+ "Content-Type": types[extname(chosen)] ?? "application/octet-stream",
33
+ "Cache-Control": chosen.includes(`${sep}assets${sep}`) ? "public, max-age=31536000, immutable" : "no-cache",
34
+ });
35
+ response.end(readFileSync(chosen));
36
+ };
@@ -0,0 +1,9 @@
1
+ import { spawn } from "node:child_process";
2
+ /** macOS's open, xdg-open elsewhere; a browser that does not start leaves the printed URL. */
3
+ export const systemBrowser = {
4
+ open: (url) => {
5
+ spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], { stdio: "ignore", detached: true })
6
+ .on("error", () => undefined)
7
+ .unref();
8
+ },
9
+ };
@@ -1,7 +1,7 @@
1
1
  import { text } from "@optique/core/message";
2
2
  import { homedir } from "node:os";
3
3
  import { isAbsolute, join, normalize } from "node:path";
4
- import { err, ok } from "./result.js";
4
+ import { err, ok } from "../result.js";
5
5
  export const serverName = (value) => /^[a-z0-9][a-z0-9-]*$/.test(value)
6
6
  ? ok(value)
7
7
  : err(`'${value}' is not a server name (lowercase letters, digits, dashes)`);
@@ -1,7 +1,7 @@
1
1
  import { appName, within } from "../brand.js";
2
2
  import { yamlOf } from "../fleet.js";
3
3
  import { run } from "../plan.js";
4
- import { err, flatMap, map } from "../result.js";
4
+ import { err, flatMap, map } from "../../result.js";
5
5
  import { appManifestSchema } from "../settings.js";
6
6
  import { checkShape } from "../validate.js";
7
7
  const mapError = (result, f) => result.ok ? result : err(f(result.error));
@@ -1,23 +1,32 @@
1
1
  import { within, } from "../brand.js";
2
2
  import { partOf, run } from "../plan.js";
3
- import { all, err, map, ok } from "../result.js";
3
+ import { all, err, map, ok } from "../../result.js";
4
4
  /** The local scripts that read the fleet's files find them here, not beside themselves. */
5
5
  const fleetEnv = ({ fleet }) => ({ FLEET_ROOT: fleet });
6
6
  const script = ({ kayra }, name) => within(kayra, "scripts", "local", name);
7
7
  const ansiblePath = ({ kayra }, ...segments) => within(kayra, "ansible", ...segments);
8
8
  const inventory = (server) => within(server.dir, "inventory.ini");
9
9
  const terraform = (server) => `-chdir=${within(server.dir, "terraform")}`;
10
- /** How Ansible gets the vault password: from a file, or by asking. */
11
- const vaultEnv = (server) => {
10
+ /**
11
+ * How Ansible gets the vault password: from the server's password file, or
12
+ * from kayra, which asks the operator once per run (Need "vault").
13
+ */
14
+ const vault = (server) => {
12
15
  switch (server.vault.kind) {
13
16
  case "file":
14
- return { ANSIBLE_VAULT_PASSWORD_FILE: server.vault.file };
17
+ return { env: { ANSIBLE_VAULT_PASSWORD_FILE: server.vault.file }, needs: [] };
15
18
  case "ask":
16
- return { ANSIBLE_ASK_VAULT_PASS: "True" };
19
+ return { env: {}, needs: [{ kind: "vault", server: server.name }] };
17
20
  case "none":
18
- return {};
21
+ return { env: {}, needs: [] };
19
22
  }
20
23
  };
24
+ const needing = (step, needs) => ({ ...step, needs });
25
+ /** The vault's environment, and its need where kayra must ask for the password. */
26
+ const vaulted = (step, server) => {
27
+ const { env, needs } = vault(server);
28
+ return { ...step, env: { ...env, ...step.env }, ...(needs.length === 0 ? {} : { needs }) };
29
+ };
21
30
  const ansibleEnv = (engine, env) => ({ ...env, ANSIBLE_CONFIG: ansiblePath(engine, "ansible.cfg") });
22
31
  /** --verbose: every playbook prints Ansible's own output, with -v, instead of kayra's summary of it (ansible.cfg's stdout_callback). */
23
32
  export const verbose = (plan) => plan.map((step) => step.kind === "run" && step.argv[0] === "ansible-playbook"
@@ -79,7 +88,7 @@ export const provision = (engine, server) => ok(partOf("provision", [
79
88
  : []),
80
89
  ]));
81
90
  /** The playbook for the server's kind, as setup runs it; plan adds check mode. */
82
- const hostPlaybook = (engine, server, extra = []) => run(`Host layer · ${server.kind}.yml${extra.includes("--check") ? ", check mode" : ""}`, [
91
+ const hostPlaybook = (engine, server, extra = []) => vaulted(run(`Host layer · ${server.kind}.yml${extra.includes("--check") ? ", check mode" : ""}`, [
83
92
  "ansible-playbook",
84
93
  "-i",
85
94
  inventory(server),
@@ -93,7 +102,7 @@ const hostPlaybook = (engine, server, extra = []) => run(`Host layer · ${server
93
102
  "-e",
94
103
  `target=${server.target}`,
95
104
  ...extra,
96
- ], ansibleEnv(engine, vaultEnv(server)));
105
+ ], ansibleEnv(engine, {})), server);
97
106
  /** The host layer: the playbook for the server's kind. */
98
107
  export const setup = (engine, server) => ok(partOf("setup", [
99
108
  fromMain(engine, server),
@@ -102,7 +111,7 @@ export const setup = (engine, server) => ok(partOf("setup", [
102
111
  ? [certs(engine, server.domain, [appSubdomains(engine, server), ...server.stackHosts])]
103
112
  : []),
104
113
  ...reachable(engine, server),
105
- collections(engine, vaultEnv(server)),
114
+ collections(engine, vault(server).env),
106
115
  hostPlaybook(engine, server),
107
116
  ]));
108
117
  /**
@@ -119,14 +128,14 @@ export const preview = (engine, server) => ok([
119
128
  run("OpenTofu plan", ["tofu", terraform(server), "plan", "-input=false", "-lock=false"]),
120
129
  ]
121
130
  : []),
122
- collections(engine, vaultEnv(server)),
131
+ collections(engine, vault(server).env),
123
132
  hostPlaybook(engine, server, ["--check", "--diff"]),
124
133
  { kind: "note", text: `kayra plan changed nothing on ${server.name}: the changed tasks above are what kayra setup would do.` },
125
134
  ]);
126
135
  /** Register every app in server.yml, then remove the rest (their data kept). */
127
136
  export const apps = (engine, server) => {
128
- const env = vaultEnv(server);
129
- const playbook = (title, name, ...extra) => run(title, ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", name), ...extra], ansibleEnv(engine, env));
137
+ const { env } = vault(server);
138
+ const playbook = (title, name, ...extra) => vaulted(run(title, ["ansible-playbook", "-i", inventory(server), ansiblePath(engine, "playbooks", name), ...extra], ansibleEnv(engine, {})), server);
130
139
  return ok(partOf("apps", [
131
140
  fromMain(engine, server),
132
141
  ...(server.kind === "platform"
@@ -143,13 +152,13 @@ export const apps = (engine, server) => {
143
152
  };
144
153
  export const hosts = (engine, server) => ok(partOf("hosts", server.target === "multipass"
145
154
  ? [
146
- run("/etc/hosts", [
155
+ needing(run("/etc/hosts", [
147
156
  "bash",
148
157
  script(engine, "setup-hosts.sh"),
149
158
  server.domain,
150
159
  { kind: "query", argv: ["tofu", terraform(server), "output", "-raw", "server_ip"], words: "one" },
151
160
  appSubdomains(engine, server),
152
- ]),
161
+ ]), [{ kind: "sudo" }])
153
162
  ]
154
163
  : [{ kind: "note", text: `hosts: ${server.target} uses real DNS, nothing to do.` }]));
155
164
  const sequence = (plans) => map(all(plans), (each) => each.flat());
@@ -212,7 +221,7 @@ export const backupTest = (engine, server) => {
212
221
  return err(`no inventory for '${server.name}' — provision it first.`);
213
222
  return ok([
214
223
  ...reachable(engine, server),
215
- run("Start the restore test", [
224
+ vaulted(run("Start the restore test", [
216
225
  "ansible",
217
226
  "servers",
218
227
  "-i",
@@ -224,7 +233,7 @@ export const backupTest = (engine, server) => {
224
233
  "ansible.builtin.command",
225
234
  "-a",
226
235
  `docker compose -f ${server.backupDir}/docker-compose.yml exec -d -T backup /etc/backup/restore-test.sh`,
227
- ], ansibleEnv(engine, vaultEnv(server))),
236
+ ], ansibleEnv(engine, {})), server),
228
237
  { kind: "note", text: "Following the restore test. Ctrl-C stops following, not the test." },
229
238
  run("Follow the restore test", [
230
239
  "ssh",
@@ -256,7 +265,7 @@ const sshTo = (server, remote) => server.inventory === undefined
256
265
  ...remote,
257
266
  ]);
258
267
  /** An interactive shell, or the remote command as ssh runs it (the remote shell reads it). */
259
- export const ssh = (server, remote) => map(sshTo(server, remote), (argv) => [run("SSH", argv)]);
268
+ export const ssh = (server, remote) => map(sshTo(server, remote), (argv) => [remote.length === 0 ? { ...run("SSH", argv), kind: "session" } : run("SSH", argv)]);
260
269
  /** What the deployer's ctl is asked, its title, and how its answer is shown: the lists as data kayra draws. */
261
270
  const ctlCall = (server, command) => {
262
271
  switch (command.kind) {