@yunuseon/kayra 0.17.2 → 0.19.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 (55) hide show
  1. package/README.md +2 -0
  2. package/agent/skills/kayra-rollout/SKILL.md +3 -2
  3. package/ansible/playbooks/edge.yml +5 -0
  4. package/ansible/playbooks/nas.yml +9 -1
  5. package/ansible/playbooks/platform.yml +8 -2
  6. package/ansible/roles/app/tasks/main.yml +11 -3
  7. package/ansible/roles/kayra-version/defaults/main.yml +5 -0
  8. package/ansible/roles/kayra-version/tasks/main.yml +18 -0
  9. package/ansible/roles/platform/tasks/main.yml +6 -4
  10. package/cli/dist/browser/assets/index-C4HCL022.js +7 -0
  11. package/cli/dist/browser/index.html +1 -1
  12. package/cli/dist/clients/api/api.js +6 -4
  13. package/cli/dist/clients/api/commands.js +0 -48
  14. package/cli/dist/clients/api/{contract.js → openapi.js} +2 -51
  15. package/cli/dist/clients/api/protocol.js +1 -66
  16. package/cli/dist/clients/api/start.js +1 -1
  17. package/cli/dist/clients/cli/parser.js +4 -0
  18. package/cli/dist/clients/cli/status.js +28 -7
  19. package/cli/dist/clients/mcp/run.js +69 -0
  20. package/cli/dist/clients/mcp/server.js +130 -0
  21. package/cli/dist/clients/mcp/tools.js +101 -0
  22. package/cli/dist/clients/wire/contract.js +53 -0
  23. package/cli/dist/clients/wire/schemas.js +68 -0
  24. package/cli/dist/clients/{api → wire}/status.js +7 -1
  25. package/cli/dist/clients/wire/words.js +48 -0
  26. package/cli/dist/core/adapters/network.js +20 -1
  27. package/cli/dist/core/fleet/brand.js +5 -0
  28. package/cli/dist/core/fleet/parse.js +10 -1
  29. package/cli/dist/core/fleet/settings.js +18 -3
  30. package/cli/dist/core/operations/dispatch.js +3 -3
  31. package/cli/dist/core/recipes/doctor.js +3 -3
  32. package/cli/dist/core/recipes/host.js +8 -3
  33. package/cli/dist/core/status/look.js +33 -13
  34. package/cli/dist/core/status/model.js +2 -0
  35. package/cli/dist/deployer/brand.js +5 -0
  36. package/cli/dist/deployer/build/builder.js +5 -0
  37. package/cli/dist/deployer/build/bundle.js +5 -0
  38. package/cli/dist/deployer/build/compose.js +21 -8
  39. package/cli/dist/deployer/build/routes.js +128 -0
  40. package/cli/dist/deployer/deployer.js +15 -13
  41. package/cli/dist/deployer/runs/queue.js +7 -0
  42. package/cli/dist/deployer/runs/run.js +14 -7
  43. package/cli/dist/main.js +11 -3
  44. package/package.json +3 -1
  45. package/schema/app.json +64 -8
  46. package/scripts/agent/guard.sh +28 -6
  47. package/scripts/local/app-check.sh +12 -9
  48. package/scripts/local/app-manifests.sh +11 -6
  49. package/scripts/local/verify.sh +22 -11
  50. package/scripts/platform/compose-policy.sh +37 -40
  51. package/cli/dist/browser/assets/index-hcyM6f6T.js +0 -7
  52. package/compose/traefik/dynamic/ratelimit.yml +0 -21
  53. /package/cli/dist/clients/{api → wire}/contract.gen.js +0 -0
  54. /package/cli/dist/clients/{api → wire}/queries.js +0 -0
  55. /package/cli/dist/clients/{api → wire}/validate.js +0 -0
@@ -46,8 +46,23 @@ const said = (reach, frame) => {
46
46
  };
47
47
  const sshCell = (reach, frame) => (reach.kind === "refused" ? typed([warn("off")]) : said(reach, frame));
48
48
  const httpsCell = (reach, frame, url) => Object.freeze(said(reach, frame).map((span, index) => (index === 0 && typeof span !== "string" ? link(span.text, url, span.tone) : span)));
