@cavelon/cli 0.1.3 → 0.1.5
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 +43 -17
- package/dist/agent-env.js +24 -0
- package/dist/choose.js +8 -4
- package/dist/code-hints.js +74 -0
- package/dist/commands/api.js +174 -33
- package/dist/commands/async.js +26 -5
- package/dist/commands/docs.js +183 -37
- package/dist/commands/fmt.js +117 -0
- package/dist/commands/index.js +6 -1
- package/dist/commands/init.js +28 -6
- package/dist/commands/inventory.js +27 -5
- package/dist/commands/models.js +7 -1
- package/dist/commands/schema.js +193 -0
- package/dist/commands/session.js +69 -13
- package/dist/commands/solution.js +275 -36
- package/dist/commands/tenants.js +125 -15
- package/dist/commands/work.js +245 -24
- package/dist/contracts.js +3 -0
- package/dist/default-route.js +21 -0
- package/dist/errors.js +4 -0
- package/dist/git.js +14 -5
- package/dist/http.js +27 -4
- package/dist/invoke.js +8 -4
- package/dist/kit-codes.js +85 -0
- package/dist/limits.js +12 -1
- package/dist/local-state.js +9 -2
- package/dist/main.js +16 -3
- package/dist/mcp.js +19 -8
- package/dist/openapi.js +91 -21
- package/dist/operations.js +4 -3
- package/dist/package-check.js +193 -4
- package/dist/package-files.js +21 -10
- package/dist/package-format.js +149 -0
- package/dist/package-references.js +231 -0
- package/dist/paths.js +4 -3
- package/dist/preview-report.js +152 -0
- package/dist/results.js +65 -5
- package/dist/skills/cavelon-authoring/SKILL.md +67 -8
- package/dist/skills/cavelon-long-running/SKILL.md +3 -1
- package/dist/skills/cavelon-loop/SKILL.md +75 -13
- package/dist/skills/cavelon-testing/SKILL.md +85 -4
- package/dist/tenant-choice.js +12 -5
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -111,14 +111,14 @@ Every command takes `--json` (one JSON document on stdout, errors included),
|
|
|
111
111
|
| `setup [--agents] [--yes] [--check] [--remove]` | changing (destructive) | Set up the coding agents on this computer (the plugin for Claude Code and Codex; the MCP server and skills in the user settings of Cursor, VS Code with GitHub Copilot, Gemini CLI and Kiro) and log in. `--check` reports what works, `--remove` undoes it. A person runs this; not an MCP tool. |
|
|
112
112
|
| `login [--token-stdin]` | changing | Store a token for an instance. A person runs this. |
|
|
113
113
|
| `logout [--all]` | changing | Delete the stored token. |
|
|
114
|
-
| `whoami` | read-only | Owner or key, tenant (name, slug and id), role,
|
|
114
|
+
| `whoami` | read-only | Owner or key, tenant (name, slug and id), role, where the credential came from, whether it may enter Platform mode and which tenants it reaches. |
|
|
115
115
|
| `use [<tenant>]` / `use --clear` | changing | Choose the tenant for this instance, by name, slug or id, or from a list. |
|
|
116
|
-
| `status [--offline]` | read-only | Instance, credential, tenant, solution folder, running operations, quotas close to full. |
|
|
116
|
+
| `status [--offline]` | read-only | Instance, credential, tenant, solution folder and the solution's state (draft or active, ready to activate, latest test run), open previews, running operations, quotas close to full or why they cannot be read. |
|
|
117
117
|
| `limits [--key <key>] [--source <source>]` | read-only | The instance's limits for this tenant by source, who changes each and how; the tenant's quotas with their use (the monthly Processing Step cap among them); branch concurrency. |
|
|
118
118
|
| `limits set <key> <value> [--confirm]` | changing (destructive) | Change a limit through the operation the instance names: a tenant admin's, a quota of the Tenant Owner's (inference budget, Processing Step cap), or an operator's run cap with a Platform-mode token; without `--confirm`, shows the old and new value. |
|
|
119
119
|
| `models list` | read-only | The tenant's Model Registry rows with their endpoint and `max_concurrent_requests`; never a key. |
|
|
120
120
|
| `models set-limit <model> <n\|none> [--confirm]` | changing (destructive) | Set or clear a row's `max_concurrent_requests`; without `--confirm`, shows the old and new value. |
|
|
121
|
-
| `tenant create <slug> [--name] [--use]` | changing | Create a tenant (personal token in Platform mode with `tenants.manage`). |
|
|
121
|
+
| `tenant create <slug> [--name] [--use]` | changing | Create a tenant (personal token in Platform mode with `tenants.manage`); refused before sending when the token cannot. |
|
|
122
122
|
| `tenant list [--search]` | read-only | Tenants the token can see, with name, slug, role and id. |
|
|
123
123
|
| `harness list [--readiness]` | read-only | The tenant's solutions, with slug, name, status and id. |
|
|
124
124
|
| `harness new <slug> [--name] [--description]` | changing | Create an empty draft solution. |
|
|
@@ -126,7 +126,8 @@ Every command takes `--json` (one JSON document on stdout, errors included),
|
|
|
126
126
|
| `activate [--harness] [--env]` | changing | Activate through the readiness gate only, never by force. |
|
|
127
127
|
| `init [--harness] [--agents <list>] [--hook] [--update] [--from <file> [--force]]` | changing (files) | Make this folder a solution: `cavelon.yaml`, `package/`, `tests/`, `env/`, `.cavelon/`; on a terminal it asks for the tenant and the solution (or a new one by name); `--from` writes a package file into it. |
|
|
128
128
|
| `pull [--harness] [--force]` | changing (files) | Write the instance's package into `package/` and `tests/`, the inventory into `.cavelon/`. |
|
|
129
|
-
| `validate [--offline]` | read-only | Check the package files against the cached package schema. |
|
|
129
|
+
| `validate [--offline]` | read-only | Check the package files against the cached package schema, their references, unknown fields and models. |
|
|
130
|
+
| `schema [<section>] [--offline]` | read-only | The package schema's sections, or one section's fields with a minimal example. |
|
|
130
131
|
| `apply [--env] [--harness] [--mode]` | changing | Preview the files against the instance; prints and stores a preview id. |
|
|
131
132
|
| `apply --confirm <preview-id>` | changing | Import exactly that preview; a stale one, or one the import's own check refuses (it names the blockers), exits 4. |
|
|
132
133
|
| `explain <code>` | read-only | Look a code up in the instance's error catalog. |
|
|
@@ -136,14 +137,14 @@ Every command takes `--json` (one JSON document on stdout, errors included),
|
|
|
136
137
|
| `secrets list [--missing]` | read-only | The tenant's secret names (`{{secret:…}}`): set or not, declared, changed when. Never a value. |
|
|
137
138
|
| `secrets set <name>` | changing | Set a secret's value from the terminal or stdin. A person runs this. |
|
|
138
139
|
| `secrets delete <name> [--confirm]` | changing (destructive) | Delete a secret's value; without `--confirm`, shows its status. A person runs this. |
|
|
139
|
-
| `api <operation> [name=value…] [--
|
|
140
|
+
| `api <operation> [name=value…] [--body <body>]` | changing | Call any operation of the instance's OpenAPI. |
|
|
140
141
|
| `api list [--tag] [--search] [--method] [--tags]` | read-only | The operations the instance publishes. |
|
|
141
142
|
| `api describe <operation>` | read-only | One operation's parameters, body and responses. |
|
|
142
143
|
| `docs search <query>` | read-only | Search the instance's own docs. |
|
|
143
144
|
| `docs get <page> [--max-chars] [--cursor]` | read-only | One docs page as markdown. |
|
|
144
|
-
| `wait <operation…> [--timeout 90s]` | read-only | Wait for operations; resumable
|
|
145
|
+
| `wait <operation…> [--timeout 90s]` | read-only | Wait for operations; resumable, and reports `waited_ms`. A test run with failed cases is a failure. |
|
|
145
146
|
| `watch <operation> [--timeout 10m]` | read-only | Stream an operation's changes (server-sent events). |
|
|
146
|
-
| `kb upload <dir> --kb <kb> [-r] [--ext pdf] [--wait]` | changing | Upload documents; returns operation ids. |
|
|
147
|
+
| `kb upload <dir> --kb <kb> [-r] [--ext pdf] [--replace] [--wait]` | changing | Upload documents; returns operation ids. Names files that match an active document; `--replace` replaces those. |
|
|
147
148
|
| `test run [--suite <s>] [--harness <h>] [--wait]` | changing | Start test-suite runs; returns operation ids. |
|
|
148
149
|
| `trace <run> [--trace <id>] [--span <id>]` | read-only | Summarise a run's traces (or a test run's results, with why a case did not pass), then one trace's spans, then one span. |
|
|
149
150
|
| `loop start <trigger> [--input <json>] [--wait]` | changing | Start a loop through its trigger, as you; returns the run and operation ids. |
|
|
@@ -168,15 +169,18 @@ Every command takes `--json` (one JSON document on stdout, errors included),
|
|
|
168
169
|
cavelon api list --search harness
|
|
169
170
|
cavelon api describe create_harness
|
|
170
171
|
cavelon api get_harness_by_slug slug=support
|
|
171
|
-
cavelon api create_knowledge_base --
|
|
172
|
-
cavelon api create_knowledge_base --
|
|
172
|
+
cavelon api create_knowledge_base --body '{"name": "FAQ"}'
|
|
173
|
+
cavelon api create_knowledge_base --body @kb.json # or --body - for stdin
|
|
173
174
|
```
|
|
174
175
|
|
|
175
176
|
An operation is named by its `operationId` or by its short name (the part before
|
|
176
|
-
FastAPI's path suffix, `list_harnesses` for `list_harnesses_api_v1_harnesses_get`)
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
177
|
+
FastAPI's path suffix, `list_harnesses` for `list_harnesses_api_v1_harnesses_get`);
|
|
178
|
+
a looser spelling such as `createTenant` finds `create_tenant` and says so.
|
|
179
|
+
Parameters are `name=value` or `-p name=value`, never `--name value`; the body
|
|
180
|
+
(`--body`) is checked against the operation's schema before it is sent. `--json`
|
|
181
|
+
is the output switch, as everywhere else. `--json <body>` still sends the body
|
|
182
|
+
for now, with a warning: it is deprecated and will be removed in a later
|
|
183
|
+
release.
|
|
180
184
|
|
|
181
185
|
### Limits
|
|
182
186
|
|
|
@@ -391,6 +395,25 @@ op read op://dev/crm/token | cavelon secrets set crm_api_token
|
|
|
391
395
|
- `--env <name>` acts in the tenant `env/<name>.yaml` names, like `apply`. A
|
|
392
396
|
name without its env file is refused (exit 2) before anything is sent.
|
|
393
397
|
|
|
398
|
+
### Updating a document
|
|
399
|
+
|
|
400
|
+
`kb upload` names each file that matches an active document of the knowledge
|
|
401
|
+
base by file name, with what happens to that document, in `--dry-run` too:
|
|
402
|
+
|
|
403
|
+
```text
|
|
404
|
+
bergbahn-faq.md exists (094e95e9…) and stays active
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
- Without a flag the old document stays active next to the new one, and both
|
|
408
|
+
answer, unless the instance replaces same-named documents itself (its upload
|
|
409
|
+
offers `replace_existing`); there `--keep-both` keeps both.
|
|
410
|
+
- `--replace` replaces it. It uses the instance's own replacement
|
|
411
|
+
(`replace_doc_ids`) and reads what was replaced from each document's
|
|
412
|
+
`replaced_document_ids`. On an instance whose upload offers neither, it shows
|
|
413
|
+
the documents it would deactivate after the upload and sends nothing; with
|
|
414
|
+
`--confirm` it uploads, then deactivates them (after the wait, with
|
|
415
|
+
`--wait`).
|
|
416
|
+
|
|
394
417
|
### Long-running work
|
|
395
418
|
|
|
396
419
|
`kb upload` and `test run` return operation ids at once. `--wait` waits for them,
|
|
@@ -681,10 +704,13 @@ The same commands as MCP tools over stdio, for agents that prefer tools to a
|
|
|
681
704
|
shell. The tools are coarse, one per workflow command plus `api`, `api_list`,
|
|
682
705
|
`api_describe`, `docs_search` and `docs_get`, and carry the standard read-only and
|
|
683
706
|
destructive annotations. The repository tools (`init`, `pull`, `validate`,
|
|
684
|
-
`apply`, `explain`, `activate`) and `sandbox_seed` and
|
|
685
|
-
the folder the agent started `cavelon mcp` in
|
|
686
|
-
`
|
|
687
|
-
|
|
707
|
+
`package_schema`, `apply`, `explain`, `activate`) and `sandbox_seed` and
|
|
708
|
+
`artifacts_export` work in the folder the agent started `cavelon mcp` in;
|
|
709
|
+
`init` and `pull` change nothing on the instance. Tools that start work never
|
|
710
|
+
block: `kb_upload`, `test_run`, `loop_start`, `sandbox_seed` and
|
|
711
|
+
`artifacts_export` return operation ids, `operation_status` reads them (at
|
|
712
|
+
once, or waiting up to its `timeout`, at most 50 seconds, with `waited_ms` in
|
|
713
|
+
the answer), and `loop_iterations` follows a loop
|
|
688
714
|
(`loop watch` and `watch` stream, so they are no tools). `loop_cancel`,
|
|
689
715
|
`sandbox_seed` and `trigger_identity` are marked destructive and change nothing
|
|
690
716
|
without `confirm: true`. `limits` is read-only; the server's instructions tell
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export const AGENT_VARIABLES = [
|
|
2
|
+
{ variable: "CAVELON_AGENT", agent: "any agent whose shell environment sets it" },
|
|
3
|
+
{ variable: "CLAUDECODE", agent: "Claude Code" },
|
|
4
|
+
{ variable: "CODEX_THREAD_ID", agent: "Codex" },
|
|
5
|
+
{ variable: "CODEX_SANDBOX", agent: "Codex" },
|
|
6
|
+
{ variable: "CURSOR_AGENT", agent: "Cursor" },
|
|
7
|
+
{ variable: "GEMINI_CLI", agent: "Gemini CLI" },
|
|
8
|
+
{ variable: "COPILOT_CLI", agent: "GitHub Copilot CLI" },
|
|
9
|
+
{ variable: "COPILOT_AGENT", agent: "GitHub Copilot in VS Code" },
|
|
10
|
+
{ variable: "AI_AGENT", agent: "an agent that follows the AI_AGENT convention" },
|
|
11
|
+
];
|
|
12
|
+
function isSet(value) {
|
|
13
|
+
const text = value?.trim().toLowerCase();
|
|
14
|
+
return Boolean(text) && text !== "0" && text !== "false";
|
|
15
|
+
}
|
|
16
|
+
export function agentVariable(env) {
|
|
17
|
+
return AGENT_VARIABLES.find(({ variable }) => isSet(env[variable]))?.variable;
|
|
18
|
+
}
|
|
19
|
+
export function drivenByAgent(ctx) {
|
|
20
|
+
if (ctx.mode === "mcp")
|
|
21
|
+
return { by: "mcp" };
|
|
22
|
+
const variable = agentVariable(ctx.io.env);
|
|
23
|
+
return variable ? { by: "agent", variable } : undefined;
|
|
24
|
+
}
|
package/dist/choose.js
CHANGED
|
@@ -60,8 +60,9 @@ function line(index, item, extra, preferred) {
|
|
|
60
60
|
export async function pick(ctx, options) {
|
|
61
61
|
const write = (text) => ctx.io.stderr.write(`${text}\n`);
|
|
62
62
|
let shown = options.items.slice(0, MAX_LISTED);
|
|
63
|
+
const preferred = options.later ? undefined : options.preferred;
|
|
63
64
|
const show = (items) => {
|
|
64
|
-
items.forEach((item, i) => write(line(i + 1, item, options.extra?.(item), item ===
|
|
65
|
+
items.forEach((item, i) => write(line(i + 1, item, options.extra?.(item), item === preferred)));
|
|
65
66
|
if (options.other)
|
|
66
67
|
write(` ${String(items.length + 1).padStart(2)} ${options.other.label}`);
|
|
67
68
|
};
|
|
@@ -69,12 +70,15 @@ export async function pick(ctx, options) {
|
|
|
69
70
|
show(shown);
|
|
70
71
|
if (options.items.length > shown.length)
|
|
71
72
|
write(` … and ${options.items.length - shown.length} more: type part of a name to find one.`);
|
|
72
|
-
const
|
|
73
|
+
const typed = shown.length || options.other ? "type its number or part of its name" : "type part of its name";
|
|
74
|
+
const hint = options.later ? `${typed}, or press Enter to ${options.later}` : typed;
|
|
73
75
|
for (let tries = 0; tries < MAX_TRIES; tries++) {
|
|
74
76
|
const answer = await readLine(ctx.io, `${options.question} ${ctx.style.dim(`(${hint})`)} `);
|
|
75
77
|
if (!answer) {
|
|
76
|
-
if (options.
|
|
77
|
-
return {
|
|
78
|
+
if (options.later)
|
|
79
|
+
return { later: true };
|
|
80
|
+
if (preferred)
|
|
81
|
+
return { item: preferred };
|
|
78
82
|
write("Type a number from the list, or part of a name.");
|
|
79
83
|
continue;
|
|
80
84
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export function editDistance(a, b) {
|
|
2
|
+
let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
3
|
+
for (let i = 1; i <= a.length; i++) {
|
|
4
|
+
const current = [i];
|
|
5
|
+
for (let j = 1; j <= b.length; j++) {
|
|
6
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
7
|
+
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
|
|
8
|
+
}
|
|
9
|
+
previous = current;
|
|
10
|
+
}
|
|
11
|
+
return previous[b.length];
|
|
12
|
+
}
|
|
13
|
+
const words = (code) => code.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
14
|
+
const COMMON = new Set(["found", "invalid", "error", "missing", "required", "unknown", "unavailable", "failed", "denied", "limit", "reached", "exceeded", "allowed"]);
|
|
15
|
+
export function similarCodes(code, known, max = 8) {
|
|
16
|
+
const wanted = code.toLowerCase();
|
|
17
|
+
const head = words(code);
|
|
18
|
+
const threshold = Math.max(2, Math.floor(wanted.length / 4));
|
|
19
|
+
const ranked = [];
|
|
20
|
+
for (const candidate of new Set(known)) {
|
|
21
|
+
const lower = candidate.toLowerCase();
|
|
22
|
+
if (lower === wanted)
|
|
23
|
+
continue;
|
|
24
|
+
const distance = editDistance(wanted, lower);
|
|
25
|
+
const theirs = words(candidate);
|
|
26
|
+
const shared = head.findIndex((w, i) => theirs[i] !== w);
|
|
27
|
+
const prefix = shared === -1 ? head.length : shared;
|
|
28
|
+
let rank;
|
|
29
|
+
if (distance <= threshold)
|
|
30
|
+
rank = distance;
|
|
31
|
+
else if ((lower.includes(wanted) || wanted.includes(lower)) && Math.min(lower.length, wanted.length) * 2 >= Math.max(lower.length, wanted.length))
|
|
32
|
+
rank = 10;
|
|
33
|
+
else if (prefix >= 2)
|
|
34
|
+
rank = 20 - prefix;
|
|
35
|
+
else if (prefix === 1 && head[0].length >= 4)
|
|
36
|
+
rank = 30;
|
|
37
|
+
else if (head.some((w) => w.length >= 5 && !COMMON.has(w) && theirs.includes(w)))
|
|
38
|
+
rank = 40;
|
|
39
|
+
if (rank !== undefined)
|
|
40
|
+
ranked.push({ code: candidate, rank: rank * 100 + Math.min(distance, 99) });
|
|
41
|
+
}
|
|
42
|
+
return ranked.sort((a, b) => a.rank - b.rank || a.code.localeCompare(b.code, "en")).slice(0, max).map((r) => r.code);
|
|
43
|
+
}
|
|
44
|
+
const BY_CODE = {
|
|
45
|
+
package_schema_invalid: "Run `cavelon validate`: it checks the package files against the package schema offline and names each field that " +
|
|
46
|
+
"does not match, with file, line and path. `cavelon schema <section>` shows a section's fields and a minimal entry.",
|
|
47
|
+
package_requirements_changed: "Run `cavelon apply` again for a new preview, show it, and confirm its id with `cavelon apply --confirm <preview-id>`.",
|
|
48
|
+
import_preview_stale: "Run `cavelon apply` again for a new preview, show it, and confirm its id with `cavelon apply --confirm <preview-id>`.",
|
|
49
|
+
};
|
|
50
|
+
const BY_ROUTE = [
|
|
51
|
+
{ route: "/api/v1/meta/package-schema", command: "`cavelon schema [section]` shows the package schema; `cavelon validate` checks the files against it." },
|
|
52
|
+
{ route: "/api/v1/meta/error-catalog", command: "`cavelon explain <code>` reads the error catalog." },
|
|
53
|
+
{ route: "/api/v1/meta/capabilities", command: "`cavelon status` and `cavelon limits` read the capabilities." },
|
|
54
|
+
{ route: "/api/v1/agent-graph/import/preview", command: "`cavelon apply` previews the package files." },
|
|
55
|
+
{ route: "/api/v1/agent-graph/import", command: "`cavelon apply --confirm <preview-id>` imports a preview." },
|
|
56
|
+
{ route: "/api/v1/agent-graph/export", command: "`cavelon pull` writes the export into the package files." },
|
|
57
|
+
{ route: "/readiness", command: "`cavelon status` shows the readiness; `cavelon activate` goes through it." },
|
|
58
|
+
{ route: "/api/v1/operations", command: "`cavelon wait <op_id>` and `cavelon status` read the operations." },
|
|
59
|
+
];
|
|
60
|
+
export function cliFix(entry) {
|
|
61
|
+
const direct = BY_CODE[entry.code];
|
|
62
|
+
if (direct)
|
|
63
|
+
return direct;
|
|
64
|
+
const text = `${entry.hint ?? ""} ${entry.message}`;
|
|
65
|
+
const found = [];
|
|
66
|
+
for (const { route, command } of BY_ROUTE) {
|
|
67
|
+
if (text.includes(route) && !found.some((f) => f === command)) {
|
|
68
|
+
const longer = BY_ROUTE.find((r) => r.route !== route && r.route.startsWith(route) && text.includes(r.route));
|
|
69
|
+
if (!longer)
|
|
70
|
+
found.push(command);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return found.length ? found.join(" ") : undefined;
|
|
74
|
+
}
|
package/dist/commands/api.js
CHANGED
|
@@ -1,29 +1,59 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { promises as fs } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
4
|
+
import { AGENT_VARIABLES, drivenByAgent } from "../agent-env.js";
|
|
3
5
|
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
|
|
4
6
|
import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
|
|
5
7
|
import { clip, moreHint, table } from "../format.js";
|
|
6
8
|
import { readAll } from "../io.js";
|
|
7
9
|
import { callOperation, previewRequest } from "../invoke.js";
|
|
8
10
|
import { confinedPath } from "../paths.js";
|
|
9
|
-
import { describeSchema, findOperation, jsonBodySchema, operations, schemaTypes } from "../openapi.js";
|
|
11
|
+
import { describeSchema, findOperation, jsonBodySchema, matchedLoosely, operations, schemaTypes, secretFields } from "../openapi.js";
|
|
12
|
+
import { canonical } from "../package-files.js";
|
|
13
|
+
import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
|
|
10
14
|
import { cavelonCommand } from "../shell.js";
|
|
11
|
-
export
|
|
15
|
+
export const JSON_BODY_DEPRECATED = "`--json <body>` as the request body is deprecated and will be removed in a later release; pass the body with --body. " +
|
|
16
|
+
"--json alone prints JSON, as on every command.";
|
|
17
|
+
export function splitJsonBody(args, warn) {
|
|
12
18
|
const out = [];
|
|
19
|
+
let aliased = false;
|
|
13
20
|
for (let i = 0; i < args.length; i++) {
|
|
14
21
|
const arg = args[i];
|
|
15
22
|
if (arg.startsWith("--json=")) {
|
|
16
23
|
out.push(`--body=${arg.slice("--json=".length)}`);
|
|
24
|
+
aliased = true;
|
|
17
25
|
continue;
|
|
18
26
|
}
|
|
19
27
|
const next = args[i + 1];
|
|
20
28
|
if (arg === "--json" && next !== undefined && looksLikeBody(next)) {
|
|
21
29
|
out.push("--body", next);
|
|
30
|
+
aliased = true;
|
|
22
31
|
i++;
|
|
23
32
|
continue;
|
|
24
33
|
}
|
|
25
34
|
out.push(arg);
|
|
26
35
|
}
|
|
36
|
+
if (aliased)
|
|
37
|
+
warn?.(JSON_BODY_DEPRECATED);
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
|
|
41
|
+
export function splitConfirm(args) {
|
|
42
|
+
const out = [];
|
|
43
|
+
for (let i = 0; i < args.length; i++) {
|
|
44
|
+
const arg = args[i];
|
|
45
|
+
if (arg !== "--confirm") {
|
|
46
|
+
out.push(arg);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const next = args[i + 1];
|
|
50
|
+
if (next !== undefined && CONFIRM_TOKEN.test(next)) {
|
|
51
|
+
out.push(`--confirm=${next}`);
|
|
52
|
+
i++;
|
|
53
|
+
}
|
|
54
|
+
else
|
|
55
|
+
out.push("--confirm=");
|
|
56
|
+
}
|
|
27
57
|
return out;
|
|
28
58
|
}
|
|
29
59
|
function looksLikeBody(value) {
|
|
@@ -37,7 +67,7 @@ function looksLikeBody(value) {
|
|
|
37
67
|
return false;
|
|
38
68
|
}
|
|
39
69
|
}
|
|
40
|
-
export async function readBody(ctx, raw) {
|
|
70
|
+
export async function readBody(ctx, raw, confine = ctx.mode === "mcp") {
|
|
41
71
|
let text = raw;
|
|
42
72
|
if (raw === "-" && ctx.mode === "mcp") {
|
|
43
73
|
throw usageError("A body from standard input is not available over MCP; pass the JSON itself.");
|
|
@@ -45,12 +75,12 @@ export async function readBody(ctx, raw) {
|
|
|
45
75
|
if (raw === "-")
|
|
46
76
|
text = await readAll(ctx.io.stdin);
|
|
47
77
|
else if (raw.startsWith("@"))
|
|
48
|
-
text = await fs.readFile(await confinedPath(ctx, raw.slice(1), "The body file"), "utf8");
|
|
78
|
+
text = await fs.readFile(await confinedPath(ctx, raw.slice(1), "The body file", confine), "utf8");
|
|
49
79
|
try {
|
|
50
80
|
return JSON.parse(text);
|
|
51
81
|
}
|
|
52
82
|
catch (error) {
|
|
53
|
-
throw usageError(`The body is not JSON: ${error instanceof Error ? error.message : String(error)}`, "Pass --
|
|
83
|
+
throw usageError(`The body is not JSON: ${error instanceof Error ? error.message : String(error)}`, "Pass --body '{\"key\": \"value\"}', @file.json or - for stdin.");
|
|
54
84
|
}
|
|
55
85
|
}
|
|
56
86
|
function parseParams(input) {
|
|
@@ -98,13 +128,50 @@ export function keptForPerson(op, all) {
|
|
|
98
128
|
const rule = byPathWords(op);
|
|
99
129
|
return rule ? { source: "kit", reason: rule.does, hint: rule.hint } : undefined;
|
|
100
130
|
}
|
|
101
|
-
function
|
|
131
|
+
function notSentBy(driven) {
|
|
132
|
+
return driven.by === "mcp"
|
|
133
|
+
? "no tool sends it, with or without confirm."
|
|
134
|
+
: `cavelon api does not send it when a coding agent runs it (${driven.variable} is set), with or without --confirm.`;
|
|
135
|
+
}
|
|
136
|
+
function personHint(hint, driven) {
|
|
137
|
+
return driven.by === "mcp" ? hint : `${hint} A person's own terminal is not guarded: it does not set ${driven.variable}.`;
|
|
138
|
+
}
|
|
139
|
+
function refusal(op, kept, driven) {
|
|
102
140
|
const named = `${op.alias} (${op.method} ${op.path})`;
|
|
103
|
-
const after =
|
|
141
|
+
const after = notSentBy(driven);
|
|
104
142
|
if (kept.source === "kit")
|
|
105
143
|
return `${named} ${kept.reason}; that stays with a person, so ${after}`;
|
|
106
144
|
return `${named} is for a person only, as the instance marks it${kept.reason ? ` (${kept.reason})` : ""}; ${after}`;
|
|
107
145
|
}
|
|
146
|
+
function secretsIn(doc, op, args) {
|
|
147
|
+
const found = new Set();
|
|
148
|
+
const fileFields = args.files?.length ? Object.fromEntries(args.files.map((f) => [f.field, f.path])) : undefined;
|
|
149
|
+
for (const media of Object.values(op.requestBody?.content ?? {})) {
|
|
150
|
+
if (args.body !== undefined)
|
|
151
|
+
for (const field of secretFields(doc, media.schema, args.body))
|
|
152
|
+
found.add(field);
|
|
153
|
+
if (fileFields)
|
|
154
|
+
for (const field of secretFields(doc, media.schema, fileFields))
|
|
155
|
+
found.add(field);
|
|
156
|
+
}
|
|
157
|
+
return [...found];
|
|
158
|
+
}
|
|
159
|
+
function secretRefusal(op, fields, driven) {
|
|
160
|
+
const named = fields.map((f) => `"${f}"`).join(", ");
|
|
161
|
+
return new CavelonError(ExitCode.usage, {
|
|
162
|
+
code: "secret_field_for_a_person",
|
|
163
|
+
message: `The request to ${op.alias} sets ${named}, which the instance marks as a secret value (x-cavelon-secret); ` +
|
|
164
|
+
`a person enters secret values, so ${notSentBy(driven)}`,
|
|
165
|
+
hint: personHint("A person sets a secret value in their terminal with `cavelon secrets set <name>`, or enters it in the Admin. Leave the field out to send the rest.", driven),
|
|
166
|
+
details: { fields },
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
function confirmToken(target, request, files) {
|
|
170
|
+
return createHash("sha256")
|
|
171
|
+
.update(canonical({ instance: target.url ?? null, tenant: target.tenant ?? null, request, files }))
|
|
172
|
+
.digest("hex")
|
|
173
|
+
.slice(0, 12);
|
|
174
|
+
}
|
|
108
175
|
function truncate(data, limit) {
|
|
109
176
|
if (limit <= 0)
|
|
110
177
|
return { data };
|
|
@@ -117,16 +184,41 @@ function truncate(data, limit) {
|
|
|
117
184
|
}
|
|
118
185
|
return { data };
|
|
119
186
|
}
|
|
187
|
+
const PERSONA_ROUTE = "/api/v1/bot-persona";
|
|
188
|
+
async function solutionForPersona(ctx, op, params) {
|
|
189
|
+
if (op.path !== PERSONA_ROUTE && !op.path.startsWith(`${PERSONA_ROUTE}/`))
|
|
190
|
+
return;
|
|
191
|
+
if (params.harness_id || !op.parameters.some((p) => p.name === "harness_id" && p.in === "query"))
|
|
192
|
+
return;
|
|
193
|
+
const session = await ctx.session();
|
|
194
|
+
const ref = session.envFile?.harness ?? session.project?.harness;
|
|
195
|
+
if (!ref)
|
|
196
|
+
return;
|
|
197
|
+
const source = session.envFile?.harness ? `env/${session.envFile.name}.yaml` : "cavelon.yaml";
|
|
198
|
+
const { harness, candidates } = await lookupHarness(ctx, ref);
|
|
199
|
+
if (!harness)
|
|
200
|
+
throw harnessNotFoundError(ref, candidates, source, (slug) => `harness_id=<id of ${slug}>`);
|
|
201
|
+
params.harness_id = [harness.id];
|
|
202
|
+
ctx.warn(`Sent harness_id=${harness.id}, the solution ${harness.slug} from ${source}: without it, ${op.alias} reaches the tenant's default route. ` +
|
|
203
|
+
"Pass harness_id=<id> for another solution.");
|
|
204
|
+
}
|
|
120
205
|
export const api = {
|
|
121
206
|
name: "api",
|
|
122
207
|
summary: "Call any operation the instance publishes in its OpenAPI.",
|
|
123
208
|
description: "The operation is its operationId or the short name before FastAPI's path suffix (list_harnesses).\n" +
|
|
124
|
-
"Parameters: -p name=value or name=value. Body: --
|
|
209
|
+
"Parameters: -p name=value or name=value (not --name). Body: --body '<json>', --body @file.json or --body - (stdin);\n" +
|
|
210
|
+
"--json <body> still works for now but is deprecated: --json alone prints JSON, as on every command.\n" +
|
|
125
211
|
"The body is checked against the operation's schema before it is sent.\n" +
|
|
126
|
-
"As an MCP tool,
|
|
127
|
-
|
|
128
|
-
"
|
|
129
|
-
"
|
|
212
|
+
"As an MCP tool, or run by a coding agent (" +
|
|
213
|
+
AGENT_VARIABLES.filter((v) => v.variable !== "CAVELON_AGENT").map((v) => v.variable).join(", ") +
|
|
214
|
+
"\nor CAVELON_AGENT=1 is set), an operation that changes something returns what it would send and sends it only\n" +
|
|
215
|
+
"with confirm (as an MCP tool) or --confirm <token> (the token the preview printed).\n" +
|
|
216
|
+
"Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
|
|
217
|
+
"sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
|
|
218
|
+
"instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
|
|
219
|
+
"approval is refused. A person's own terminal sends at once.\n" +
|
|
220
|
+
"In a solution folder, the persona operations (get_bot_persona, upsert_bot_persona, …) get the folder's solution as\n" +
|
|
221
|
+
"harness_id when none is passed, since without it they reach the tenant's default route.",
|
|
130
222
|
readOnly: false,
|
|
131
223
|
destructive: true,
|
|
132
224
|
mcpTool: "api",
|
|
@@ -136,63 +228,72 @@ export const api = {
|
|
|
136
228
|
],
|
|
137
229
|
options: {
|
|
138
230
|
param: { type: "string", short: "p", multiple: true, value: "<name=value>", description: "A path, query or header parameter." },
|
|
139
|
-
body: { type: "string", value: "<json|@file|->", description: "The request body
|
|
231
|
+
body: { type: "string", value: "<json|@file|->", description: "The request body: JSON, @file.json or - for stdin (--json <body> is a deprecated alias)." },
|
|
140
232
|
file: { type: "string", multiple: true, value: "<field=path>", description: "Attach a file to a multipart body." },
|
|
141
233
|
output: { type: "string", value: "<file>", description: "Write the response body to a file instead of printing it.", cliOnly: true },
|
|
142
234
|
confirm: {
|
|
143
|
-
type: "
|
|
144
|
-
|
|
235
|
+
type: "string",
|
|
236
|
+
value: "<token>",
|
|
237
|
+
mcpBoolean: true,
|
|
238
|
+
description: "Send an operation that changes something: run by a coding agent, the token its preview printed; as an MCP tool, true. " +
|
|
239
|
+
"Without it, nothing is sent. A person's terminal sends at once.",
|
|
145
240
|
},
|
|
146
241
|
limit: { type: "string", value: "<n>", description: "Show at most n items of a list response (default 50, 0 for all)." },
|
|
147
242
|
},
|
|
148
243
|
examples: [
|
|
149
244
|
"cavelon api list_harnesses",
|
|
150
245
|
"cavelon api get_harness_by_slug slug=support",
|
|
151
|
-
"cavelon api create_knowledge_base --
|
|
246
|
+
"cavelon api create_knowledge_base --body '{\"name\": \"FAQ\"}'",
|
|
152
247
|
],
|
|
153
|
-
preprocess: splitJsonBody,
|
|
248
|
+
preprocess: (args, warn) => splitConfirm(splitJsonBody(args, warn)),
|
|
154
249
|
async run(ctx, input) {
|
|
155
250
|
const name = positional(input, "operation");
|
|
156
251
|
const doc = await (await ctx.contracts()).openapi();
|
|
157
252
|
const op = findOperation(doc, name);
|
|
253
|
+
if (matchedLoosely(op, name))
|
|
254
|
+
ctx.warn(`"${name}" is taken as ${op.alias} (${op.method} ${op.path}).`);
|
|
255
|
+
const driven = drivenByAgent(ctx);
|
|
256
|
+
const confine = driven !== undefined;
|
|
158
257
|
const args = { params: parseParams(input) };
|
|
258
|
+
await solutionForPersona(ctx, op, args.params);
|
|
159
259
|
const rawBody = stringOption(input, "body");
|
|
160
260
|
if (rawBody !== undefined)
|
|
161
|
-
args.body = await readBody(ctx, rawBody);
|
|
261
|
+
args.body = await readBody(ctx, rawBody, confine);
|
|
162
262
|
for (const spec of listOption(input, "file")) {
|
|
163
263
|
const at = spec.indexOf("=");
|
|
164
264
|
if (at <= 0)
|
|
165
265
|
throw usageError(`--file "${spec}" is not field=path.`);
|
|
166
|
-
const file = await confinedPath(ctx, spec.slice(at + 1), "The file");
|
|
266
|
+
const file = await confinedPath(ctx, spec.slice(at + 1), "The file", confine);
|
|
167
267
|
args.files = [...(args.files ?? []), { field: spec.slice(0, at), path: file }];
|
|
168
268
|
}
|
|
169
|
-
|
|
269
|
+
const rawOutput = stringOption(input, "output");
|
|
270
|
+
const output = rawOutput ? await confinedPath(ctx, rawOutput, "The output file", confine) : undefined;
|
|
271
|
+
if (driven) {
|
|
170
272
|
const kept = keptForPerson(op, operations(doc));
|
|
171
273
|
if (kept) {
|
|
172
274
|
throw new CavelonError(ExitCode.usage, {
|
|
173
275
|
code: "operation_for_a_person",
|
|
174
|
-
message: refusal(op, kept),
|
|
175
|
-
hint: kept.hint,
|
|
176
|
-
details: { source: kept.source, ...(kept.reason ? { reason: kept.reason } : {}) },
|
|
276
|
+
message: refusal(op, kept, driven),
|
|
277
|
+
hint: personHint(kept.hint, driven),
|
|
278
|
+
details: { source: kept.source, ...(kept.reason ? { reason: kept.reason } : {}), ...(driven.by === "agent" ? { agent_variable: driven.variable } : {}) },
|
|
177
279
|
});
|
|
178
280
|
}
|
|
281
|
+
const secrets = secretsIn(doc, op, args);
|
|
282
|
+
if (secrets.length)
|
|
283
|
+
throw secretRefusal(op, secrets, driven);
|
|
179
284
|
}
|
|
180
|
-
if (
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
data: { operation: op.alias, ...request, ...(files.length ? { files } : {}), sent: false, confirm: "Call api again with the same arguments and confirm: true." },
|
|
185
|
-
text: `Would send ${request.method} ${request.path}. Nothing was sent.`,
|
|
186
|
-
};
|
|
285
|
+
if (driven && !op.readOnly) {
|
|
286
|
+
const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven);
|
|
287
|
+
if (preview)
|
|
288
|
+
return preview;
|
|
187
289
|
}
|
|
188
290
|
const client = await ctx.client();
|
|
189
291
|
const result = await callOperation(ctx, client, doc, op, args);
|
|
190
|
-
const output = stringOption(input, "output");
|
|
191
292
|
if (output) {
|
|
192
293
|
const content = result.bytes ?? (typeof result.data === "string" ? result.data : JSON.stringify(result.data, null, 2));
|
|
193
294
|
await fs.writeFile(output, content);
|
|
194
295
|
const size = typeof content === "string" ? Buffer.byteLength(content) : content.length;
|
|
195
|
-
return { data: { status: result.status, written:
|
|
296
|
+
return { data: { status: result.status, written: rawOutput, bytes: size }, text: `Wrote ${size} bytes to ${rawOutput}.` };
|
|
196
297
|
}
|
|
197
298
|
if (result.bytes) {
|
|
198
299
|
throw validationError(`${op.alias} answered ${result.contentType} (${result.bytes.length} bytes).`, undefined, "Save it with --output <file>.");
|
|
@@ -205,6 +306,43 @@ export const api = {
|
|
|
205
306
|
return { data, text };
|
|
206
307
|
},
|
|
207
308
|
};
|
|
309
|
+
async function previewUnlessConfirmed(ctx, input, doc, op, args, driven) {
|
|
310
|
+
if (driven.by === "mcp" && boolOption(input, "confirm"))
|
|
311
|
+
return undefined;
|
|
312
|
+
const request = previewRequest(doc, op, args);
|
|
313
|
+
const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
|
|
314
|
+
const shown = { operation: op.alias, ...request, ...(files.length ? { files } : {}), sent: false };
|
|
315
|
+
if (driven.by === "mcp") {
|
|
316
|
+
return {
|
|
317
|
+
data: { ...shown, confirm: "Call api again with the same arguments and confirm: true." },
|
|
318
|
+
text: `Would send ${request.method} ${request.path}. Nothing was sent.`,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
const session = await ctx.session();
|
|
322
|
+
const token = confirmToken({ url: session.url, tenant: session.tenant }, request, files);
|
|
323
|
+
const given = stringOption(input, "confirm");
|
|
324
|
+
if (given === token)
|
|
325
|
+
return undefined;
|
|
326
|
+
const stale = Boolean(given);
|
|
327
|
+
const confirm = `Show the person this request, then run the same command again with --confirm ${token} to send exactly it.`;
|
|
328
|
+
const lines = [`Would send ${request.method} ${request.path}. Nothing was sent.`];
|
|
329
|
+
if (stale)
|
|
330
|
+
lines.push("The --confirm token is not this request's: the request changed since its preview, or the token is another one's.");
|
|
331
|
+
if (Object.keys(request.query).length)
|
|
332
|
+
lines.push(`Query: ${JSON.stringify(request.query)}`);
|
|
333
|
+
if (Object.keys(request.headers).length)
|
|
334
|
+
lines.push(`Headers: ${JSON.stringify(request.headers)}`);
|
|
335
|
+
if (request.body !== null)
|
|
336
|
+
lines.push("Body:", JSON.stringify(request.body, null, 2));
|
|
337
|
+
for (const f of files)
|
|
338
|
+
lines.push(`File: ${f.field} = ${f.file}`);
|
|
339
|
+
lines.push(confirm);
|
|
340
|
+
return {
|
|
341
|
+
data: { ...shown, confirm_token: token, confirm, ...(stale ? { token_mismatch: true } : {}) },
|
|
342
|
+
text: lines.join("\n"),
|
|
343
|
+
...(stale ? { exitCode: ExitCode.conflict } : {}),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
208
346
|
export const apiList = {
|
|
209
347
|
name: "api list",
|
|
210
348
|
summary: "List the operations the instance publishes.",
|
|
@@ -271,7 +409,10 @@ export const apiDescribe = {
|
|
|
271
409
|
positionals: [{ name: "operation", description: "operationId or its short name.", required: true }],
|
|
272
410
|
async run(ctx, input) {
|
|
273
411
|
const doc = await (await ctx.contracts()).openapi();
|
|
274
|
-
const
|
|
412
|
+
const name = positional(input, "operation");
|
|
413
|
+
const op = findOperation(doc, name);
|
|
414
|
+
if (matchedLoosely(op, name))
|
|
415
|
+
ctx.warn(`"${name}" is taken as ${op.alias}; that is the name \`cavelon api\` takes.`);
|
|
275
416
|
const bodyTypes = Object.keys(op.requestBody?.content ?? {});
|
|
276
417
|
const bodySchema = jsonBodySchema(op) ?? op.requestBody?.content?.[bodyTypes[0] ?? ""]?.schema;
|
|
277
418
|
const responses = Object.fromEntries(Object.entries(op.responses)
|