@cavelon/cli 0.0.0 → 0.1.2

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 (61) hide show
  1. package/README.md +713 -3
  2. package/dist/LICENSE +201 -0
  3. package/dist/agents.js +107 -0
  4. package/dist/branches.js +61 -0
  5. package/dist/capacity.js +162 -0
  6. package/dist/cli.js +4 -0
  7. package/dist/command.js +62 -0
  8. package/dist/commands/api.js +313 -0
  9. package/dist/commands/async.js +207 -0
  10. package/dist/commands/docs.js +158 -0
  11. package/dist/commands/index.js +112 -0
  12. package/dist/commands/init.js +481 -0
  13. package/dist/commands/inventory.js +56 -0
  14. package/dist/commands/limits-set.js +633 -0
  15. package/dist/commands/limits.js +156 -0
  16. package/dist/commands/loops.js +798 -0
  17. package/dist/commands/models.js +197 -0
  18. package/dist/commands/sandboxes.js +674 -0
  19. package/dist/commands/session.js +480 -0
  20. package/dist/commands/solution.js +830 -0
  21. package/dist/commands/tenants.js +266 -0
  22. package/dist/commands/values.js +386 -0
  23. package/dist/commands/work.js +761 -0
  24. package/dist/context.js +60 -0
  25. package/dist/contracts.js +234 -0
  26. package/dist/credentials.js +134 -0
  27. package/dist/errors.js +64 -0
  28. package/dist/features.js +52 -0
  29. package/dist/format.js +36 -0
  30. package/dist/fsutil.js +43 -0
  31. package/dist/git.js +41 -0
  32. package/dist/http.js +304 -0
  33. package/dist/invoke.js +165 -0
  34. package/dist/io.js +49 -0
  35. package/dist/limits.js +307 -0
  36. package/dist/local-state.js +78 -0
  37. package/dist/main.js +227 -0
  38. package/dist/markers.js +113 -0
  39. package/dist/mcp.js +137 -0
  40. package/dist/openapi.js +233 -0
  41. package/dist/operations.js +107 -0
  42. package/dist/package-check.js +342 -0
  43. package/dist/package-files.js +394 -0
  44. package/dist/pair-order.js +39 -0
  45. package/dist/paths.js +77 -0
  46. package/dist/principal.js +33 -0
  47. package/dist/project.js +157 -0
  48. package/dist/prompt.js +34 -0
  49. package/dist/results.js +104 -0
  50. package/dist/session.js +190 -0
  51. package/dist/shell.js +41 -0
  52. package/dist/skills/cavelon-authoring/SKILL.md +224 -0
  53. package/dist/skills/cavelon-long-running/SKILL.md +185 -0
  54. package/dist/skills/cavelon-loop/SKILL.md +159 -0
  55. package/dist/skills/cavelon-testing/SKILL.md +97 -0
  56. package/dist/sse.js +44 -0
  57. package/dist/tar.js +172 -0
  58. package/dist/user-config.js +36 -0
  59. package/dist/version.js +17 -0
  60. package/dist/zip.js +132 -0
  61. package/package.json +40 -4