49
- const headings = ["SERVER", "KIND", "TARGET", "DOMAIN", "ADDRESS", "SSH", "HTTPS", "APPS"];
50
- const probed = ["SSH", "HTTPS"];
49
+ /** The kayra that set the server up; where it is not the pin, the pin after it: what a setup would make it. */
50
+ const kayraCell = (running, pin, frame) => {
51
+ switch (running.kind) {
52
+ case "pending":
53
+ return waiting(frame, pin.length);
54
+ case "skipped":
55
+ return typed([muted("–")]);
56
+ case "recorded":
57
+ return running.version === pin ? typed([fine(running.version)]) : typed([warn(running.version), muted(` → ${pin}`)]);
58
+ case "unrecorded":
59
+ return typed([warn("unrecorded"), muted(` → ${pin}`)]);
60
+ case "unreadable":
61
+ return typed([bad("unreadable")]);
62
+ }
63
+ };
64
+ const headings = ["SERVER", "KIND", "TARGET", "DOMAIN", "ADDRESS", "SSH", "HTTPS", "KAYRA", "APPS"];
65
+ const probed = ["SSH", "HTTPS", "KAYRA"];
51
66
  const row = (look, frame) => {
52
67
  const { server } = look;
53
68
  return typed([
@@ -58,6 +73,7 @@ const row = (look, frame) => {
58
73
  machineCell(look.machine, frame),
59
74
  sshCell(look.ssh, frame),
60
75
  look.https === undefined ? [] : httpsCell(look.https, frame, authUrl(server)),
76
+ kayraCell(look.kayra, look.pin, frame),
61
77
  [server.apps.map((app) => app.name).join(", ")],
62
78
  ]);
63
79
  };
@@ -65,11 +81,16 @@ const row = (look, frame) => {
65
81
  export const statusView = (looks, drawing) => {
66
82
  const shown = headings.flatMap((heading, index) => (drawing.offline && probed.includes(heading) ? Object.freeze([]) : Object.freeze([index])));
67
83
  const rows = [headings.map((heading) => Object.freeze([muted(heading)])), ...looks.map((look) => row(look, drawing.frame))].map((cells) => Object.freeze(shown.map((index) => cells[index] ?? [])));
68
- const notes = looks.flatMap((look) => typed(look.machine.kind === "unreadable" ? [
69
- [" ", bad("✗"), " ", strong(look.server.name), `: OpenTofu's state could not be read: ${look.machine.reason}`],
70
- ...(look.machine.reason === "tofu init needed"
71
- ? [pointing(" ", `tofu -chdir=servers/${look.server.name}/terraform init`)]
84
+ const notes = looks.flatMap((look) => typed([
85
+ ...(look.machine.kind === "unreadable" ? [
86
+ typed([" ", bad("✗"), " ", strong(look.server.name), `: OpenTofu's state could not be read: ${look.machine.reason}`]),
87
+ ...(look.machine.reason === "tofu init needed"
88
+ ? [pointing(" ", `tofu -chdir=servers/${look.server.name}/terraform init`)]
89
+ : []),
90
+ ] : []),
91
+ ...(look.kayra.kind === "unreadable"
92
+ ? [typed([" ", bad("✗"), " ", strong(look.server.name), `: which kayra set it up could not be read: ${look.kayra.reason}`])]
72
93
  : []),
73
- ] : []));
94
+ ]));
74
95
  return typed([...table(fit(rows, drawing.room, [shown.length - 1, shown.indexOf(3)])), ...(notes.length === 0 ? [] : [[], ...notes])]);
75
96
  };
@@ -0,0 +1,69 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { reporting } from "../../core/interpreter/events.js";
3
+ import { interpret } from "../../core/interpreter/loop.js";
4
+ import { duration } from "../../core/text/time.js";
5
+ import { flat } from "../../core/text/spans.js";
6
+ import { typed } from "../../lib/typed.js";
7
+ /** A plan's confirmations, in order: what the operator was asked to type before it ran. */
8
+ export const confirmations = (plan) => Object.freeze(plan.flatMap((step, index) => (step.kind === "confirm" ? [{ key: `confirm-${String(index)}`, warning: step.warning, expect: step.expect }] : [])));
9
+ const secretNote = (question, server) => [
10
+ `kayra mcp passes no password, and this step needed one: ${flat(question).trim().replace(/^\?\s*/, "").replace(/:$/, "")}.`,
11
+ `Name a vault_password_file in ${server === undefined ? "the server's" : `servers/${server}/`}server.yml, have sudo's cached (sudo -v), or run the command in a terminal.`,
12
+ ].join(" ");
13
+ /** The run as text: the heading, each step with its output and how it went, the footer. */
14
+ const report = (told, about, bare) => {
15
+ const titles = told.flatMap((event) => (event.kind === "plan" ? event.steps.map((step) => step.title) : []));
16
+ const lines = told.flatMap((event) => {
17
+ switch (event.kind) {
18
+ case "plan":
19
+ return bare ? [] : [`${about.command} · ${about.about.join(" · ")}`];
20
+ case "started":
21
+ return bare ? [] : [`▸ ${titles[event.index] ?? ""}`];
22
+ case "output":
23
+ return [stripVTControlCharacters(event.chunk).replace(/\n$/, "")];
24
+ case "said":
25
+ return [flat(event.text)];
26
+ case "done":
27
+ return bare || (!event.failed && !event.stopped)
28
+ ? []
29
+ : [`${event.failed ? "✗" : "■"} ${titles[event.index] ?? ""}${event.why === undefined ? "" : ` · ${event.why}`} · ${duration(event.ms)}`];
30
+ case "ended":
31
+ return bare && event.failures === 0 && event.stop === undefined ? [] : event.footer.map(flat);
32
+ }
33
+ });
34
+ return lines.filter((line) => line !== "").join("\n");
35
+ };
36
+ /** Runs a plan with no terminal: every step's output piped and collected, questions answered from what was asked up front. */
37
+ export const run = async (plan, watching) => {
38
+ // eslint-disable-next-line functional/prefer-immutable-types -- the run's events, collected as they come
39
+ const told = [];
40
+ // eslint-disable-next-line functional/immutable-data -- see above
41
+ const tell = (event) => { told.push(event); };
42
+ const asked = { confirmations: 0 };
43
+ const total = plan.length;
44
+ const io = typed({
45
+ out: (text) => { tell({ kind: "said", text }); },
46
+ err: (text) => { tell({ kind: "said", text }); },
47
+ ask: (question) => {
48
+ if (question.kind === "secret") {
49
+ tell({ kind: "said", text: secretNote(question.text, watching.about.server) });
50
+ return Promise.resolve(undefined);
51
+ }
52
+ const answer = watching.typed[asked.confirmations];
53
+ // eslint-disable-next-line functional/immutable-data -- see above
54
+ asked.confirmations += 1;
55
+ return Promise.resolve(answer);
56
+ },
57
+ output: (chunk) => { tell({ kind: "output", chunk }); },
58
+ signal: watching.signal,
59
+ });
60
+ const progress = reporting((event) => {
61
+ tell(event);
62
+ if (event.kind === "started")
63
+ watching.began(event.index, total, told.flatMap((each) => (each.kind === "plan" ? [each.steps[event.index]?.title ?? ""] : []))[0] ?? "");
64
+ }, watching.about, watching.short);
65
+ await interpret(plan, io, progress);
66
+ // Stopped is not passed here, even when the operator declined: for an agent, what it asked for did not happen.
67
+ const passed = told.some((event) => event.kind === "ended" && event.failures === 0 && event.stop === undefined);
68
+ return { passed, text: report(told, watching.about, watching.bare) };
69
+ };
@@ -0,0 +1,130 @@
1
+ import { inputRequired, inputResponse, Server } from "@modelcontextprotocol/server";
2
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
+ import { heading } from "../../core/interpreter/events.js";
4
+ import { operation } from "../../core/operations/catalog.js";
5
+ import { hasPlan, invocation, isQuery, isStream, planOf, serverOf, stream } from "../../core/operations/dispatch.js";
6
+ import { render } from "../../core/plan/describe.js";
7
+ import { verbose } from "../../core/recipes/steps.js";
8
+ import { settle } from "../../core/status/updates.js";
9
+ import { answer } from "../wire/queries.js";
10
+ import { statusJson } from "../wire/status.js";
11
+ import { words } from "../wire/words.js";
12
+ import { confirmations, run } from "./run.js";
13
+ import { operationOf, runOptions, tools } from "./tools.js";
14
+ import { typed } from "../../lib/typed.js";
15
+ const said = (text, isError = false) => typed({ content: [{ type: "text", text }], ...(isError ? { isError } : {}) });
16
+ const answered = (value) => typed({
17
+ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }],
18
+ ...(typeof value === "object" && value !== null ? { structuredContent: value } : {}),
19
+ });
20
+ const instructions = (fleet) => [
21
+ "kayra runs a fleet of servers: provisioning, host setup, the apps on them, and their checks. These tools are its operations, as the kayra command line has them.",
22
+ "",
23
+ "The fleet's servers:",
24
+ ...fleet.servers.map((each) => `- ${each.name}: ${each.kind} on ${each.target}, ${each.domain}`),
25
+ "",
26
+ "- dryRun: true on a plan's tool lists its steps and runs nothing: use it before a change.",
27
+ "- A change to a server whose target is not multipass is approved by the operator first; down and app_purge every time, with the server's name typed.",
28
+ "- No password passes through here: a vaulted server needs vault_password_file in its server.yml.",
29
+ "- verify, plan, status and validate change nothing.",
30
+ ].join("\n").slice(0, 4000);
31
+ /** What the operator typed for each confirmation, or the request to ask them first. */
32
+ const confirmed = (asks, responses) => {
33
+ if (asks.length === 0)
34
+ return { typed: [] };
35
+ const views = asks.map((each) => inputResponse(responses, each.key));
36
+ if (views.every((view) => view.kind === "missing"))
37
+ return {
38
+ ask: inputRequired({
39
+ inputRequests: Object.fromEntries(asks.map((each) => [each.key, inputRequired.elicit({
40
+ message: `${each.warning}\nType ${each.expect} to confirm.`,
41
+ requestedSchema: { type: "object", properties: { typed: { type: "string", title: `Type ${each.expect}` } }, required: ["typed"] },
42
+ })])),
43
+ }),
44
+ };
45
+ return { typed: views.map((view) => (view.kind === "elicit" && view.action === "accept" && typeof view.content?.["typed"] === "string" ? view.content["typed"] : undefined)) };
46
+ };
47
+ const runPlan = async (mcp, busy, call, plan, asked) => {
48
+ const options = runOptions.parse({ dryRun: asked.arguments?.["dryRun"], verbose: asked.arguments?.["verbose"] });
49
+ const steps = options.verbose ? verbose(plan) : plan;
50
+ if (options.dryRun)
51
+ return said(render(steps).join("\n"));
52
+ const target = serverOf(mcp.context, call);
53
+ const changes = operation(call.name).effect !== "reads" && target !== undefined;
54
+ if (changes && busy.has(target.name))
55
+ return said(`a change on ${target.name} is still running: wait for it to end`, true);
56
+ const asks = confirmed(confirmations(steps), asked.responses);
57
+ if ("ask" in asks)
58
+ return asks.ask;
59
+ if (changes)
60
+ busy.add(target.name);
61
+ try {
62
+ const ran = await run(steps, {
63
+ about: heading(words(call), target, mcp.context.version),
64
+ short: mcp.short,
65
+ bare: operation(call.name).bare === true,
66
+ typed: asks.typed,
67
+ signal: asked.signal,
68
+ began: (index, total, title) => { void asked.progress(index, total, title); },
69
+ });
70
+ return said(ran.text, !ran.passed);
71
+ }
72
+ finally {
73
+ if (changes)
74
+ busy.delete(target.name);
75
+ }
76
+ };
77
+ /** One tools/call: the tool's operation, its input through the core's one gate, then by kind. */
78
+ const callTool = async (mcp, busy, asked) => {
79
+ const name = operationOf(asked.name);
80
+ if (name === undefined)
81
+ return said(`no such tool: ${asked.name}`, true);
82
+ const input = Object.fromEntries(Object.entries(asked.arguments ?? {}).filter(([key]) => !Object.hasOwn(runOptions.shape, key)));
83
+ const call = invocation(name, operation(name).kind === "plan" ? input : asked.arguments);
84
+ if (!call.ok)
85
+ return said(call.error, true);
86
+ const context = { ...mcp.context, signal: asked.signal };
87
+ if (isQuery(call.value)) {
88
+ const result = await answer(context, call.value.name, call.value.input);
89
+ return result.ok ? answered(result.value) : said(result.error, true);
90
+ }
91
+ if (isStream(call.value)) {
92
+ const { initial, updates } = stream(context, call.value.name, call.value.input);
93
+ return answered(statusJson(await settle(initial, updates)));
94
+ }
95
+ if (hasPlan(call.value)) {
96
+ const plan = planOf(context, call.value);
97
+ return plan.ok ? runPlan({ ...mcp, context }, busy, call.value, plan.value, asked) : said(plan.error, true);
98
+ }
99
+ return said(`${asked.name} is not offered here`, true);
100
+ };
101
+ /** The MCP server over the core: tools/list from the catalog, tools/call through invocation(). */
102
+ export const mcpServer = (mcp, busy) => {
103
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- the low-level server: tools/list and tools/call stay kayra's, through invocation()
104
+ const server = new Server({ name: "kayra", version: mcp.context.version }, { capabilities: { tools: {} }, instructions: instructions(mcp.context.fleet) });
105
+ server.setRequestHandler("tools/list", () => ({ tools: [...tools(mcp.context.fleet)] }));
106
+ server.setRequestHandler("tools/call", (request, ctx) => {
107
+ const token = request.params._meta?.progressToken;
108
+ return callTool(mcp, busy, {
109
+ name: request.params.name,
110
+ ...(request.params.arguments === undefined ? {} : { arguments: request.params.arguments }),
111
+ ...(token === undefined ? {} : { progressToken: token }),
112
+ ...(ctx.mcpReq.inputResponses === undefined ? {} : { responses: ctx.mcpReq.inputResponses }),
113
+ signal: ctx.mcpReq.signal,
114
+ progress: (progress, total, message) => token === undefined ? Promise.resolve() : ctx.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress, total, message } }),
115
+ });
116
+ });
117
+ return server;
118
+ };
119
+ /** kayra mcp: the server on this process's stdin and stdout, one change per server at a time. */
120
+ export const serveMcp = (mcp, onError) => {
121
+ const running = new Set();
122
+ const busy = {
123
+ has: (server) => running.has(server),
124
+ // eslint-disable-next-line functional/immutable-data -- the servers a change runs on now, shared by the connection's calls
125
+ add: (server) => { running.add(server); },
126
+ // eslint-disable-next-line functional/immutable-data -- see above
127
+ delete: (server) => { running.delete(server); },
128
+ };
129
+ return serveStdio(() => mcpServer(mcp, busy), { onerror: (error) => { onError(error.message); } });
130
+ };
@@ -0,0 +1,101 @@
1
+ import { z } from "zod";
2
+ import { operation, operationNames } from "../../core/operations/catalog.js";
3
+ import { querySchemas, schemas } from "../wire/schemas.js";
4
+ import { typed } from "../../lib/typed.js";
5
+ /**
6
+ * How MCP reaches each operation. The compiler refuses a catalog operation
7
+ * this table leaves out; a tool's name is the operation's, `.` spelled `_`
8
+ * (Claude's API takes no dots in a tool name).
9
+ */
10
+ export const reaches = {
11
+ up: { tool: "up" },
12
+ provision: { tool: "provision" },
13
+ deploy: { tool: "deploy" },
14
+ setup: { tool: "setup" },
15
+ plan: { tool: "plan" },
16
+ verify: { tool: "verify" },
17
+ apps: { tool: "apps" },
18
+ hosts: { tool: "hosts" },
19
+ ssh: { refused: "an interactive shell, which an agent cannot hold: ssh_exec runs a command" },
20
+ "ssh.exec": { tool: "ssh_exec" },
21
+ down: { tool: "down" },
22
+ adopt: { tool: "adopt" },
23
+ "backup.test": { tool: "backup_test" },
24
+ "app.check": { tool: "app_check" },
25
+ "app.purge": { tool: "app_purge" },
26
+ "app.runs": { tool: "app_runs" },
27
+ "app.log": { tool: "app_log" },
28
+ "app.deploy": { tool: "app_deploy" },
29
+ "app.releases": { tool: "app_releases" },
30
+ "app.rollback": { tool: "app_rollback" },
31
+ job: { tool: "job" },
32
+ status: { tool: "status" },
33
+ validate: { tool: "validate" },
34
+ doctor: { tool: "doctor" },
35
+ certs: { tool: "certs" },
36
+ version: { tool: "version" },
37
+ };
38
+ /** The operations offered as tools, by their tool's name. */
39
+ export const offered = Object.freeze(operationNames.flatMap((name) => {
40
+ const offer = reaches[name];
41
+ return "tool" in offer ? [[offer.tool, name]] : [];
42
+ }));
43
+ export const operationOf = (tool) => offered.find(([name]) => name === tool)?.[1];
44
+ /** What a plan's tool takes besides the operation's input. */
45
+ export const runOptions = z.strictObject({
46
+ dryRun: z.boolean().default(false).describe("List the plan's steps and run nothing"),
47
+ verbose: z.boolean().default(false).describe("Ansible's own output, as with -v"),
48
+ });
49
+ const effectSaid = (each) => {
50
+ if (each.effect === "reads")
51
+ return "Changes nothing.";
52
+ if (each.effect === "destroys")
53
+ return "Irreversible: the operator approves every call, and types the server's name before it runs.";
54
+ return each.scope === "fleet" || each.scope === "repo"
55
+ ? "Changes files on this machine."
56
+ : "Changes the server: on one that is not multipass, the operator approves it first.";
57
+ };
58
+ const kindSaid = (each) => each.kind === "plan" ? (each.bare === true ? " Its output is its answer." : " Runs a plan of steps; dryRun lists them and runs nothing.") : "";
59
+ const isSchema = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
60
+ /** A JSON Schema without its dialect: Claude Code reads it as draft 2020-12 either way. */
61
+ // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable, a class the rule cannot see into
62
+ const plain = (schema, io) => typed(Object.fromEntries(Object.entries(z.toJSONSchema(schema, { io })).filter(([key]) => key !== "$schema")));
63
+ const optionsSchema = plain(runOptions, "input");
64
+ /** A tool's schemas as MCP has them: an object at the root, its properties plain JSON. */
65
+ const objectSchema = z.looseObject({ type: z.literal("object"), properties: z.record(z.string(), z.json()).optional() });
66
+ /** The input's JSON Schema, with the fleet's servers as the only choices (the command line's choice()), and a plan's options. */
67
+ const inputSchema = (each, servers) => {
68
+ const base = plain(each.input, "input");
69
+ const properties = {
70
+ ...(isSchema(base["properties"]) ? base["properties"] : {}),
71
+ ...(each.kind === "plan" && isSchema(optionsSchema["properties"]) ? optionsSchema["properties"] : {}),
72
+ };
73
+ const server = properties["server"];
74
+ return objectSchema.parse({ ...base, properties: isSchema(server) && servers.length > 0 ? { ...properties, server: { ...server, enum: servers } } : properties });
75
+ };
76
+ const isQueryName = (name) => Object.hasOwn(querySchemas, name);
77
+ /** An answer's schema, where it is an object: MCP's structured content is one. */
78
+ const outputSchema = (name) => {
79
+ const schema = name === "status" ? schemas.Status : isQueryName(name) ? querySchemas[name] : undefined;
80
+ if (schema === undefined)
81
+ return undefined;
82
+ const json = objectSchema.safeParse(plain(schema, "output"));
83
+ return json.success ? json.data : undefined;
84
+ };
85
+ /** Every tool, as tools/list answers. */
86
+ export const tools = (fleet) => {
87
+ const servers = fleet.servers.map((each) => each.name);
88
+ return Object.freeze(offered.map(([tool, name]) => {
89
+ const each = operation(name);
90
+ const output = outputSchema(name);
91
+ return {
92
+ name: tool,
93
+ title: each.summary,
94
+ description: `${each.summary} ${effectSaid(each)}${kindSaid(each)}`,
95
+ inputSchema: inputSchema(each, servers),
96
+ ...(output === undefined ? {} : { outputSchema: output }),
97
+ annotations: { readOnlyHint: each.effect === "reads", destructiveHint: each.effect === "destroys", openWorldHint: each.scope !== "repo" },
98
+ ...(each.effect === "destroys" ? { _meta: { "anthropic/requiresUserInteraction": true } } : {}),
99
+ };
100
+ }));
101
+ };
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+ import { operations, operationNames } from "../../core/operations/catalog.js";
3
+ import { options, schemas } from "./schemas.js";
4
+ import { typed } from "../../lib/typed.js";
5
+ export const catalog = () => Object.freeze(operationNames.map((name) => {
6
+ const { summary, scope, effect, kind, input } = operations[name];
7
+ return { name, summary, scope, effect, kind, input: z.toJSONSchema(input, { io: "input" }) };
8
+ }));
9
+ const isObject = (value) => typeof value === "object" && value !== null;
10
+ const object = (value) => isObject(value) ? value : typed({});
11
+ const list = (value) => typed(Array.isArray(value) ? value : []);
12
+ const literal = (value) => JSON.stringify(value);
13
+ // Recursive: TypeScript cannot infer what it returns.
14
+ const typescript = (value) => {
15
+ const schema = object(value);
16
+ if ("const" in schema)
17
+ return literal(schema["const"]);
18
+ if (Array.isArray(schema["enum"]))
19
+ return schema["enum"].map(literal).join(" | ");
20
+ if (Array.isArray(schema["anyOf"]))
21
+ return schema["anyOf"].map(typescript).join(" | ");
22
+ if (Array.isArray(schema["oneOf"]))
23
+ return schema["oneOf"].map(typescript).join(" | ");
24
+ if (Array.isArray(schema["type"]))
25
+ return schema["type"].map((type) => typescript({ ...schema, type })).join(" | ");
26
+ switch (schema["type"]) {
27
+ case "null": return "null";
28
+ case "string": return "string";
29
+ case "integer":
30
+ case "number": return "number";
31
+ case "boolean": return "boolean";
32
+ case "array": return `readonly (${typescript(schema["items"])})[]`;
33
+ case "object": {
34
+ const properties = Object.entries(object(schema["properties"]));
35
+ const required = list(schema["required"]);
36
+ const fields = properties.map(([key, property]) => `readonly ${literal(key)}${required.includes(key) ? "" : "?"}: ${typescript(property)}`).join("; ");
37
+ if (properties.length === 0 && schema["additionalProperties"] === false)
38
+ return "Readonly<Record<string, never>>";
39
+ return properties.length === 0 ? `Readonly<Record<string, ${typescript(schema["additionalProperties"])}>>` : `{ ${fields} }`;
40
+ }
41
+ default: return "unknown";
42
+ }
43
+ };
44
+ export const contractTypes = () => [
45
+ "// Generated by npm run contract. The pinned kayra version defines this /api contract.",
46
+ ...Object.entries(schemas).map(([name, schema]) => `export type ${name} = ${typescript(z.toJSONSchema(schema))};`),
47
+ `export type OperationInputs = { ${operationNames.map((name) => `readonly ${literal(name)}: ${typescript(z.toJSONSchema(operations[name].input, { io: "input" }))}`).join("; ")} };`,
48
+ 'export type OperationName = keyof OperationInputs;',
49
+ 'export type InputOf<N extends OperationName> = OperationInputs[N];',
50
+ 'export type OperationCall = { readonly [N in OperationName]: { readonly name: N; readonly input: InputOf<N> } }[OperationName];',
51
+ `export type RunOptions = ${typescript(z.toJSONSchema(options, { io: "input" }))};`,
52
+ "",
53
+ ].join("\n");
@@ -0,0 +1,68 @@
1
+ import { z } from "zod";
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, runningStates } 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);
12
+ const span = z.union([z.string(), z.object({ tone: tone.exactOptional(), text: z.string(), href: z.string().exactOptional() })]);
13
+ const line = z.array(span);
14
+ const text = z.union([z.string(), line]);
15
+ const part = z.enum(parts);
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() });
17
+ const invocation = z.object({ command: z.string(), server: z.string().exactOptional(), about: z.array(z.string()) });
18
+ const stop = z.enum(stopReasons);
19
+ const state = z.enum(["running", "passed", "failed", "interrupted", "declined"]);
20
+ const summary = z.object({ id: z.string(), command: z.string(), server: z.string().exactOptional(), started: z.string(), state, session: z.boolean() });
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
+ const event = z.discriminatedUnion("kind", [
23
+ z.object({ kind: z.literal("plan"), invocation, steps: z.array(listed) }),
24
+ z.object({ kind: z.literal("started"), index: z.number() }),
25
+ z.object({ kind: z.literal("done"), index: z.number(), failed: z.boolean(), stopped: z.boolean(), why: z.string().exactOptional(), ms: z.number() }),
26
+ ended,
27
+ z.object({ kind: z.literal("output"), stream: z.enum(["stdout", "stderr"]), chunk: z.string() }),
28
+ z.object({ kind: z.literal("said"), stream: z.enum(["out", "err"]), text }),
29
+ z.object({ kind: z.literal("ask"), prompt: text, secret: z.boolean(), expect: z.string().exactOptional() }),
30
+ z.object({ kind: z.literal("answered") }),
31
+ ]);
32
+ const reach = z.enum(reachStates);
33
+ const verdict = z.enum(verdicts);
34
+ const serverCommand = z.enum(["up", "provision", "deploy", "setup", "plan", "verify", "apps", "down", "adopt", "backup.test"]);
35
+ const serverFacts = z.object({
36
+ name: z.string(), kind: z.enum(serverKinds), target: z.enum(serverTargets), domain: z.string(), apps: z.array(z.string()),
37
+ commands: z.array(z.union([serverCommand, z.literal("job")])),
38
+ });
39
+ export const options = z.strictObject({
40
+ verbose: z.boolean().default(false),
41
+ dryRun: z.boolean().default(false),
42
+ columns: z.number().int().min(1).max(1000).default(120),
43
+ rows: z.number().int().min(1).max(1000).default(32),
44
+ });
45
+ export const schemas = {
46
+ Tone: tone, Span: span, Line: line, Text: text, Part: part, Listed: listed, Invocation: invocation, Stop: stop, RunState: state,
47
+ RunEvent: event, RunSummary: summary,
48
+ Run: summary.extend({ events: z.array(event) }),
49
+ Preview: z.object({ invocation, steps: z.array(listed), changes: z.boolean() }),
50
+ ServerCommand: serverCommand,
51
+ ServerFacts: serverFacts,
52
+ FleetFacts: z.object({ fleet: z.string(), version: z.string(), servers: z.array(serverFacts) }),
53
+ DirectoryListing: z.object({ path: z.string(), parent: z.string(), directories: z.array(z.object({ name: z.string(), path: z.string() })) }),
54
+ ReachState: reach,
55
+ Status: z.object({ servers: z.array(z.object({
56
+ name: z.string(), kind: z.string(), target: z.string(), domain: z.string(), apps: z.array(z.string()),
57
+ machine: z.object({ state: z.enum(machineStates), address: z.string().nullable(), from: z.enum(["inventory", "opentofu"]).nullable(), reason: z.string().nullable() }),
58
+ ssh: z.object({ port: z.number(), state: reach, ms: z.number().nullable(), error: z.string().nullable() }),
59
+ https: z.object({ url: z.string(), state: reach, status: z.number().nullable(), ms: z.number().nullable(), error: z.string().nullable() }).nullable(),
60
+ kayra: z.object({ pin: z.string(), state: z.enum(runningStates), version: z.string().nullable(), error: z.string().nullable() }),
61
+ })) }),
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() })) })) }),
63
+ AppRuns: runsSchema, AppReleases: releasesSchema,
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()) }),
65
+ };
66
+ export const querySchemas = {
67
+ validate: schemas.Validation, version: z.string(), "app.runs": schemas.AppRuns, "app.releases": schemas.AppReleases, "app.log": z.string(),
68
+ };
@@ -3,7 +3,7 @@ export const ms = (reach) => ("ms" in reach ? reach.ms : null);
3
3
  const error = (reach) => ("code" in reach ? reach.code : null);
