@yunuseon/kayra 0.17.1 → 0.18.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 (91) hide show
  1. package/README.md +2 -0
  2. package/agent/skills/kayra-release/SKILL.md +6 -1
  3. package/ansible/roles/platform/tasks/main.yml +10 -2
  4. package/cli/dist/clients/api/api.js +6 -4
  5. package/cli/dist/clients/api/auth.js +1 -1
  6. package/cli/dist/clients/api/commands.js +1 -49
  7. package/cli/dist/clients/api/directories.js +1 -1
  8. package/cli/dist/clients/api/discovery.js +1 -1
  9. package/cli/dist/clients/api/{contract.js → openapi.js} +3 -52
  10. package/cli/dist/clients/api/protocol.js +1 -66
  11. package/cli/dist/clients/api/runs.js +1 -1
  12. package/cli/dist/clients/api/start.js +3 -3
  13. package/cli/dist/clients/cli/explain.js +1 -1
  14. package/cli/dist/clients/cli/framed.js +1 -1
  15. package/cli/dist/clients/cli/invocation.js +1 -1
  16. package/cli/dist/clients/cli/parser.js +4 -0
  17. package/cli/dist/clients/cli/questions.js +1 -1
  18. package/cli/dist/clients/cli/status.js +1 -1
  19. package/cli/dist/clients/cli/terminal.js +1 -1
  20. package/cli/dist/clients/cli/text.js +1 -1
  21. package/cli/dist/clients/cli/validate.js +1 -1
  22. package/cli/dist/clients/cli/values.js +1 -1
  23. package/cli/dist/clients/cli/views.js +1 -1
  24. package/cli/dist/clients/mcp/run.js +69 -0
  25. package/cli/dist/clients/mcp/server.js +130 -0
  26. package/cli/dist/clients/mcp/tools.js +101 -0
  27. package/cli/dist/clients/wire/contract.js +53 -0
  28. package/cli/dist/clients/{api → wire}/queries.js +1 -1
  29. package/cli/dist/clients/wire/schemas.js +67 -0
  30. package/cli/dist/clients/wire/words.js +48 -0
  31. package/cli/dist/core/adapters/fs.js +1 -1
  32. package/cli/dist/core/adapters/network.js +1 -1
  33. package/cli/dist/core/adapters/opentofu.js +1 -1
  34. package/cli/dist/core/fleet/brand.js +23 -14
  35. package/cli/dist/core/fleet/docs.js +2 -2
  36. package/cli/dist/core/fleet/load.js +3 -2
  37. package/cli/dist/core/fleet/parse.js +59 -91
  38. package/cli/dist/core/fleet/settings.js +38 -13
  39. package/cli/dist/core/fleet/shape.js +5 -20
  40. package/cli/dist/core/interpreter/events.js +1 -1
  41. package/cli/dist/core/interpreter/loop.js +1 -1
  42. package/cli/dist/core/interpreter/needs.js +1 -1
  43. package/cli/dist/core/interpreter/process.js +2 -2
  44. package/cli/dist/core/interpreter/progress.js +1 -1
  45. package/cli/dist/core/interpreter/pty.js +1 -1
  46. package/cli/dist/core/operations/dispatch.js +2 -2
  47. package/cli/dist/core/plan/model.js +1 -1
  48. package/cli/dist/core/recipes/app-check.js +5 -8
  49. package/cli/dist/core/recipes/apps.js +2 -2
  50. package/cli/dist/core/recipes/backup.js +1 -1
  51. package/cli/dist/core/recipes/certs.js +1 -1
  52. package/cli/dist/core/recipes/doctor.js +1 -1
  53. package/cli/dist/core/recipes/host.js +2 -2
  54. package/cli/dist/core/recipes/ssh.js +2 -2
  55. package/cli/dist/core/recipes/steps.js +2 -2
  56. package/cli/dist/core/status/look.js +1 -1
  57. package/cli/dist/core/text/spans.js +1 -1
  58. package/cli/dist/core/validation/facts.js +3 -2
  59. package/cli/dist/core/validation/findings.js +3 -3
  60. package/cli/dist/deployer/app.js +2 -2
  61. package/cli/dist/deployer/brand.js +1 -1
  62. package/cli/dist/deployer/build/builder.js +2 -2
  63. package/cli/dist/deployer/build/bundle.js +2 -2
  64. package/cli/dist/deployer/build/compose.js +1 -1
  65. package/cli/dist/deployer/cron.js +1 -1
  66. package/cli/dist/deployer/ctl/answers.js +1 -1
  67. package/cli/dist/deployer/deployer.js +7 -11
  68. package/cli/dist/deployer/forges/forge.js +1 -1
  69. package/cli/dist/deployer/forges/forgejo.js +1 -1
  70. package/cli/dist/deployer/forges/github.js +1 -1
  71. package/cli/dist/deployer/forges/gitlab.js +1 -1
  72. package/cli/dist/deployer/forges/issues.js +2 -2
  73. package/cli/dist/deployer/forges/notify.js +2 -2
  74. package/cli/dist/deployer/runs/queue.js +8 -1
  75. package/cli/dist/deployer/runs/records.js +1 -1
  76. package/cli/dist/deployer/runs/run.js +2 -2
  77. package/cli/dist/deployer/runs/store.js +1 -1
  78. package/cli/dist/lib/brand.js +2 -0
  79. package/cli/dist/lib/closest.js +17 -0
  80. package/cli/dist/lib/schema.js +7 -0
  81. package/cli/dist/lib/yaml.js +21 -0
  82. package/cli/dist/main.js +12 -4
  83. package/package.json +3 -1
  84. package/schema/app.json +4 -2
  85. package/schema/server.json +10 -5
  86. package/scripts/agent/guard.sh +28 -6
  87. /package/cli/dist/clients/{api → wire}/contract.gen.js +0 -0
  88. /package/cli/dist/clients/{api → wire}/status.js +0 -0
  89. /package/cli/dist/clients/{api → wire}/validate.js +0 -0
  90. /package/cli/dist/{result.js → lib/result.js} +0 -0
  91. /package/cli/dist/{typed.js → lib/typed.js} +0 -0
