@cavelon/cli 0.0.0 → 0.1.1
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 +697 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +91 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +243 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +452 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +624 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +792 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +667 -0
- package/dist/commands/session.js +476 -0
- package/dist/commands/solution.js +760 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +383 -0
- package/dist/commands/work.js +744 -0
- package/dist/context.js +56 -0
- package/dist/contracts.js +189 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +37 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +40 -0
- package/dist/git.js +41 -0
- package/dist/http.js +286 -0
- package/dist/invoke.js +161 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +299 -0
- package/dist/local-state.js +60 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +130 -0
- package/dist/openapi.js +223 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +329 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +28 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +138 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +66 -0
- package/dist/session.js +166 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +214 -0
- package/dist/skills/cavelon-long-running/SKILL.md +181 -0
- package/dist/skills/cavelon-loop/SKILL.md +158 -0
- package/dist/skills/cavelon-testing/SKILL.md +90 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
package/dist/markers.js
ADDED
|
@@ -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,130 @@
|
|
|
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. Tools marked destructive change nothing without confirm: true; " +
|
|
10
|
+
"show the person what they would do first. Read limits before planning a solution: it lists what the " +
|
|
11
|
+
"instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
|
|
12
|
+
"Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
|
|
13
|
+
"models_set_limit for an endpoint's max_concurrent_requests) and let the person decide; an operator's limit goes to the operator. " +
|
|
14
|
+
"variables_list/variables_get/variables_set handle plain-text {{var:…}} values. secrets_list shows which {{secret:…}} " +
|
|
15
|
+
"values are set, never a value: a person sets a secret, so tell them the exact `cavelon secrets set <name>` command " +
|
|
16
|
+
"to run in their terminal, and never ask for, read or pass a secret value. Never approve or decide an approval; " +
|
|
17
|
+
"that stays with a person. Use docs_search before guessing, " +
|
|
18
|
+
"and api_list/api_describe/api for anything without its own tool.";
|
|
19
|
+
export function toolName(spec) {
|
|
20
|
+
return spec.mcpTool || undefined;
|
|
21
|
+
}
|
|
22
|
+
function ownsTenant(spec) {
|
|
23
|
+
return Boolean(spec.positionals?.some((p) => p.name === "tenant") || spec.options?.tenant);
|
|
24
|
+
}
|
|
25
|
+
export function inputSchema(spec) {
|
|
26
|
+
const properties = {};
|
|
27
|
+
const required = [];
|
|
28
|
+
for (const p of spec.positionals ?? []) {
|
|
29
|
+
properties[p.name] = p.variadic
|
|
30
|
+
? { type: "array", items: { type: "string" }, description: p.description }
|
|
31
|
+
: { type: "string", description: p.description };
|
|
32
|
+
if (p.required)
|
|
33
|
+
required.push(p.name);
|
|
34
|
+
}
|
|
35
|
+
for (const [name, option] of Object.entries(spec.options ?? {})) {
|
|
36
|
+
if (option.cliOnly)
|
|
37
|
+
continue;
|
|
38
|
+
properties[name] =
|
|
39
|
+
option.type === "boolean"
|
|
40
|
+
? { type: "boolean", description: option.description }
|
|
41
|
+
: option.multiple
|
|
42
|
+
? { type: "array", items: { type: "string" }, description: option.description }
|
|
43
|
+
: { type: ["string", "number"], description: option.description };
|
|
44
|
+
}
|
|
45
|
+
if (!ownsTenant(spec)) {
|
|
46
|
+
properties.tenant = { type: "string", description: "Tenant slug or id, when not the one chosen for this directory." };
|
|
47
|
+
}
|
|
48
|
+
return { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false };
|
|
49
|
+
}
|
|
50
|
+
export function toolFor(spec) {
|
|
51
|
+
const marked = spec.readOnly ? "Read-only." : spec.destructive ? "Changes the instance; may delete or overwrite." : "Changes the instance.";
|
|
52
|
+
return {
|
|
53
|
+
name: toolName(spec),
|
|
54
|
+
description: [spec.summary, spec.description, marked].filter(Boolean).join("\n"),
|
|
55
|
+
inputSchema: inputSchema(spec),
|
|
56
|
+
annotations: {
|
|
57
|
+
title: spec.summary,
|
|
58
|
+
readOnlyHint: spec.readOnly,
|
|
59
|
+
destructiveHint: !spec.readOnly && Boolean(spec.destructive),
|
|
60
|
+
idempotentHint: Boolean(spec.idempotent),
|
|
61
|
+
openWorldHint: true,
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function inputFrom(spec, args) {
|
|
66
|
+
const input = { positionals: {}, options: {} };
|
|
67
|
+
for (const p of spec.positionals ?? []) {
|
|
68
|
+
const value = args[p.name];
|
|
69
|
+
if (value === undefined || value === null)
|
|
70
|
+
continue;
|
|
71
|
+
input.positionals[p.name] = p.variadic ? (Array.isArray(value) ? value.map(String) : [String(value)]) : String(value);
|
|
72
|
+
}
|
|
73
|
+
for (const [name, option] of Object.entries(spec.options ?? {})) {
|
|
74
|
+
if (option.cliOnly)
|
|
75
|
+
continue;
|
|
76
|
+
const value = args[name];
|
|
77
|
+
if (value === undefined || value === null)
|
|
78
|
+
continue;
|
|
79
|
+
if (option.type === "boolean")
|
|
80
|
+
input.options[name] = value === true || value === "true";
|
|
81
|
+
else if (option.multiple)
|
|
82
|
+
input.options[name] = Array.isArray(value) ? value.map(String) : [String(value)];
|
|
83
|
+
else
|
|
84
|
+
input.options[name] = String(value);
|
|
85
|
+
}
|
|
86
|
+
return input;
|
|
87
|
+
}
|
|
88
|
+
function missingRequired(spec, args) {
|
|
89
|
+
return (spec.positionals ?? []).filter((p) => p.required && (args[p.name] === undefined || args[p.name] === "")).map((p) => p.name);
|
|
90
|
+
}
|
|
91
|
+
function mcpIo(io) {
|
|
92
|
+
return { ...io, stdout: { write: () => true, isTTY: false } };
|
|
93
|
+
}
|
|
94
|
+
export function createMcpServer(io, commands) {
|
|
95
|
+
const tools = commands.filter((c) => c.mcpTool);
|
|
96
|
+
const byName = new Map(tools.map((c) => [toolName(c), c]));
|
|
97
|
+
const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
98
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map(toolFor) }));
|
|
99
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
100
|
+
const spec = byName.get(request.params.name);
|
|
101
|
+
const args = (request.params.arguments ?? {});
|
|
102
|
+
const fail = (error) => ({
|
|
103
|
+
isError: true,
|
|
104
|
+
content: [{ type: "text", text: JSON.stringify({ error: asCavelonError(error).toJSON() }) }],
|
|
105
|
+
});
|
|
106
|
+
if (!spec)
|
|
107
|
+
return fail(new Error(`Unknown tool ${request.params.name}.`));
|
|
108
|
+
const missing = missingRequired(spec, args);
|
|
109
|
+
if (missing.length) {
|
|
110
|
+
return fail(usageError(`Missing ${missing.join(", ")}.`));
|
|
111
|
+
}
|
|
112
|
+
const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
|
|
113
|
+
const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
|
|
114
|
+
const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv }, "mcp");
|
|
115
|
+
try {
|
|
116
|
+
const result = await spec.run(ctx, inputFrom(spec, args));
|
|
117
|
+
let data = result.data;
|
|
118
|
+
if (data && typeof data === "object" && !Array.isArray(data)) {
|
|
119
|
+
data = ctx.warnings.length ? withWarnings(data, ctx.warnings) : { ...data };
|
|
120
|
+
if (result.exitCode)
|
|
121
|
+
data.exit_code = result.exitCode;
|
|
122
|
+
}
|
|
123
|
+
return { content: [{ type: "text", text: JSON.stringify(data ?? null) }] };
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
return fail(error);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
return server;
|
|
130
|
+
}
|
package/dist/openapi.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
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
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
indexCache.set(doc, out);
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
export function deref(doc, value) {
|
|
48
|
+
let current = value;
|
|
49
|
+
for (let i = 0; i < 10 && current && typeof current === "object" && typeof current.$ref === "string"; i++) {
|
|
50
|
+
const ref = current.$ref;
|
|
51
|
+
if (!ref.startsWith("#/"))
|
|
52
|
+
break;
|
|
53
|
+
current = ref
|
|
54
|
+
.slice(2)
|
|
55
|
+
.split("/")
|
|
56
|
+
.reduce((node, key) => node?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], doc);
|
|
57
|
+
}
|
|
58
|
+
return current;
|
|
59
|
+
}
|
|
60
|
+
export function findOperation(doc, name) {
|
|
61
|
+
const all = operations(doc);
|
|
62
|
+
const exact = all.find((o) => o.operationId === name);
|
|
63
|
+
if (exact)
|
|
64
|
+
return exact;
|
|
65
|
+
const byAlias = all.filter((o) => o.alias === name);
|
|
66
|
+
if (byAlias.length === 1)
|
|
67
|
+
return byAlias[0];
|
|
68
|
+
if (byAlias.length > 1) {
|
|
69
|
+
throw new CavelonError(ExitCode.usage, {
|
|
70
|
+
code: "operation_ambiguous",
|
|
71
|
+
message: `"${name}" names ${byAlias.length} operations.`,
|
|
72
|
+
hint: `Use the full operationId: ${byAlias.map((o) => o.operationId).join(", ")}`,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const needle = name.toLowerCase();
|
|
76
|
+
const similar = all
|
|
77
|
+
.filter((o) => o.alias.toLowerCase().includes(needle) || needle.includes(o.alias.toLowerCase()))
|
|
78
|
+
.slice(0, 5)
|
|
79
|
+
.map((o) => o.alias);
|
|
80
|
+
throw new CavelonError(ExitCode.usage, {
|
|
81
|
+
code: "operation_not_found",
|
|
82
|
+
message: `This instance publishes no operation "${name}".`,
|
|
83
|
+
hint: similar.length ? `Did you mean: ${similar.join(", ")}? (\`cavelon api list --search <text>\`)` : "Find it with `cavelon api list --search <text>`.",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
export function operationAt(doc, method, path) {
|
|
87
|
+
return operations(doc).find((o) => o.method === method.toUpperCase() && o.path === path);
|
|
88
|
+
}
|
|
89
|
+
export function operationForPath(doc, method, path) {
|
|
90
|
+
const exact = operationAt(doc, method, path);
|
|
91
|
+
if (exact)
|
|
92
|
+
return { op: exact, fixed: {} };
|
|
93
|
+
const wanted = path.split("/");
|
|
94
|
+
for (const op of operations(doc)) {
|
|
95
|
+
if (op.method !== method.toUpperCase())
|
|
96
|
+
continue;
|
|
97
|
+
const parts = op.path.split("/");
|
|
98
|
+
if (parts.length !== wanted.length)
|
|
99
|
+
continue;
|
|
100
|
+
const fixed = {};
|
|
101
|
+
const fits = parts.every((part, i) => {
|
|
102
|
+
const given = wanted[i];
|
|
103
|
+
if (part === given)
|
|
104
|
+
return true;
|
|
105
|
+
const isParam = part.startsWith("{") && part.endsWith("}");
|
|
106
|
+
if (!isParam || !given || given.includes("{") || given.includes("}"))
|
|
107
|
+
return false;
|
|
108
|
+
fixed[part.slice(1, -1)] = [decodeURIComponent(given)];
|
|
109
|
+
return true;
|
|
110
|
+
});
|
|
111
|
+
if (fits)
|
|
112
|
+
return { op, fixed };
|
|
113
|
+
}
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
const ajvCache = new WeakMap();
|
|
117
|
+
const validatorCache = new WeakMap();
|
|
118
|
+
const addFormats = addFormatsModule.default ?? addFormatsModule;
|
|
119
|
+
function ajvFor(doc) {
|
|
120
|
+
let ajv = ajvCache.get(doc);
|
|
121
|
+
if (!ajv) {
|
|
122
|
+
ajv = new Ajv2020({ strict: false, allErrors: true, validateSchema: false, validateFormats: true });
|
|
123
|
+
addFormats(ajv);
|
|
124
|
+
ajv.addSchema({ $id: "cavelon:openapi", components: doc.components ?? {} });
|
|
125
|
+
ajvCache.set(doc, ajv);
|
|
126
|
+
}
|
|
127
|
+
return ajv;
|
|
128
|
+
}
|
|
129
|
+
function rebase(schema) {
|
|
130
|
+
if (Array.isArray(schema))
|
|
131
|
+
return schema.map(rebase);
|
|
132
|
+
if (schema && typeof schema === "object") {
|
|
133
|
+
return Object.fromEntries(Object.entries(schema).map(([k, v]) => [k, k === "$ref" && typeof v === "string" && v.startsWith("#/") ? `cavelon:openapi${v}` : rebase(v)]));
|
|
134
|
+
}
|
|
135
|
+
return schema;
|
|
136
|
+
}
|
|
137
|
+
export function validatorFor(doc, schema) {
|
|
138
|
+
let validate = validatorCache.get(schema);
|
|
139
|
+
if (!validate) {
|
|
140
|
+
validate = ajvFor(doc).compile(rebase(schema));
|
|
141
|
+
validatorCache.set(schema, validate);
|
|
142
|
+
}
|
|
143
|
+
return validate;
|
|
144
|
+
}
|
|
145
|
+
export function schemaErrors(doc, schema, value) {
|
|
146
|
+
const validate = validatorFor(doc, schema);
|
|
147
|
+
if (validate(value))
|
|
148
|
+
return [];
|
|
149
|
+
return (validate.errors ?? []).slice(0, 10).map((e) => {
|
|
150
|
+
const where = e.instancePath || "(body)";
|
|
151
|
+
const extra = e.keyword === "additionalProperties" ? ` "${e.params.additionalProperty}"` : "";
|
|
152
|
+
return `${where} ${e.message ?? "is invalid"}${extra}`;
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
export function jsonBodySchema(op) {
|
|
156
|
+
return op.requestBody?.content?.["application/json"]?.schema;
|
|
157
|
+
}
|
|
158
|
+
export function validateBody(doc, op, body) {
|
|
159
|
+
const schema = jsonBodySchema(op);
|
|
160
|
+
if (!schema)
|
|
161
|
+
return;
|
|
162
|
+
const errors = schemaErrors(doc, schema, body);
|
|
163
|
+
if (errors.length) {
|
|
164
|
+
throw validationError(`The body does not match ${op.alias}'s schema: ${errors.join("; ")}`, errors, `See \`cavelon api describe ${op.alias}\`.`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
export function coerceParameter(param, raw) {
|
|
168
|
+
const types = schemaTypes(param.schema);
|
|
169
|
+
if (types.includes("integer") && /^-?\d+$/.test(raw))
|
|
170
|
+
return Number(raw);
|
|
171
|
+
if (types.includes("number") && raw.trim() !== "" && !Number.isNaN(Number(raw)))
|
|
172
|
+
return Number(raw);
|
|
173
|
+
if (types.includes("boolean") && (raw === "true" || raw === "false"))
|
|
174
|
+
return raw === "true";
|
|
175
|
+
return raw;
|
|
176
|
+
}
|
|
177
|
+
export function schemaTypes(schema) {
|
|
178
|
+
if (!schema)
|
|
179
|
+
return [];
|
|
180
|
+
const out = [];
|
|
181
|
+
if (typeof schema.type === "string")
|
|
182
|
+
out.push(schema.type);
|
|
183
|
+
if (Array.isArray(schema.type))
|
|
184
|
+
out.push(...schema.type);
|
|
185
|
+
for (const key of ["anyOf", "oneOf", "allOf"]) {
|
|
186
|
+
for (const sub of schema[key] ?? [])
|
|
187
|
+
out.push(...schemaTypes(sub));
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
export function isArrayParameter(param) {
|
|
192
|
+
return schemaTypes(param.schema).includes("array");
|
|
193
|
+
}
|
|
194
|
+
export function describeSchema(doc, schema) {
|
|
195
|
+
if (!schema)
|
|
196
|
+
return null;
|
|
197
|
+
const resolved = deref(doc, schema);
|
|
198
|
+
const props = resolved.properties;
|
|
199
|
+
const ref = typeof schema.$ref === "string" ? schema.$ref.split("/").pop() : undefined;
|
|
200
|
+
if (!props) {
|
|
201
|
+
if (resolved.type === "array" && resolved.items)
|
|
202
|
+
return { type: "array", items: describeSchema(doc, resolved.items) };
|
|
203
|
+
return { ...(ref ? { name: ref } : {}), type: resolved.type ?? (schemaTypes(resolved).join("|") || "any") };
|
|
204
|
+
}
|
|
205
|
+
const required = new Set(resolved.required ?? []);
|
|
206
|
+
return {
|
|
207
|
+
...(ref ? { name: ref } : {}),
|
|
208
|
+
type: "object",
|
|
209
|
+
fields: Object.fromEntries(Object.entries(props).map(([name, p]) => {
|
|
210
|
+
const sub = deref(doc, p);
|
|
211
|
+
const subRef = typeof p.$ref === "string" ? p.$ref.split("/").pop() : undefined;
|
|
212
|
+
const type = subRef ?? (schemaTypes(sub).filter((t) => t !== "null").join("|") || "object");
|
|
213
|
+
const parts = [type];
|
|
214
|
+
if (required.has(name))
|
|
215
|
+
parts.push("required");
|
|
216
|
+
if (Array.isArray(sub.enum))
|
|
217
|
+
parts.push(`one of ${sub.enum.join(", ")}`);
|
|
218
|
+
if (sub.default !== undefined)
|
|
219
|
+
parts.push(`default ${JSON.stringify(sub.default)}`);
|
|
220
|
+
return [name, parts.join(", ")];
|
|
221
|
+
})),
|
|
222
|
+
};
|
|
223
|
+
}
|
|
@@ -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 ExitCode.failure;
|
|
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
|
+
}
|