4
4
  /** `kayra status --json`: the shape cli.md documents. */
5
5
  export const statusJson = (looks) => ({
6
- servers: looks.map(({ server, machine, ssh, https }) => ({
6
+ servers: looks.map(({ server, machine, ssh, https, kayra, pin }) => ({
7
7
  name: server.name,
8
8
  kind: server.kind,
9
9
  target: server.target,
@@ -25,5 +25,11 @@ export const statusJson = (looks) => ({
25
25
  ms: ms(https),
26
26
  error: error(https),
27
27
  },
28
+ kayra: {
29
+ pin,
30
+ state: kayra.kind,
31
+ version: kayra.kind === "recorded" ? kayra.version : null,
32
+ error: kayra.kind === "unreadable" ? kayra.reason : null,
33
+ },
28
34
  })),
29
35
  });
@@ -0,0 +1,48 @@
1
+ /** What follows the server and the app on the command line, by operation. */
2
+ const extra = (call) => {
3
+ switch (call.name) {
4
+ case "ssh.exec":
5
+ return ["--", ...call.input.command];
6
+ case "job":
7
+ return [call.input.job, ...(call.input.noPrs ? ["--no-prs"] : [])];
8
+ case "app.rollback":
9
+ return [call.input.sha];
10
+ case "app.deploy":
11
+ return call.input.ref === undefined ? [] : [call.input.ref];
12
+ case "app.log":
13
+ return call.input.run === undefined ? [] : [call.input.run];
14
+ case "app.check":
15
+ return [call.input.dir];
16
+ case "certs":
17
+ return [call.input.domain, ...call.input.subdomains];
18
+ case "up":
19
+ case "provision":
20
+ case "deploy":
21
+ case "setup":
22
+ case "plan":
23
+ case "verify":
24
+ case "apps":
25
+ case "hosts":
26
+ case "ssh":
27
+ case "down":
28
+ case "adopt":
29
+ case "backup.test":
30
+ case "app.purge":
31
+ case "app.runs":
32
+ case "app.releases":
33
+ case "status":
34
+ case "validate":
35
+ case "doctor":
36
+ case "version":
37
+ return [];
38
+ }
39
+ };
40
+ /** How the command line spells an operation where its words are not its name's. */
41
+ const spelled = { "ssh.exec": "ssh", "app.releases": "app rollback", "app.log": "app logs" };
42
+ /** The command's words, as typed on the command line. */
43
+ export const words = (call) => {
44
+ const { input } = call;
45
+ const scope = ["server" in input ? input.server : undefined, "app" in input ? input.app : undefined];
46
+ const name = spelled[call.name] ?? call.name.replaceAll(".", " ");
47
+ return ["kayra", name, ...scope, ...extra(call)].filter((word) => word !== undefined).join(" ");
48
+ };
@@ -1,7 +1,11 @@
1
+ import { execFile } from "node:child_process";
1
2
  import { Agent, request } from "node:https";
2
3
  import { connect } from "node:net";
3
4
  import { getCACertificates } from "node:tls";
4
5
  import { milliseconds } from "../fleet/brand.js";
6
+ import { quote } from "../plan/describe.js";
7
+ import { sshArgv } from "../recipes/ssh.js";
8
+ import { err, ok } from "../../lib/result.js";
5
9
  import { typed } from "../../lib/typed.js";
6
10
  /** Why a connection failed, by Node's error code. */
7
11
  export const failure = (code) => {
@@ -19,7 +23,12 @@ export const failure = (code) => {
19
23
  };
20
24
  const codeOf = (error) => typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "ERROR";
21
25
  const since = (started) => milliseconds(Math.round(performance.now() - started));
22
- /** The network, as status asks it: a TCP connect, an HTTPS GET, each given up after `ms`; every answer a Reach, never an exception. */
26
+ /**
27
+ * The network, as status asks it: a TCP connect, an HTTPS GET, each given up
28
+ * after `ms`, every answer a Reach, never an exception; and a file read over
29
+ * SSH, which never asks (no password, no host key to confirm: rebuilt servers
30
+ * come back with new ones) and is given up after three times `ms`.
31
+ */
23
32
  export const network = (ms) => {
24
33
  // A multipass server's certificates are mkcert's, whose root is in the system's store, not Node's.
25
34
  // Reading it takes a while: after the first frame, not before.
@@ -63,5 +72,15 @@ export const network = (ms) => {
63
72
  asked.end();
64
73
  });
65
74
  },
75
+ read: (inventory, path) => new Promise((resolve) => {
76
+ const [program, ...args] = sshArgv(inventory, ["-o", "BatchMode=yes", "-o", `ConnectTimeout=${String(Math.ceil(ms / 1000))}`, "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "LogLevel=ERROR"], [`cat ${quote(path)} 2>/dev/null || true`]);
77
+ execFile(program, args, { timeout: ms * 3, killSignal: "SIGKILL" }, (error, stdout, stderr) => {
78
+ const said = stderr.trim().split("\n").at(-1) ?? "";
79
+ if (error === null)
80
+ resolve(ok(stdout));
81
+ else
82
+ resolve(err(error.killed ? "no answer" : said === "" ? `ssh exited ${String(error.code ?? "")}` : said));
83
+ });
84
+ }),
66
85
  });
67
86
  };
@@ -10,6 +10,11 @@ const pattern = (regex, what) => z.string().regex(regex, { error: (issue) => `'$
10
10
  export const serverNameSchema = pattern(/^[a-z0-9][a-z0-9-]*$/, "a server name (lowercase letters, digits, dashes)").transform(branded());
11
11
  export const appNameSchema = pattern(/^[a-z][a-z0-9-]*$/, "an app name (lowercase letters, digits, dashes)").transform(branded());
12
12
  export const subdomainSchema = pattern(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/, "a subdomain").transform(branded());
13
+ /** A route's path prefix: no backtick, quote or `$`, so it cannot leave its Traefik rule or meet Compose's interpolation. */
14
+ export const routePathSchema = pattern(/^\/[A-Za-z0-9._~%/-]*$/, "a path (/, then letters, digits and ._~%/-)").transform(branded());
15
+ export const serviceNameSchema = pattern(/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/, "a compose service name").transform(branded());
16
+ /** A Traefik duration. */
17
+ export const periodSchema = pattern(/^[1-9][0-9]*(ms|s|m|h)$/, "a period such as 10s, 10m or 1h").transform(branded());
13
18
  export const domainSchema = pattern(/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/, "a domain").transform(branded());
14
19
  /** A path inside a repository, never above it. */
15
20
  export const repoPathSchema = z
@@ -1,5 +1,5 @@
1
1
  import { absolutePath, host, sshDefaultPort, keyFile, port, remotePath, sshUser, vaultPasswordFile } from "./brand.js";
2
- import { err, map, ok } from "../../lib/result.js";
2
+ import { err, flatMap, map, ok } from "../../lib/result.js";
3
3
  import { serverSchema, varsSchema } from "./settings.js";
4
4
  import { checkSettings, knownSettings } from "./shape.js";
5
5
  import { typed } from "../../lib/typed.js";
@@ -118,6 +118,14 @@ export const parseServer = (files) => {
118
118
  const backupDir = typeof backup === "string" ? remotePath(backup) : ok(undefined);
119
119
  if (!backupDir.ok)
120
120
  return err(`vars.yml: restic_backup.dir ${backupDir.error}`);
121
+ const nasRoot = vars.value["nas_root"];
122
+ const versionFile = kind !== "nas"
123
+ ? remotePath("/opt/kayra/version")
124
+ : typeof nasRoot === "string"
125
+ ? flatMap(remotePath(nasRoot), (dir) => remotePath(`${dir}/.kayra/version`))
126
+ : ok(undefined);
127
+ if (!versionFile.ok)
128
+ return err(`vars.yml: nas_root ${versionFile.error}`);
121
129
  const inventory = files.inventory === undefined ? ok(undefined) : inventoryOf(files.inventory);
122
130
  if (!inventory.ok)
123
131
  return inventory;
@@ -137,6 +145,7 @@ export const parseServer = (files) => {
137
145
  usesAcmeDns: typeof vars.value["acme_dns"] === "string" && vars.value["acme_dns"] !== "",
138
146
  inventory: inventory.value,
139
147
  backupDir: backupDir.value,
148
+ versionFile: versionFile.value,
140
149
  stackHosts: stackHosts(files.stacks.flatMap((stack) => Object.freeze(stack.compose ?? [])), domain),
141
150
  vars: vars.value,
142
151
  files: { vars: files.vars, secrets: files.secrets, stacks: files.stacks.map((stack) => stack.name), appValues: files.appValues },