package/README.md CHANGED
@@ -62,6 +62,7 @@ kayra deploy shop-prod # host setup + apps, no re-provision (from main only)
62
62
  kayra status
63
63
  kayra serve # the fleet in the browser
64
64
  kayra serve --ui --api # browser and the local program API
65
+ kayra mcp # every command as a tool, for an agent (from .mcp.json)
65
66
  ```
66
67
 
67
68
  ## Documentation
@@ -73,6 +74,7 @@ kayra serve --ui --api # browser and the local program API
73
74
  | [CI isolation](https://yunuseon.github.io/kayra/concepts/ci-isolation/) | why app code cannot reach the host or the platform |
74
75
  | [Authentication](https://yunuseon.github.io/kayra/concepts/authentication/) | staff login (Authelia), adding people, recovery |
75
76
  | [Local API](https://yunuseon.github.io/kayra/reference/api/) | program access, authentication, operations, runs and terminal sessions |
77
+ | [MCP](https://yunuseon.github.io/kayra/reference/mcp/) | every operation as a tool for an agent such as Claude Code, and what asks |
76
78
  | [Upgrade to 0.17.0](https://yunuseon.github.io/kayra/reference/upgrading-0-17/) | replacing `kayra ui`, client changes and the fleet dependency bump |
77
79
  | [`CLAUDE.md`](CLAUDE.md) | how everything fits together, and the rules that keep it working |
78
80
 
@@ -47,13 +47,18 @@ In the worktree:
47
47
  ```bash
48
48
  git -C "$W" switch -c release-<version>
49
49
  npm --prefix "$W" version <version> --no-git-tag-version # package.json + package-lock.json only
50
- git -C "$W" add package.json package-lock.json
50
+ npm --prefix "$W" run contract # openapi.json carries the version
51
+ git -C "$W" add package.json package-lock.json cli/src/clients/api/openapi.json
51
52
  git -C "$W" commit -s -F <message file> # DCO sign-off; the message summarises the PRs
52
53
  git -C "$W" push -u origin release-<version>
53
54
  gh pr create --repo yunuseon/kayra --base main --head release-<version> --title "<version>" --body-file <file>
54
55
  gh pr checks release-<version> --repo yunuseon/kayra --watch --interval 20