@@ -0,0 +1,113 @@
1
+ const MARKERS = {
2
+ html: { begin: "<!-- cavelon:begin -->", end: "<!-- cavelon:end -->" },
3
+ hash: { begin: "# cavelon:begin", end: "# cavelon:end" },
4
+ };
5
+ export const GENERATED_TOKEN = "cavelon:generated";
6
+ function lineEnding(text) {
7
+ return text.includes("\r\n") ? "\r\n" : "\n";
8
+ }
9
+ function locate(lines, style) {
10
+ const { begin, end } = MARKERS[style];
11
+ const begins = lines.flatMap((line, i) => (line.trim() === begin ? [i] : []));
12
+ const ends = lines.flatMap((line, i) => (line.trim() === end ? [i] : []));
13
+ if (begins.length === 0 && ends.length === 0)
14
+ return undefined;
15
+ if (begins.length !== 1 || ends.length !== 1 || ends[0] < begins[0]) {
16
+ return { error: `its ${begin} … ${end} markers are not one well-formed pair` };
17
+ }
18
+ return { begin: begins[0], end: ends[0] };
19
+ }
20
+ export function upsertBlock(existing, body, style, options = {}) {
21
+ const { begin, end } = MARKERS[style];
22
+ const bodyLines = body.trimEnd().split(/\r?\n/);
23
+ if (existing === undefined) {
24
+ if (options.onlyExisting)
25
+ return { outcome: "skipped", reason: "the file does not exist" };
26
+ return { outcome: "created", content: [begin, ...bodyLines, end].join("\n") + "\n" };
27
+ }
28
+ const eol = lineEnding(existing);
29
+ const lines = existing.split(/\r?\n/);
30
+ const found = locate(lines, style);
31
+ if (found && "error" in found)
32
+ return { outcome: "skipped", reason: found.error };
33
+ if (!found) {
34
+ if (options.onlyExisting)
35
+ return { outcome: "skipped", reason: "it has no cavelon block" };
36
+ if (options.afterShebang && lines[0]?.startsWith("#!")) {
37
+ return { outcome: "appended", content: [lines[0], begin, ...bodyLines, end, ...lines.slice(1)].join(eol) };
38
+ }
39
+ const trimmed = withoutTrailingNewlines(existing);
40
+ const separator = trimmed ? eol + eol : "";
41
+ return { outcome: "appended", content: trimmed + separator + [begin, ...bodyLines, end].join(eol) + eol };
42
+ }
43
+ const next = [...lines.slice(0, found.begin + 1), ...bodyLines, ...lines.slice(found.end)].join(eol);
44
+ return next === existing ? { outcome: "unchanged" } : { outcome: "updated", content: next };
45
+ }
46
+ export function isGenerated(content) {
47
+ return content !== undefined && content.includes(GENERATED_TOKEN);
48
+ }
49
+ export function upsertJsonEntry(existing, keys, value) {
50
+ if (existing === undefined || existing.trim() === "") {
51
+ const root = {};
52
+ setPath(root, keys, value);
53
+ return { outcome: "created", content: JSON.stringify(root, null, 2) + "\n" };
54
+ }
55
+ let parsed;
56
+ try {
57
+ parsed = JSON.parse(existing);
58
+ }
59
+ catch {
60
+ return { outcome: "skipped", reason: "it is not plain JSON (comments or a syntax error)" };
61
+ }
62
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
63
+ return { outcome: "skipped", reason: "it is not a JSON object" };
64
+ }
65
+ const indent = detectIndent(existing);
66
+ const eol = lineEnding(existing);
67
+ const serialize = (v) => {
68
+ const text = JSON.stringify(v, null, indent).replace(/\n/g, eol);
69
+ return /\r?\n$/.test(existing) ? text + eol : text;
70
+ };
71
+ if (serialize(parsed) !== existing) {
72
+ return { outcome: "skipped", reason: "rewriting it would change its formatting" };
73
+ }
74
+ const current = getPath(parsed, keys);
75
+ if (current !== undefined && JSON.stringify(current) === JSON.stringify(value))
76
+ return { outcome: "unchanged" };
77
+ const parent = getPath(parsed, keys.slice(0, -1));
78
+ if (parent !== undefined && (typeof parent !== "object" || parent === null || Array.isArray(parent))) {
79
+ return { outcome: "skipped", reason: `its "${keys.slice(0, -1).join(".")}" is not an object` };
80
+ }
81
+ setPath(parsed, keys, value);
82
+ return { outcome: current === undefined ? "appended" : "updated", content: serialize(parsed) };
83
+ }
84
+ function detectIndent(text) {
85
+ const match = /^\{\r?\n([ \t]+)"/.exec(text);
86
+ if (!match)
87
+ return 2;
88
+ return match[1].includes("\t") ? "\t" : match[1].length;
89
+ }
90
+ function getPath(root, keys) {
91
+ let node = root;
92
+ for (const key of keys) {
93
+ if (!node || typeof node !== "object" || Array.isArray(node))
94
+ return undefined;
95
+ node = node[key];
96
+ }
97
+ return node;
98
+ }
99
+ function setPath(root, keys, value) {
100
+ let node = root;
101
+ for (const key of keys.slice(0, -1)) {
102
+ if (!node[key] || typeof node[key] !== "object")
103
+ node[key] = {};
104
+ node = node[key];
105
+ }
106
+ node[keys[keys.length - 1]] = value;
107
+ }
108
+ function withoutTrailingNewlines(text) {
109
+ let end = text.length;
110
+ while (end > 0 && text[end - 1] === "\n")
111
+ end -= text[end - 2] === "\r" ? 2 : 1;
112
+ return text.slice(0, end);
113
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,137 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
+ import { createContext, withWarnings } from "./context.js";
4
+ import { asCavelonError, usageError } from "./errors.js";
5
+ import { KIT_VERSION } from "./version.js";
6
+ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a person stored with `cavelon login` " +
7
+ "(or CAVELON_TOKEN). You never see or pass the token. Tools that start work (kb_upload, test_run, " +
8
+ "loop_start, sandbox_seed, artifacts_export) return operation ids at once; read them with operation_status, " +
9
+ "and follow a loop with loop_iterations. What needs confirmation: apply imports only with confirm set to a preview's id; " +
10
+ "limits_set, models_set_limit, loop_cancel, sandbox_seed, trigger_identity, and api for an operation that is not read-only, " +
11
+ "return what they would do and change nothing without confirm: true; show the person that first. " +
12
+ "init and pull write files in the solution folder without confirm (pull refuses to replace package files with uncommitted changes unless force), " +
13
+ "and the other changing tools act at once. api refuses, even with confirm, an operation the instance marks for a person " +
14
+ "(x-cavelon-person-only; its reason is in the error), or on an instance that marks none, one that changes a secret, " +
15
+ "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval. Tools read and write files only " +
16
+ "inside the solution folder (the folder of cavelon.yaml, or the one the server started in), never in cavelon's own " +
17
+ "config or cache directory. Read limits before planning a solution: it lists what the " +
18
+ "instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
19
+ "Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
20
+ "models_set_limit for an endpoint's max_concurrent_requests) and let the person decide; an operator's limit goes to the operator. " +
21
+ "variables_list/variables_get/variables_set handle plain-text {{var:…}} values. secrets_list shows which {{secret:…}} " +
22
+ "values are set, never a value: a person sets a secret, so tell them the exact `cavelon secrets set <name>` command " +
23
+ "to run in their terminal, and never ask for, read or pass a secret value. Never approve or decide an approval; " +
24
+ "that stays with a person. Use docs_search before guessing, " +
25
+ "and api_list/api_describe/api for anything without its own tool.";
26
+ export function toolName(spec) {
27
+ return spec.mcpTool || undefined;
28
+ }
29
+ function ownsTenant(spec) {
30
+ return Boolean(spec.positionals?.some((p) => p.name === "tenant") || spec.options?.tenant);
31
+ }
32
+ export function inputSchema(spec) {
33
+ const properties = {};
34
+ const required = [];
35
+ for (const p of spec.positionals ?? []) {
36
+ properties[p.name] = p.variadic
37
+ ? { type: "array", items: { type: "string" }, description: p.description }
38
+ : { type: "string", description: p.description };
39
+ if (p.required)
40
+ required.push(p.name);
41
+ }
42
+ for (const [name, option] of Object.entries(spec.options ?? {})) {
43
+ if (option.cliOnly)
44
+ continue;
45
+ properties[name] =
46
+ option.type === "boolean"
47
+ ? { type: "boolean", description: option.description }
48
+ : option.multiple
49
+ ? { type: "array", items: { type: "string" }, description: option.description }
50
+ : { type: ["string", "number"], description: option.description };
51
+ }
52
+ if (!ownsTenant(spec)) {
53
+ properties.tenant = { type: "string", description: "Tenant slug or id, when not the one chosen for this directory." };
54
+ }
55
+ return { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false };
56
+ }
57
+ export function toolFor(spec) {
58
+ const marked = spec.readOnly ? "Read-only." : spec.destructive ? "Changes the instance; may delete or overwrite." : "Changes the instance.";
59
+ return {
60
+ name: toolName(spec),
61
+ description: [spec.summary, spec.description, marked].filter(Boolean).join("\n"),
62
+ inputSchema: inputSchema(spec),
63
+ annotations: {
64
+ title: spec.summary,
65
+ readOnlyHint: spec.readOnly,
66
+ destructiveHint: !spec.readOnly && Boolean(spec.destructive),
67
+ idempotentHint: Boolean(spec.idempotent),
68
+ openWorldHint: true,
69
+ },
70
+ };
71
+ }
72
+ function inputFrom(spec, args) {
73
+ const input = { positionals: {}, options: {} };
74
+ for (const p of spec.positionals ?? []) {
75
+ const value = args[p.name];
76
+ if (value === undefined || value === null)
77
+ continue;
78
+ input.positionals[p.name] = p.variadic ? (Array.isArray(value) ? value.map(String) : [String(value)]) : String(value);
79
+ }
80
+ for (const [name, option] of Object.entries(spec.options ?? {})) {
81
+ if (option.cliOnly)
82
+ continue;
83
+ const value = args[name];
84
+ if (value === undefined || value === null)
85
+ continue;
86
+ if (option.type === "boolean")
87
+ input.options[name] = value === true || value === "true";
88
+ else if (option.multiple)
89
+ input.options[name] = Array.isArray(value) ? value.map(String) : [String(value)];
90
+ else
91
+ input.options[name] = String(value);
92
+ }
93
+ return input;
94
+ }
95
+ function missingRequired(spec, args) {
96
+ return (spec.positionals ?? []).filter((p) => p.required && (args[p.name] === undefined || args[p.name] === "")).map((p) => p.name);
97
+ }
98
+ function mcpIo(io) {
99
+ return { ...io, stdout: { write: () => true, isTTY: false } };
100
+ }
101
+ export function createMcpServer(io, commands) {
102
+ const tools = commands.filter((c) => c.mcpTool);
103
+ const byName = new Map(tools.map((c) => [toolName(c), c]));
104
+ const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
105
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map(toolFor) }));
106
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
107
+ const spec = byName.get(request.params.name);
108
+ const args = (request.params.arguments ?? {});
109
+ const fail = (error) => ({
110
+ isError: true,
111
+ content: [{ type: "text", text: JSON.stringify({ error: asCavelonError(error).toJSON() }) }],
112
+ });
113
+ if (!spec)
114
+ return fail(new Error(`Unknown tool ${request.params.name}.`));
115
+ const missing = missingRequired(spec, args);
116
+ if (missing.length) {
117
+ return fail(usageError(`Missing ${missing.join(", ")}.`));
118
+ }
119
+ const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
120
+ const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
121
+ const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv }, "mcp");
122
+ try {
123
+ const result = await spec.run(ctx, inputFrom(spec, args));
124
+ let data = result.data;
125
+ if (data && typeof data === "object" && !Array.isArray(data)) {
126
+ data = ctx.warnings.length ? withWarnings(data, ctx.warnings) : { ...data };
127
+ if (result.exitCode)
128
+ data.exit_code = result.exitCode;
129
+ }
130
+ return { content: [{ type: "text", text: JSON.stringify(data ?? null) }] };
131
+ }
132
+ catch (error) {
133
+ return fail(error);
134
+ }
135
+ });
136
+ return server;
137
+ }
@@ -0,0 +1,233 @@
1
+ import { Ajv2020 } from "ajv/dist/2020.js";
2
+ import addFormatsModule from "ajv-formats";
3
+ import { CavelonError, ExitCode, validationError } from "./errors.js";
4
+ const METHODS = ["get", "put", "post", "delete", "patch", "head", "options"];
5
+ export function aliasOf(operationId, path, method) {
6
+ const suffix = `${path.replace(/\W/g, "_")}_${method.toLowerCase()}`;
7
+ if (operationId.endsWith(suffix) && operationId.length > suffix.length)
8
+ return operationId.slice(0, -suffix.length);
9
+ return operationId;
10
+ }
11
+ const indexCache = new WeakMap();
12
+ export function operations(doc) {
13
+ const cached = indexCache.get(doc);
14
+ if (cached)
15
+ return cached;
16
+ const out = [];
17
+ for (const [path, item] of Object.entries(doc.paths ?? {})) {
18
+ const shared = (item.parameters ?? []).map((p) => deref(doc, p));
19
+ for (const method of METHODS) {
20
+ const raw = item[method];
21
+ if (!raw)
22
+ continue;
23
+ const operationId = raw.operationId ?? `${method}_${path}`;
24
+ const own = (raw.parameters ?? []).map((p) => deref(doc, p));
25
+ const byKey = new Map();
26
+ for (const p of [...shared, ...own])
27
+ byKey.set(`${p.in}:${p.name}`, p);
28
+ out.push({
29
+ operationId,
30
+ alias: aliasOf(operationId, path, method),
31
+ method: method.toUpperCase(),
32
+ path,
33
+ tags: raw.tags ?? [],
34
+ summary: raw.summary,
35
+ description: raw.description,
36
+ deprecated: raw.deprecated,
37
+ parameters: [...byKey.values()],
38
+ requestBody: raw.requestBody ? deref(doc, raw.requestBody) : undefined,
39
+ responses: raw.responses ?? {},
40
+ readOnly: method === "get" || method === "head" || method === "options",
41
+ personOnly: personOnlyOf(raw),
42
+ });
43
+ }
44
+ }
45
+ indexCache.set(doc, out);
46
+ return out;
47
+ }
48
+ function personOnlyOf(raw) {
49
+ if (!("x-cavelon-person-only" in raw))
50
+ return undefined;
51
+ const reason = raw["x-cavelon-person-only-reason"];
52
+ return {
53
+ marked: raw["x-cavelon-person-only"] === true,
54
+ ...(typeof reason === "string" && reason.trim() ? { reason: reason.trim() } : {}),
55
+ };
56
+ }
57
+ export function deref(doc, value) {
58
+ let current = value;
59
+ for (let i = 0; i < 10 && current && typeof current === "object" && typeof current.$ref === "string"; i++) {
60
+ const ref = current.$ref;
61
+ if (!ref.startsWith("#/"))
62
+ break;
63
+ current = ref
64
+ .slice(2)
65
+ .split("/")
66
+ .reduce((node, key) => node?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], doc);
67
+ }
68
+ return current;
69
+ }
70
+ export function findOperation(doc, name) {
71
+ const all = operations(doc);
72
+ const exact = all.find((o) => o.operationId === name);
73
+ if (exact)
74
+ return exact;
75
+ const byAlias = all.filter((o) => o.alias === name);
76
+ if (byAlias.length === 1)
77
+ return byAlias[0];
78
+ if (byAlias.length > 1) {
79
+ throw new CavelonError(ExitCode.usage, {
80
+ code: "operation_ambiguous",
81
+ message: `"${name}" names ${byAlias.length} operations.`,
82
+ hint: `Use the full operationId: ${byAlias.map((o) => o.operationId).join(", ")}`,
83
+ });
84
+ }
85
+ const needle = name.toLowerCase();
86
+ const similar = all
87
+ .filter((o) => o.alias.toLowerCase().includes(needle) || needle.includes(o.alias.toLowerCase()))
88
+ .slice(0, 5)
89
+ .map((o) => o.alias);
90
+ throw new CavelonError(ExitCode.usage, {
91
+ code: "operation_not_found",
92
+ message: `This instance publishes no operation "${name}".`,
93
+ hint: similar.length ? `Did you mean: ${similar.join(", ")}? (\`cavelon api list --search <text>\`)` : "Find it with `cavelon api list --search <text>`.",
94
+ });
95
+ }
96
+ export function operationAt(doc, method, path) {
97
+ return operations(doc).find((o) => o.method === method.toUpperCase() && o.path === path);
98
+ }
99
+ export function operationForPath(doc, method, path) {
100
+ const exact = operationAt(doc, method, path);
101
+ if (exact)
102
+ return { op: exact, fixed: {} };
103
+ const wanted = path.split("/");
104
+ for (const op of operations(doc)) {
105
+ if (op.method !== method.toUpperCase())
106
+ continue;
107
+ const parts = op.path.split("/");
108
+ if (parts.length !== wanted.length)
109
+ continue;
110
+ const fixed = {};
111
+ const fits = parts.every((part, i) => {
112
+ const given = wanted[i];
113
+ if (part === given)
114
+ return true;
115
+ const isParam = part.startsWith("{") && part.endsWith("}");
116
+ if (!isParam || !given || given.includes("{") || given.includes("}"))
117
+ return false;
118
+ fixed[part.slice(1, -1)] = [decodeURIComponent(given)];
119
+ return true;
120
+ });
121
+ if (fits)
122
+ return { op, fixed };
123
+ }
124
+ return undefined;
125
+ }
126
+ const ajvCache = new WeakMap();
127
+ const validatorCache = new WeakMap();
128
+ const addFormats = addFormatsModule.default ?? addFormatsModule;
129
+ function ajvFor(doc) {
130
+ let ajv = ajvCache.get(doc);
131
+ if (!ajv) {
132
+ ajv = new Ajv2020({ strict: false, allErrors: true, validateSchema: false, validateFormats: true });
133
+ addFormats(ajv);
134
+ ajv.addSchema({ $id: "cavelon:openapi", components: doc.components ?? {} });
135
+ ajvCache.set(doc, ajv);
136
+ }
137
+ return ajv;
138
+ }
139
+ function rebase(schema) {
140
+ if (Array.isArray(schema))
141
+ return schema.map(rebase);
142
+ if (schema && typeof schema === "object") {
143
+ return Object.fromEntries(Object.entries(schema).map(([k, v]) => [k, k === "$ref" && typeof v === "string" && v.startsWith("#/") ? `cavelon:openapi${v}` : rebase(v)]));
144
+ }
145
+ return schema;
146
+ }
147
+ export function validatorFor(doc, schema) {
148
+ let validate = validatorCache.get(schema);
149
+ if (!validate) {
150
+ validate = ajvFor(doc).compile(rebase(schema));
151
+ validatorCache.set(schema, validate);
152
+ }
153
+ return validate;
154
+ }
155
+ export function schemaErrors(doc, schema, value) {
156
+ const validate = validatorFor(doc, schema);
157
+ if (validate(value))
158
+ return [];
159
+ return (validate.errors ?? []).slice(0, 10).map((e) => {
160
+ const where = e.instancePath || "(body)";
161
+ const extra = e.keyword === "additionalProperties" ? ` "${e.params.additionalProperty}"` : "";
162
+ return `${where} ${e.message ?? "is invalid"}${extra}`;
163
+ });
164
+ }
165
+ export function jsonBodySchema(op) {
166
+ return op.requestBody?.content?.["application/json"]?.schema;
167
+ }
168
+ export function validateBody(doc, op, body) {
169
+ const schema = jsonBodySchema(op);
170
+ if (!schema)
171
+ return;
172
+ const errors = schemaErrors(doc, schema, body);
173
+ if (errors.length) {
174
+ throw validationError(`The body does not match ${op.alias}'s schema: ${errors.join("; ")}`, errors, `See \`cavelon api describe ${op.alias}\`.`);
175
+ }
176
+ }
177
+ export function coerceParameter(param, raw) {
178
+ const types = schemaTypes(param.schema);
179
+ if (types.includes("integer") && /^-?\d+$/.test(raw))
180
+ return Number(raw);
181
+ if (types.includes("number") && raw.trim() !== "" && !Number.isNaN(Number(raw)))
182
+ return Number(raw);
183
+ if (types.includes("boolean") && (raw === "true" || raw === "false"))
184
+ return raw === "true";
185
+ return raw;
186
+ }
187
+ export function schemaTypes(schema) {
188
+ if (!schema)
189
+ return [];
190
+ const out = [];
191
+ if (typeof schema.type === "string")
192
+ out.push(schema.type);
193
+ if (Array.isArray(schema.type))
194
+ out.push(...schema.type);
195
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
196
+ for (const sub of schema[key] ?? [])
197
+ out.push(...schemaTypes(sub));
198
+ }
199
+ return out;
200
+ }
201
+ export function isArrayParameter(param) {
202
+ return schemaTypes(param.schema).includes("array");
203
+ }
204
+ export function describeSchema(doc, schema) {
205
+ if (!schema)
206
+ return null;
207
+ const resolved = deref(doc, schema);
208
+ const props = resolved.properties;
209
+ const ref = typeof schema.$ref === "string" ? schema.$ref.split("/").pop() : undefined;
210
+ if (!props) {
211
+ if (resolved.type === "array" && resolved.items)
212
+ return { type: "array", items: describeSchema(doc, resolved.items) };
213
+ return { ...(ref ? { name: ref } : {}), type: resolved.type ?? (schemaTypes(resolved).join("|") || "any") };
214
+ }
215
+ const required = new Set(resolved.required ?? []);
216
+ return {
217
+ ...(ref ? { name: ref } : {}),
218
+ type: "object",
219
+ fields: Object.fromEntries(Object.entries(props).map(([name, p]) => {
220
+ const sub = deref(doc, p);
221
+ const subRef = typeof p.$ref === "string" ? p.$ref.split("/").pop() : undefined;
222
+ const type = subRef ?? (schemaTypes(sub).filter((t) => t !== "null").join("|") || "object");
223
+ const parts = [type];
224
+ if (required.has(name))
225
+ parts.push("required");
226
+ if (Array.isArray(sub.enum))
227
+ parts.push(`one of ${sub.enum.join(", ")}`);
228
+ if (sub.default !== undefined)
229
+ parts.push(`default ${JSON.stringify(sub.default)}`);
230
+ return [name, parts.join(", ")];
231
+ })),
232
+ };
233
+ }
@@ -0,0 +1,107 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
2
+ import { failureLines } from "./results.js";
3
+ export const TERMINAL = new Set(["succeeded", "failed", "cancelled"]);
4
+ export function isSettled(op) {
5
+ return TERMINAL.has(op.status) || op.status === "needs_action";
6
+ }
7
+ export function exitCodeFor(op, note) {
8
+ if (note?.result_failure)
9
+ return note.result_failure.exit_code;
10
+ switch (op.status) {
11
+ case "succeeded":
12
+ return ExitCode.ok;
13
+ case "needs_action":
14
+ return ExitCode.needsAction;
15
+ case "failed":
16
+ case "cancelled":
17
+ return ExitCode.failure;
18
+ default:
19
+ return ExitCode.timeout;
20
+ }
21
+ }
22
+ export function combinedExitCode(ops, notes = []) {
23
+ const codes = new Set(ops.map((op, i) => exitCodeFor(op, notes[i])));
24
+ for (const code of [ExitCode.failure, ExitCode.needsAction, ExitCode.timeout])
25
+ if (codes.has(code))
26
+ return code;
27
+ return ExitCode.ok;
28
+ }
29
+ function operationsUnavailable() {
30
+ return new CavelonError(ExitCode.failure, {
31
+ code: "operations_unavailable",
32
+ message: "This instance does not offer the operations API (/api/v1/operations).",
33
+ hint: "It is turned on with OPERATIONS_API_ENABLED on the instance; ask its operator.",
34
+ });
35
+ }
36
+ export async function getOperation(client, id, signal) {
37
+ try {
38
+ const response = await client.get(`/api/v1/operations/${encodeURIComponent(id)}`, { signal });
39
+ return response.data;
40
+ }
41
+ catch (error) {
42
+ if (error instanceof CavelonError && error.status === 404) {
43
+ if (!id.startsWith("op_")) {
44
+ throw new CavelonError(ExitCode.usage, {
45
+ code: "not_an_operation_id",
46
+ message: `"${id}" is not an operation id (they start with op_).`,
47
+ hint: "Commands that start work print the operation id; `cavelon status` lists running ones.",
48
+ });
49
+ }
50
+ const probe = await client.get("/api/v1/operations", { query: { limit: 1 }, allow: [404] });
51
+ if (probe.status === 404)
52
+ throw operationsUnavailable();
53
+ throw new CavelonError(ExitCode.failure, {
54
+ code: "operation_not_found",
55
+ status: 404,
56
+ message: `No operation ${id} in this tenant.`,
57
+ hint: "Operation ids are per tenant; check `cavelon whoami`.",
58
+ });
59
+ }
60
+ throw error;
61
+ }
62
+ }
63
+ export async function waitFor(ctx, client, ids, options) {
64
+ const deadline = Date.now() + options.timeoutMs;
65
+ const latest = new Map();
66
+ let interval = options.intervalMs;
67
+ for (;;) {
68
+ for (const id of ids) {
69
+ const previous = latest.get(id);
70
+ if (previous && isSettled(previous))
71
+ continue;
72
+ const remaining = Math.max(1000, deadline - Date.now());
73
+ const op = await getOperation(client, id, AbortSignal.timeout(Math.min(remaining, 30_000)));
74
+ if (!previous || previous.status !== op.status || previous.progress?.current !== op.progress?.current)
75
+ options.onChange?.(op);
76
+ latest.set(id, op);
77
+ }
78
+ const ops = ids.map((id) => latest.get(id));
79
+ if (ops.every(isSettled))
80
+ return { operations: ops, timedOut: false };
81
+ const left = deadline - Date.now();
82
+ if (left <= 0)
83
+ return { operations: ops, timedOut: true };
84
+ await ctx.io.sleep(Math.min(interval, left));
85
+ interval = Math.min(Math.round(interval * 1.5), 5000);
86
+ }
87
+ }
88
+ export function describe(op, note) {
89
+ const progress = op.progress;
90
+ const parts = [`${op.id} ${op.kind} ${op.status}`];
91
+ if (progress?.phase)
92
+ parts.push(`phase ${progress.phase}`);
93
+ if (progress?.current != null && progress?.total != null)
94
+ parts.push(`${progress.current}/${progress.total}`);
95
+ let line = parts.join(" ");
96
+ if (note?.capacity_wait)
97
+ line += `\n ${note.capacity_wait.note}`;
98
+ if (op.error)
99
+ line += `\n error ${op.error.code}: ${op.error.message}`;
100
+ if (note?.capacity_refusal)
101
+ line += `\n ${note.capacity_refusal.code}: ${note.capacity_refusal.hint}`;
102
+ if (note?.result_failure)
103
+ line += `\n${failureLines(note.result_failure)}`;
104
+ if (op.action)
105
+ line += `\n needs a person: ${op.action.reason}\n ${op.action.admin_url}`;
106
+ return line;
107
+ }