@yunuseon/kayra 0.17.2 → 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.
- package/README.md +2 -0
- package/cli/dist/clients/api/api.js +6 -4
- package/cli/dist/clients/api/commands.js +0 -48
- package/cli/dist/clients/api/{contract.js → openapi.js} +2 -51
- package/cli/dist/clients/api/protocol.js +1 -66
- package/cli/dist/clients/api/start.js +1 -1
- package/cli/dist/clients/cli/parser.js +4 -0
- package/cli/dist/clients/mcp/run.js +69 -0
- package/cli/dist/clients/mcp/server.js +130 -0
- package/cli/dist/clients/mcp/tools.js +101 -0
- package/cli/dist/clients/wire/contract.js +53 -0
- package/cli/dist/clients/wire/schemas.js +67 -0
- package/cli/dist/clients/wire/words.js +48 -0
- package/cli/dist/deployer/deployer.js +5 -9
- package/cli/dist/deployer/runs/queue.js +7 -0
- package/cli/dist/main.js +11 -3
- package/package.json +3 -1
- package/scripts/agent/guard.sh +28 -6
- /package/cli/dist/clients/{api → wire}/contract.gen.js +0 -0
- /package/cli/dist/clients/{api → wire}/queries.js +0 -0
- /package/cli/dist/clients/{api → wire}/status.js +0 -0
- /package/cli/dist/clients/{api → wire}/validate.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
|
|
|
@@ -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
|
|
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
|
|
14
|
-
import {
|
|
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 "
|
|
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
|
};
|
|
@@ -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,56 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import {
|
|
3
|
-
import { options, schemas, querySchemas } from "
|
|
2
|
+
import { catalog } from "../wire/contract.js";
|
|
3
|
+
import { options, schemas, querySchemas } from "../wire/schemas.js";
|
|
4
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");
|
|
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 {
|
|
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
|
-
};
|
|
@@ -10,7 +10,7 @@ import { hasPlan, planOf, serverOf } from "../../core/operations/dispatch.js";
|
|
|
10
10
|
import { verbose } from "../../core/recipes/steps.js";
|
|
11
11
|
import { err, ok } from "../../lib/result.js";
|
|
12
12
|
import { typed } from "../../lib/typed.js";
|
|
13
|
-
import { words } from "
|
|
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) => {
|
|
@@ -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.` }),
|
|
@@ -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,67 @@
|
|
|
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
|
+
});
|
|
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
|
+
})) }),
|
|
61
|
+
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() })) })) }),
|
|
62
|
+
AppRuns: runsSchema, AppReleases: releasesSchema,
|
|
63
|
+
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()) }),
|
|
64
|
+
};
|
|
65
|
+
export const querySchemas = {
|
|
66
|
+
validate: schemas.Validation, version: z.string(), "app.runs": schemas.AppRuns, "app.releases": schemas.AppReleases, "app.log": z.string(),
|
|
67
|
+
};
|
|
@@ -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
|
+
};
|
|
@@ -7,12 +7,12 @@ import { createInterface } from "node:readline";
|
|
|
7
7
|
import { Readable } from "node:stream";
|
|
8
8
|
import { all, err, ok } from "../lib/result.js";
|
|
9
9
|
import { field, registered } from "./app.js";
|
|
10
|
-
import { appName, appOwner,
|
|
10
|
+
import { appName, appOwner, newRunId, sha } from "./brand.js";
|
|
11
11
|
import { matches, parseCron } from "./cron.js";
|
|
12
12
|
import { forge, forgeRepo } from "./forges/forge.js";
|
|
13
13
|
import { json, send } from "./http/http.js";
|
|
14
14
|
import { spawnLines } from "./process.js";
|
|
15
|
-
import { empty, enqueue, finish } from "./runs/queue.js";
|
|
15
|
+
import { describe, empty, enqueue, finish, jobRequest } from "./runs/queue.js";
|
|
16
16
|
import { expired, moved, releaseName, releases } from "./runs/records.js";
|
|
17
17
|
import { githubIssues } from "./forges/issues.js";
|
|
18
18
|
import { decide, parseNotify, silent } from "./forges/notify.js";
|
|
@@ -172,9 +172,6 @@ const effects = (s, who, id, log) => typed({
|
|
|
172
172
|
log(`(commit status ${context} not posted: ${posted.error})`);
|
|
173
173
|
},
|
|
174
174
|
});
|
|
175
|
-
const describe = (request) => request.work.kind === "deploy"
|
|
176
|
-
? typed({ what: `deploy ${request.work.ref}`, why: request.work.why })
|
|
177
|
-
: typed({ what: `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`, why: "schedule" });
|
|
178
175
|
const work = async (s, request, fx) => {
|
|
179
176
|
if (request.work.kind === "deploy") {
|
|
180
177
|
const app = registered(s.platformDir, request.work.app);
|
|
@@ -238,7 +235,6 @@ const deployRequest = (app, ref, why) => typed({
|
|
|
238
235
|
owner: appOwner(app.name),
|
|
239
236
|
work: { kind: "deploy", app: app.name, ref, why },
|
|
240
237
|
});
|
|
241
|
-
const jobRequest = (job, dryRun) => typed({ owner: jobOwner(job), work: { kind: "job", job, dryRun } });
|
|
242
238
|
/** The webhook's fallback: an app whose ref moved to a commit no run has tried yet and no release runs (one migrated from Jenkins has releases but no runs). */
|
|
243
239
|
const poll = async (s) => {
|
|
244
240
|
await Promise.all(registeredApps(s).map(async (app) => {
|
|
@@ -254,9 +250,9 @@ const tick = (s, at) => {
|
|
|
254
250
|
if (matches(s.poll, at))
|
|
255
251
|
void poll(s);
|
|
256
252
|
if (matches(s.gc, at))
|
|
257
|
-
swap(s, (queue) => enqueue(queue, jobRequest("gc", false)));
|
|
253
|
+
swap(s, (queue) => enqueue(queue, jobRequest("gc", false, "schedule")));
|
|
258
254
|
if (s.renovate !== undefined && matches(s.renovate, at))
|
|
259
|
-
swap(s, (queue) => enqueue(queue, jobRequest("renovate", false)));
|
|
255
|
+
swap(s, (queue) => enqueue(queue, jobRequest("renovate", false, "schedule")));
|
|
260
256
|
};
|
|
261
257
|
const schedule = (s) => {
|
|
262
258
|
const wait = 60_000 - (Date.now() % 60_000) + 500;
|
|
@@ -301,7 +297,7 @@ const control = async (s, request, response) => {
|
|
|
301
297
|
send(response, 409, "this server has no renovate_repositories\n");
|
|
302
298
|
return;
|
|
303
299
|
}
|
|
304
|
-
accept(s, response, jobRequest(job, field(input, "dryRun") === true));
|
|
300
|
+
accept(s, response, jobRequest(job, field(input, "dryRun") === true, "manual"));
|
|
305
301
|
return;
|
|
306
302
|
}
|
|
307
303
|
send(response, 404, "not found\n");
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
+
import { jobOwner } from "../brand.js";
|
|
1
2
|
import { typed } from "../../lib/typed.js";
|
|
3
|
+
export const jobRequest = (job, dryRun, why) => typed({ owner: jobOwner(job), work: { kind: "job", job, dryRun, why } });
|
|
4
|
+
/** A run's meta.json `what` and `why`. */
|
|
5
|
+
export const describe = (request) => Object.freeze({
|
|
6
|
+
what: request.work.kind === "deploy" ? `deploy ${request.work.ref}` : `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`,
|
|
7
|
+
why: request.work.why,
|
|
8
|
+
});
|
|
2
9
|
export const empty = (limit) => typed({ running: [], waiting: [], limit });
|
|
3
10
|
const exclusive = (request) => request.work.kind === "job" && request.work.job === "gc";
|
|
4
11
|
/** Starts what may start, in order; a waiting exclusive request holds back everything behind it. */
|
package/cli/dist/main.js
CHANGED
|
@@ -9,10 +9,10 @@ import { fromCommand } from "./clients/cli/invocation.js";
|
|
|
9
9
|
import { parser, runOptions } from "./clients/cli/parser.js";
|
|
10
10
|
import { verbose } from "./core/recipes/steps.js";
|
|
11
11
|
import { opentofu } from "./core/adapters/opentofu.js";
|
|
12
|
-
import { statusJson } from "./clients/
|
|
12
|
+
import { statusJson } from "./clients/wire/status.js";
|
|
13
13
|
import { statusView } from "./clients/cli/status.js";
|
|
14
14
|
import { overall } from "./core/validation/findings.js";
|
|
15
|
-
import { validateJson } from "./clients/
|
|
15
|
+
import { validateJson } from "./clients/wire/validate.js";
|
|
16
16
|
import { validateView } from "./clients/cli/validate.js";
|
|
17
17
|
import { interpret } from "./core/interpreter/loop.js";
|
|
18
18
|
import { findFleetRoot, loadFleet } from "./core/fleet/load.js";
|
|
@@ -20,6 +20,7 @@ import { operation as describe } from "./core/operations/catalog.js";
|
|
|
20
20
|
import { contextFor, hasPlan, planOf, query, serverOf, stream } from "./core/operations/dispatch.js";
|
|
21
21
|
import { systemBrowser } from "./clients/ui/opener.js";
|
|
22
22
|
import { serve } from "./serve.js";
|
|
23
|
+
import { serveMcp } from "./clients/mcp/server.js";
|
|
23
24
|
import { network } from "./core/adapters/network.js";
|
|
24
25
|
import { render } from "./core/plan/describe.js";
|
|
25
26
|
import { err, flatMap, map, ok } from "./lib/result.js";
|
|
@@ -90,7 +91,14 @@ const short = shortener([
|
|
|
90
91
|
[homedir(), "~"],
|
|
91
92
|
]);
|
|
92
93
|
const context = contextFor({ kayra, fleet: fleet, version, here: here.value, network: network(2_000), tofu: opentofu });
|
|
93
|
-
if (args.command.name === "
|
|
94
|
+
if (args.command.name === "mcp") {
|
|
95
|
+
// stdout is the protocol: nothing else may write there, and every step's output is piped.
|
|
96
|
+
if (!found.ok)
|
|
97
|
+
fail(found.error);
|
|
98
|
+
else
|
|
99
|
+
serveMcp({ context, short }, (message) => { process.stderr.write(`kayra mcp: ${message}\n`); });
|
|
100
|
+
}
|
|
101
|
+
else if (args.command.name === "serve") {
|
|
94
102
|
if (!found.ok)
|
|
95
103
|
fail(found.error);
|
|
96
104
|
// The browser side: web/dist in a checkout, cli/dist/browser in the package.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yunuseon/kayra",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "A self-hosted app platform and the CLI that runs it: Traefik, Authelia, a registry, rootless BuildKit and a small deployer per server, set up with OpenTofu and Ansible.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Yunus Öztürk",
|
|
@@ -44,6 +44,7 @@
|
|
|
44
44
|
"signatures": "rm -rf .cache/signatures && tsc -p cli/tsconfig.build.json --declaration --emitDeclarationOnly --outDir .cache/signatures"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
+
"@modelcontextprotocol/server": "2.3.1",
|
|
47
48
|
"@optique/core": "1.3.3",
|
|
48
49
|
"@optique/run": "1.3.3",
|
|
49
50
|
"yaml": "2.9.1",
|
|
@@ -51,6 +52,7 @@
|
|
|
51
52
|
},
|
|
52
53
|
"devDependencies": {
|
|
53
54
|
"@eslint/js": "10.0.1",
|
|
55
|
+
"@modelcontextprotocol/client": "2.3.1",
|
|
54
56
|
"@tsconfig/node24": "24.0.5",
|
|
55
57
|
"@tsconfig/strictest": "2.0.8",
|
|
56
58
|
"@types/node": "24.19.1",
|
package/scripts/agent/guard.sh
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
2
|
# =============================================================================
|
|
3
|
-
# guard.sh — Claude Code's PreToolUse hook on Bash, in kayra and every fleet
|
|
3
|
+
# guard.sh — Claude Code's PreToolUse hook on Bash and kayra's MCP tools, in kayra and every fleet
|
|
4
4
|
# (.claude/settings.json): an AI agent may build, test and read freely, but a
|
|
5
5
|
# command that changes something real waits for the operator to approve it,
|
|
6
6
|
# in that moment.
|
|
@@ -21,6 +21,10 @@
|
|
|
21
21
|
# - git push of main or a tag, a force push, deleting a remote branch
|
|
22
22
|
# - tofu / terraform apply, destroy, import, state changes
|
|
23
23
|
# - destructive commands over SSH (rm, docker rm/stop/prune/down, systemctl…)
|
|
24
|
+
# kayra's MCP tools (mcp__kayra__<tool>, the fleet's .mcp.json naming the
|
|
25
|
+
# server kayra) the same way, read from their JSON input: a tool that changes
|
|
26
|
+
# a server asks unless dryRun is set or the server is a multipass one; one
|
|
27
|
+
# that changes nothing passes.
|
|
24
28
|
# Anything else: no output, the normal permission flow.
|
|
25
29
|
#
|
|
26
30
|
# It reads the command's text, so it stops mistakes and instructions smuggled
|
|
@@ -30,8 +34,6 @@
|
|
|
30
34
|
set -uo pipefail
|
|
31
35
|
|
|
32
36
|
input="$(cat)"
|
|
33
|
-
command="$(jq -r '.tool_input.command // empty' <<< "$input" 2>/dev/null)"
|
|
34
|
-
[ -n "$command" ] || exit 0
|
|
35
37
|
mode="$(jq -r '.permission_mode // empty' <<< "$input" 2>/dev/null)"
|
|
36
38
|
project="${CLAUDE_PROJECT_DIR:-$PWD}"
|
|
37
39
|
|
|
@@ -44,6 +46,28 @@ ask() {
|
|
|
44
46
|
'{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: $decision, permissionDecisionReason: $reason}}'
|
|
45
47
|
exit 0
|
|
46
48
|
}
|
|
49
|
+
# The target a server's server.yml names, if the server is one of this project's.
|
|
50
|
+
target_of() {
|
|
51
|
+
[[ "$1" =~ ^[a-z0-9][a-z0-9-]*$ ]] && [ -f "${project}/servers/$1/server.yml" ] || return 0
|
|
52
|
+
sed -n 's/^target: *\([a-z]*\).*/\1/p' "${project}/servers/$1/server.yml"
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
# ── kayra's MCP tools ───────────────────────────────────────────────────────
|
|
56
|
+
# The tools that change nothing (the catalog's effect "reads"; a test holds this list to it).
|
|
57
|
+
mcp_reads='status|validate|verify|plan|doctor|version|app_check|app_runs|app_log|app_releases'
|
|
58
|
+
tool="$(jq -r '.tool_name // empty' <<< "$input" 2>/dev/null)"
|
|
59
|
+
if [[ "$tool" == mcp__kayra__* ]]; then
|
|
60
|
+
name="${tool#mcp__kayra__}"
|
|
61
|
+
[[ "$name" =~ ^(${mcp_reads})$ ]] && exit 0
|
|
62
|
+
[ "$(jq -r '.tool_input.dryRun // false' <<< "$input" 2>/dev/null)" = true ] && exit 0
|
|
63
|
+
server="$(jq -r '.tool_input.server // empty | strings' <<< "$input" 2>/dev/null)"
|
|
64
|
+
target="$(target_of "$server")"
|
|
65
|
+
[ "$target" = multipass ] || ask "kayra (MCP) ${name} changes ${server:-this machine}${target:+ (target ${target})}"
|
|
66
|
+
exit 0
|
|
67
|
+
fi
|
|
68
|
+
|
|
69
|
+
command="$(jq -r '.tool_input.command // empty' <<< "$input" 2>/dev/null)"
|
|
70
|
+
[ -n "$command" ] || exit 0
|
|
47
71
|
has() { grep -qE -- "$1" <<< "$command"; }
|
|
48
72
|
|
|
49
73
|
# ── kayra changing a server ─────────────────────────────────────────────────
|
|
@@ -52,9 +76,7 @@ verbs='(up|provision|setup|deploy|apps|adopt|down|hosts|job|app (purge|deploy|ro
|
|
|
52
76
|
if has "${kayra} +(--[a-z-]+ +)*${verbs}( |$)" && ! has '--dry-run'; then
|
|
53
77
|
# The server: the word after the verb (after the app subcommand for app …).
|
|
54
78
|
server="$(grep -oE -- "${kayra} +(--[a-z-]+ +)*${verbs} +[a-z0-9][a-z0-9-]*" <<< "$command" | head -1 | awk '{print $NF}')"
|
|
55
|
-
target=""
|
|
56
|
-
[ -z "$server" ] || [ ! -f "${project}/servers/${server}/server.yml" ] \
|
|
57
|
-
|| target="$(sed -n 's/^target: *\([a-z]*\).*/\1/p' "${project}/servers/${server}/server.yml")"
|
|
79
|
+
target="$(target_of "$server")"
|
|
58
80
|
[ "$target" = multipass ] || ask "kayra changes ${server:-a server}${target:+ (target ${target})}"
|
|
59
81
|
fi
|
|
60
82
|
# kayra serve runs any command on any server from a browser, where this guard sees none of them.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|