55
56
  ```
56
57
 
58
+ The generated API contract names the version: a bump without `npm run
59
+ contract` fails the checks (0.17.2's first push did, and 0.17.1 needed a
60
+ follow-up commit).
61
+
57
62
  Write commit messages and PR bodies to a file first (quoted heredoc):
58
63
  backticks inside `-m "…"` or a double-quoted `--body` are executed by the
59
64
  shell.
@@ -123,12 +123,20 @@
123
123
  mode: "0644"
124
124
  loop:
125
125
  - deployer/
126
- - "result.{{ 'ts' if deployer_source.stat.exists else 'js' }}"
127
- - "typed.{{ 'ts' if deployer_source.stat.exists else 'js' }}"
126
+ - lib/
128
127
  vars:
129
128
  code: "{{ 'src' if deployer_source.stat.exists else 'dist' }}"
130
129
  become: true
131
130
 
131
+ # result and typed used to sit next to deployer/, before lib/. Drop this
132
+ # once every fleet's servers have deployed lib/.
133
+ - name: Remove the deployer's shared files of earlier versions
134
+ ansible.builtin.file:
135
+ path: "{{ platform_dir }}/deployer/app/{{ item.0 }}.{{ item.1 }}"
136
+ state: absent
137
+ loop: "{{ ['result', 'typed'] | product(['ts', 'js']) | list }}"
138
+ become: true
139
+
132
140
  # The deployer's files used to sit flat in deployer/; those now in folders
133
141
  # are removed here, since a copy adds and never removes. Idempotent; drop it
134
142
  # once every fleet's servers have deployed the folders.
@@ -7,14 +7,16 @@ import { contextFor, invocation, isQuery, isStream, stream } from "../../core/op
7
7
  import { follow } from "../../core/status/updates.js";
8
8
  import { json, send } from "../../deployer/http/http.js";
9
9
  import { facts } from "./commands.js";
10
- import { catalog, openapi } from "./contract.js";
10
+ import { catalog } from "../wire/contract.js";
11
+ import { openapi } from "./openapi.js";
11
12
  import { directories } from "./directories.js";
12
13
  import { inFlight, liveRuns } from "./live.js";
13
- import { options, requestBody } from "./protocol.js";
14
- import { answer as queryAnswer } from "./queries.js";
14
+ import { options } from "../wire/schemas.js";
15
+ import { requestBody } from "./protocol.js";
16
+ import { answer as queryAnswer } from "../wire/queries.js";
15
17
  import { stateOf, summary } from "./runs.js";
16
18
  import { allRuns, preview, start } from "./start.js";
17
- import { statusJson } from "./status.js";
19
+ import { statusJson } from "../wire/status.js";
18
20
  const answerJson = (response, status, value) => {
19
21
  send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
20
22
  };
@@ -1,5 +1,5 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** Cookies are shared by every port of a host: the name carries the port, so another local server's cookie is not ours. */
4
4
  export const cookieName = (port) => `kayra_ui_${String(port)}`;
5
5
  const origins = (port) => typed([`127.0.0.1:${String(port)}`, `localhost:${String(port)}`]);
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  export const offered = (server) => typed([
3
3
  ...(server.kind === "platform" ? ["deploy", "apps", "verify"] : []),
4
4
  "setup", "plan",
@@ -13,51 +13,3 @@ export const facts = (server) => typed({
13
13
  name: server.name, kind: server.kind, target: server.target, domain: server.domain,
14
14
  apps: server.apps.map((app) => app.name), commands: offered(server),
15
15
  });
16
- /** What follows the server and the app on the command line, by operation. */
17
- const extra = (call) => {
18
- switch (call.name) {
19
- case "ssh.exec":
20
- return ["--", ...call.input.command];
21
- case "job":
22
- return [call.input.job, ...(call.input.noPrs ? ["--no-prs"] : [])];
23
- case "app.rollback":
24
- return [call.input.sha];
25
- case "app.deploy":
26
- return call.input.ref === undefined ? [] : [call.input.ref];
27
- case "app.log":
28
- return call.input.run === undefined ? [] : [call.input.run];
29
- case "app.check":
30
- return [call.input.dir];
31
- case "certs":
32
- return [call.input.domain, ...call.input.subdomains];
33
- case "up":
34
- case "provision":
35
- case "deploy":
36
- case "setup":
37
- case "plan":
38
- case "verify":
39
- case "apps":
40
- case "hosts":
41
- case "ssh":
42
- case "down":
43
- case "adopt":
44
- case "backup.test":
45
- case "app.purge":
46
- case "app.runs":
47
- case "app.releases":
48
- case "status":
49
- case "validate":
50
- case "doctor":
51
- case "version":
52
- return [];
53
- }
54
- };
55
- /** How the command line spells an operation where its words are not its name's. */
56
- const spelled = { "ssh.exec": "ssh", "app.releases": "app rollback", "app.log": "app logs" };
57
- /** The command's words, as typed on the command line. */
58
- export const words = (call) => {
59
- const { input } = call;
60
- const scope = ["server" in input ? input.server : undefined, "app" in input ? input.app : undefined];
61
- const name = spelled[call.name] ?? call.name.replaceAll(".", " ");
62
- return ["kayra", name, ...scope, ...extra(call)].filter((word) => word !== undefined).join(" ");
63
- };
@@ -1,6 +1,6 @@
1
1
  import { readdir, realpath, stat } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
- import { err, ok } from "../../result.js";
3
+ import { err, ok } from "../../lib/result.js";
4
4
  export const directories = async (path, root) => {
5
5
  try {
6
6
  const absolute = await realpath(resolve(root, path));
@@ -1,7 +1,7 @@
1
1
  import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { z } from "zod";
4
- import { err, ok } from "../../result.js";
4
+ import { err, ok } from "../../lib/result.js";
5
5
  const entry = z.object({ url: z.string(), token: z.string(), pid: z.number().int().positive() });
6
6
  const alive = (pid) => {
7
7
  try {
@@ -1,56 +1,7 @@
1
1
  import { z } from "zod";
2
- import { operations, operationNames } from "../../core/operations/catalog.js";
3
- import { options, schemas, querySchemas } from "./protocol.js";
4
- import { typed } from "../../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");
2
+ import { catalog } from "../wire/contract.js";
3
+ import { options, schemas, querySchemas } from "../wire/schemas.js";
4
+ import { typed } from "../../lib/typed.js";
54
5
  const response = (description, schema, media = "application/json") => ({ description, content: { [media]: { schema } } });
55
6
  const ref = (name) => ({ $ref: `#/components/schemas/${name}` });
56
7
  const isQueryName = (name) => Object.hasOwn(querySchemas, name);
@@ -1,68 +1,3 @@
1
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 } 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
- });
2
+ import { options } from "../wire/schemas.js";
45
3
  export const requestBody = z.strictObject({ input: z.unknown().exactOptional(), options: options.exactOptional(), confirm: z.string().exactOptional() });
46
- export const schemas = {
47
- Tone: tone, Span: span, Line: line, Text: text, Part: part, Listed: listed, Invocation: invocation, Stop: stop, RunState: state,
48
- RunEvent: event, RunSummary: summary,
49
- Run: summary.extend({ events: z.array(event) }),
50
- Preview: z.object({ invocation, steps: z.array(listed), changes: z.boolean() }),
51
- ServerCommand: serverCommand,
52
- ServerFacts: serverFacts,
53
- FleetFacts: z.object({ fleet: z.string(), version: z.string(), servers: z.array(serverFacts) }),
54
- DirectoryListing: z.object({ path: z.string(), parent: z.string(), directories: z.array(z.object({ name: z.string(), path: z.string() })) }),
55
- ReachState: reach,
56
- Status: z.object({ servers: z.array(z.object({
57
- name: z.string(), kind: z.string(), target: z.string(), domain: z.string(), apps: z.array(z.string()),
58
- machine: z.object({ state: z.enum(machineStates), address: z.string().nullable(), from: z.enum(["inventory", "opentofu"]).nullable(), reason: z.string().nullable() }),
59
- ssh: z.object({ port: z.number(), state: reach, ms: z.number().nullable(), error: z.string().nullable() }),
60
- https: z.object({ url: z.string(), state: reach, status: z.number().nullable(), ms: z.number().nullable(), error: z.string().nullable() }).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
- };
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /** Sortable by time (an ISO 8601 instant), unique by its tail. */
3
3
  export const runId = (iso, random) => `${iso.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${random}`;
4
4
  export const stateOf = (events) => {
@@ -8,9 +8,9 @@ import { interpret } from "../../core/interpreter/loop.js";
8
8
  import { operation } from "../../core/operations/catalog.js";
9
9
  import { hasPlan, planOf, serverOf } from "../../core/operations/dispatch.js";
10
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";
11
+ import { err, ok } from "../../lib/result.js";
12
+ import { typed } from "../../lib/typed.js";
13
+ import { words } from "../wire/words.js";
14
14
  import { busy, readRecord, recordLine, runId } from "./runs.js";
15
15
  /** Every run there is: the live ones, then those recorded, newest first. */
16
16
  export const allRuns = (served) => {
@@ -4,7 +4,7 @@ import { position } from "../../core/interpreter/progress.js";
4
4
  import { steps as count } from "../../core/interpreter/events.js";
5
5
  import { wrap } from "./text.js";
6
6
  import { drawnAs } from "./views.js";
7
- import { typed } from "../../typed.js";
7
+ import { typed } from "../../lib/typed.js";
8
8
  const kinds = { guard: warn, check: active, run: active, confirm: bad, note: muted };
9
9
  const tag = (step) => {
10
10
  const kind = kindOf(step);
@@ -6,7 +6,7 @@ import { spread, truncate } from "./text.js";
6
6
  import { paint } from "./paint.js";
7
7
  import { escapes, spinner } from "./terminal.js";
8
8
  import { milliseconds } from "../../core/fleet/brand.js";
9
- import { typed } from "../../typed.js";
9
+ import { typed } from "../../lib/typed.js";
10
10
  /** A run of this long earns a notification when it ends: the operator has looked away. */
11
11
  const worthNotifying = 30_000;
12
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. */
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /**
3
3
  * The parsed command line as the operation it names. `app rollback` without a
4
4
  * commit lists the releases (`app.releases`), with one it rolls back.
@@ -169,6 +169,10 @@ export const parser = (fleet) => {
169
169
  brief: message `The local browser interface and API: the fleet, its servers and apps, every command with its steps live.`,
170
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.`,
171
171
  footer: footer(["kayra serve", "open it in the browser"], ["kayra serve --port 7700 --no-open", "for web/'s dev server"]),
172
+ }), command("mcp", object({ name: constant("mcp") }), {
173
+ brief: message `An MCP server on stdin and stdout: every operation as a tool, for an agent such as Claude Code.`,
174
+ description: message `Started by the agent from the fleet's .mcp.json, not by hand. Runs the same plans as the command line, with the same guards; asks for no password, and has the operator type a server's name before destroying it.`,
175
+ footer: footer(["kayra mcp", "what the fleet's .mcp.json starts: {\"command\": \"kayra\", \"args\": [\"mcp\"]}"]),
172
176
  }), command("certs", object({
173
177
  name: constant("certs"),
174
178
  domain: argument(domainParser, { description: message `The domain the certificates are for.` }),
@@ -1,5 +1,5 @@
1
1
  import { createInterface } from "node:readline/promises";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** The command line's questions: secret typing stays unseen, piped answers keep their order. */
4
4
  export const questions = (render) => {
5
5
  // eslint-disable-next-line functional/prefer-immutable-types -- resources belong to this reader and close with the plan
@@ -1,7 +1,7 @@
1
1
  import { active, bad, ok as fine, link, muted, pointing, strong, warn } from "../../core/text/spans.js";
2
2
  import { fit, table } from "./text.js";
3
3
  import { authUrl } from "../../core/status/look.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  /** A spinner as wide as most answers, so the columns hardly move when they come. */
6
6
  const waiting = (frame, width) => typed([active(frame), " ".repeat(width - 1)]);
7
7
  const machineCell = (machine, frame) => {
@@ -43,7 +43,7 @@ export const escapes = {
43
43
  up: (count) => (count > 0 ? `\u001b[${String(count)}F` : ""),
44
44
  clearDown: "\u001b[J",
45
45
  };
46
- import { typed } from "../../typed.js";
46
+ import { typed } from "../../lib/typed.js";
47
47
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
48
48
  const frameOf = (ms) => frames[Math.floor(ms / 80) % frames.length] ?? "";
49
49
  /** Draws a line in place, again every frame, until stopped; stopping clears it. */
@@ -1,5 +1,5 @@
1
1
  import { characters, width } from "../../core/text/spans.js";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** `left`, then `right` flush with the last column, at least two spaces apart. */
4
4
  export const spread = (left, right, columns) => typed([
5
5
  ...left,
@@ -1,7 +1,7 @@
1
1
  import { bad, muted, ok, pointing, strong } from "../../core/text/spans.js";
2
2
  import { count } from "../../core/text/plural.js";
3
3
  import { overall, tally } from "../../core/validation/findings.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  const marks = { problem: bad("✗"), unchecked: muted("·"), passed: ok("✓") };
6
6
  /** "✗ 3 servers · 1 problem · 2 not checked" */
7
7
  export const summary = (reports) => {
@@ -1,6 +1,6 @@
1
1
  import { text } from "@optique/core/message";
2
2
  import { appName, domain, examples, serverName, subdomain } from "../../core/fleet/brand.js";
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  /** An Optique value parser that mints a brand: arguments arrive already validated. */
5
5
  const minting = (metavar, mint, placeholder) => typed({
6
6
  mode: "sync",
@@ -4,7 +4,7 @@ import { duration } from "../../core/text/time.js";
4
4
  import { parsed, releasesSchema, runsSchema } from "../../core/ctl/answers.js";
5
5
  import { count } from "../../core/text/plural.js";
6
6
  import { milliseconds } from "../../core/fleet/brand.js";
7
- import { typed } from "../../typed.js";
7
+ import { typed } from "../../lib/typed.js";
8
8
  /** Lines as printing them one by one gives the text back: newline-ended, as a ctl writes. */
9
9
  const linesOf = (text) => (text === "" ? typed([]) : text.replace(/\n$/, "").split("\n"));
10
10
  const short = (sha) => sha.slice(0, 7);
@@ -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
+ };