@cavelon/cli 0.1.1 → 0.1.3

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 (52) hide show
  1. package/README.md +50 -20
  2. package/dist/agents.js +43 -19
  3. package/dist/choose.js +112 -0
  4. package/dist/command.js +1 -1
  5. package/dist/commands/api.js +76 -6
  6. package/dist/commands/index.js +2 -0
  7. package/dist/commands/init.js +196 -29
  8. package/dist/commands/limits-set.js +17 -8
  9. package/dist/commands/limits.js +2 -2
  10. package/dist/commands/loops.js +12 -6
  11. package/dist/commands/sandboxes.js +27 -20
  12. package/dist/commands/session.js +179 -45
  13. package/dist/commands/setup.js +426 -0
  14. package/dist/commands/solution.js +137 -91
  15. package/dist/commands/tenants.js +33 -22
  16. package/dist/commands/values.js +8 -5
  17. package/dist/commands/work.js +33 -16
  18. package/dist/context.js +5 -1
  19. package/dist/contracts.js +83 -38
  20. package/dist/embedded.js +7 -0
  21. package/dist/features.js +15 -0
  22. package/dist/fsutil.js +3 -0
  23. package/dist/git.js +14 -9
  24. package/dist/harness-ref.js +54 -0
  25. package/dist/http.js +44 -18
  26. package/dist/install.js +94 -0
  27. package/dist/invoke.js +17 -13
  28. package/dist/limits.js +9 -1
  29. package/dist/local-state.js +18 -0
  30. package/dist/main.js +31 -2
  31. package/dist/markers.js +53 -0
  32. package/dist/mcp.js +9 -2
  33. package/dist/openapi.js +10 -0
  34. package/dist/operations.js +1 -1
  35. package/dist/package-check.js +1 -1
  36. package/dist/package-files.js +103 -38
  37. package/dist/paths.js +53 -4
  38. package/dist/principal.js +43 -0
  39. package/dist/project.js +23 -4
  40. package/dist/prompt.js +55 -11
  41. package/dist/results.js +47 -9
  42. package/dist/run-program.js +92 -0
  43. package/dist/session.js +100 -19
  44. package/dist/setup-agents.js +544 -0
  45. package/dist/skills/cavelon-authoring/SKILL.md +13 -3
  46. package/dist/skills/cavelon-long-running/SKILL.md +5 -1
  47. package/dist/skills/cavelon-loop/SKILL.md +15 -9
  48. package/dist/skills/cavelon-testing/SKILL.md +9 -2
  49. package/dist/tenant-choice.js +93 -0
  50. package/dist/update-check.js +118 -0
  51. package/dist/version.js +2 -1
  52. package/package.json +5 -2
package/README.md CHANGED
@@ -6,13 +6,20 @@ learns each instance's API, features and docs from what the instance publishes
6
6
  (its OpenAPI, `/api/v1/meta/capabilities`, `/api/v1/meta/error-catalog` and
7
7
  `/llms.txt`), so a new core release needs no new `cavelon` release.
8
8
 
9
- Node.js 20.3 or newer. Install it from npm, or run it as `npx -y @cavelon/cli`:
9
+ Node.js 20.3 or newer. Run it through `npx`, which needs no install; to type
10
+ `cavelon`, install it globally (or define an alias for the `npx` command):
10
11
 
11
12
  ```bash
13
+ npx -y @cavelon/cli --help
12
14
  npm i -g @cavelon/cli
13
- cavelon --help
14
15
  ```
15
16
 
17
+ Without Node.js, one line installs a standalone `cavelon` into your user
18
+ folder: `curl -fsSL https://github.com/goodguys-gmbh/cavelon-dev-kit/releases/latest/download/install.sh | sh`
19
+ on macOS and Linux, `irm https://github.com/goodguys-gmbh/cavelon-dev-kit/releases/latest/download/install.ps1 | iex`
20
+ in Windows PowerShell. Then `cavelon setup` sets up your coding agents and logs
21
+ you in.
22
+
16
23
  The full documentation is in the repository's
17
24
  [`docs/`](https://github.com/goodguys-gmbh/cavelon-dev-kit/tree/main/docs):
18
25
  [installation](https://github.com/goodguys-gmbh/cavelon-dev-kit/blob/main/docs/installation.md)
@@ -45,9 +52,13 @@ This page is a compact reference.
45
52
  standard input instead. **`cavelon` never takes a token as an argument**, so it
46
53
  stays out of shell history. Run it in a terminal of your own: an agent's
47
54
  shell (`!` in Claude Code) has no terminal to type the token into.
48
- 3. `cavelon whoami` shows who the token acts as, its name and when it expires (it
49
- warns from seven days before), and whether it may activate solutions. With a
50
- token that reaches several tenants, choose one: `cavelon use <tenant>`.
55
+ `login` finds the tenants the token reaches: it uses the only one, or asks
56
+ you to choose by number or part of a name. Without a terminal it stores the
57
+ token and prints one `cavelon use <tenant>` line per tenant (exit 2).
58
+ 3. `cavelon whoami` shows who the token acts as, in which tenant (name, slug
59
+ and id), its name and when it expires (it warns from seven days before), and
60
+ whether it may activate solutions. `cavelon use` chooses another tenant from
61
+ the same list.
51
62
 
52
63
  The token goes into the operating system's credential store (Keychain, Windows
53
64
  Credential Manager, Secret Service). Where there is none, it goes into
@@ -67,14 +78,14 @@ Environment variables replace the login:
67
78
  |---|---|
68
79
  | `CAVELON_URL` | the instance URL |
69
80
  | `CAVELON_TOKEN` | a personal access token (`cvpat_…`) or a tenant API key (`cbp_…`); needs `CAVELON_URL` |
70
- | `CAVELON_TENANT` | the tenant slug or id, for a personal token that reaches several tenants |
81
+ | `CAVELON_TENANT` | the tenant's name, slug or id, for a personal token that reaches several tenants |
71
82
 
72
83
  ### Which instance, token and tenant
73
84
 
74
85
  Highest first:
75
86
 
76
- 1. command-line options: `--instance <url>`, `--tenant <tenant>` (there is no
77
- token option);
87
+ 1. command-line options: `--instance <url>`, `--tenant <name, slug or id>`
88
+ (there is no token option);
78
89
  2. `CAVELON_URL`, `CAVELON_TOKEN`, `CAVELON_TENANT`;
79
90
  3. the nearest `cavelon.yaml` from the current directory upwards (instance URL
80
91
  and tenant, never a token);
@@ -97,22 +108,23 @@ Every command takes `--json` (one JSON document on stdout, errors included),
97
108
 
98
109
  | Command | Marked | What it does |
99
110
  |---|---|---|
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. |
100
112
  | `login [--token-stdin]` | changing | Store a token for an instance. A person runs this. |
101
113
  | `logout [--all]` | changing | Delete the stored token. |
102
- | `whoami` | read-only | Owner or key, tenant, role, and where the credential came from. |
103
- | `use <tenant>` / `use --clear` | changing | Choose the tenant for this instance. |
114
+ | `whoami` | read-only | Owner or key, tenant (name, slug and id), role, and where the credential came from. |
115
+ | `use [<tenant>]` / `use --clear` | changing | Choose the tenant for this instance, by name, slug or id, or from a list. |
104
116
  | `status [--offline]` | read-only | Instance, credential, tenant, solution folder, running operations, quotas close to full. |
105
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. |
106
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. |
107
119
  | `models list` | read-only | The tenant's Model Registry rows with their endpoint and `max_concurrent_requests`; never a key. |
108
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. |
109
121
  | `tenant create <slug> [--name] [--use]` | changing | Create a tenant (personal token in Platform mode with `tenants.manage`). |
110
- | `tenant list [--search]` | read-only | Tenants the token can see. |
111
- | `harness list [--readiness]` | read-only | The tenant's solutions. |
122
+ | `tenant list [--search]` | read-only | Tenants the token can see, with name, slug, role and id. |
123
+ | `harness list [--readiness]` | read-only | The tenant's solutions, with slug, name, status and id. |
112
124
  | `harness new <slug> [--name] [--description]` | changing | Create an empty draft solution. |
113
125
  | `harness clone <source> [--slug] [--name] [--no-tests] [--no-triggers]` | changing | Copy a solution into a new draft. |
114
126
  | `activate [--harness] [--env]` | changing | Activate through the readiness gate only, never by force. |
115
- | `init [--harness] [--agents <list>] [--hook] [--update] [--from <file> [--force]]` | changing (files) | Make this folder a solution: `cavelon.yaml`, `package/`, `tests/`, `env/`, `.cavelon/`; `--from` writes a package file into it. |
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. |
116
128
  | `pull [--harness] [--force]` | changing (files) | Write the instance's package into `package/` and `tests/`, the inventory into `.cavelon/`. |
117
129
  | `validate [--offline]` | read-only | Check the package files against the cached package schema. |
118
130
  | `apply [--env] [--harness] [--mode]` | changing | Preview the files against the instance; prints and stores a preview id. |
@@ -376,7 +388,8 @@ op read op://dev/crm/token | cavelon secrets set crm_api_token
376
388
  or sends anything (exit 7, `secret_needs_a_person`, as the instance would
377
389
  answer). MCP offers only `secrets_list`; an agent tells the person the exact
378
390
  `cavelon secrets set <name>` command instead.
379
- - `--env <name>` acts in the tenant `env/<name>.yaml` names, like `apply`.
391
+ - `--env <name>` acts in the tenant `env/<name>.yaml` names, like `apply`. A
392
+ name without its env file is refused (exit 2) before anything is sent.
380
393
 
381
394
  ### Long-running work
382
395
 
@@ -390,10 +403,13 @@ cavelon wait op_test_run_… --timeout 5m
390
403
  `wait` returns when every operation has finished or needs a person, or when the
391
404
  timeout passes. It prints the state in every case; when time ran out, the work
392
405
  goes on, and the same `wait` again resumes it. `watch` streams each change.
393
- An operation only says that the work finished: for a test run, `wait` and
394
- `watch` also read the run's summary, and a run whose cases failed or errored
395
- exits 1 with those cases and the reason the instance recorded (`--json`:
396
- `failed_results`). `trace <test run>` lists every case that did not pass with
406
+ An operation only says that the work finished: for a test run, `wait`,
407
+ `watch` and `test run --wait` also read the run's summary. A run whose cases
408
+ failed or errored, or that measured nothing comparable (steps not run,
409
+ technical errors, missing results, or no pass rate), exits 1 with the counts,
410
+ the failed cases and the reason the instance recorded; a run whose answers
411
+ wait for a manual verdict or for a value a case needs exits 5 (`--json`:
412
+ `failed_results`, each with `counts`, `comparable` and `exit_code`). `trace <test run>` lists every case that did not pass with
397
413
  its error, the judge's reasoning and the command that opens its traces (by its
398
414
  conversation id, or for a trigger case by the run it started), and the judge's
399
415
  reasoning for each scored pass the instance sent it for. `test run --wait` ends,
@@ -445,7 +461,12 @@ cavelon artifacts export orders-test --path output --wait --out results.tar
445
461
 
446
462
  - **`loop start`** calls the trigger's run-now route; the run acts as you (with
447
463
  a personal access token, the person). It returns the run id and the run's
448
- operation id, so `wait` and `watch` follow it; a paused loop makes `wait` exit 5.
464
+ operation id, so `wait` and `watch` follow it (and `trace <operation>` reads
465
+ the run's traces); a paused loop makes `wait` exit 5. It sends an
466
+ `Idempotency-Key` (`--idempotency-key`, a new UUID by default; `--json`:
467
+ `idempotency_key`). When the start ends in exit 8 (a timeout, a cut
468
+ connection, a 5xx), the run may have started: the error's hint names the key,
469
+ and the same command with `--idempotency-key <key>` starts no second run.
449
470
  With `--wait`, a run that ended without starting a loop exits 1 and names the
450
471
  stage that recorded an error.
451
472
  - **`loop watch`** prints each iteration once the loop decided on it: accepted
@@ -468,7 +489,8 @@ cavelon artifacts export orders-test --path output --wait --out results.tar
468
489
  the stage that recorded an error. `loop iterations` reads the same a page at
469
490
  a time; `trace <child_run_id>` reads one iteration's run.
470
491
  - **`loop pause`**, **`loop resume`** send the loop's version and an
471
- `Idempotency-Key` (`--idempotency-key` makes a retry safe); a loop that
492
+ `Idempotency-Key` (`--idempotency-key` makes a retry safe; an exit-8 error
493
+ names the key it sent); a loop that
472
494
  changed in between answers 409 (exit 4). `loop resume --reason` must be the
473
495
  loop's pause reason (exit 2 otherwise, before anything is sent). A pause that
474
496
  needs a review and has none exits 5 (`loop_resume_review_required`) with the
@@ -689,10 +711,18 @@ an agent only with a new plugin or `init --update`. With `cavelon` installed,
689
711
  |---|---|
690
712
  | `~/.config/cavelon/config.json` | the current instance, the tenant chosen with `use`, which store holds the token. Never a token. |
691
713
  | `~/.config/cavelon/credentials.json` | the token per instance (0600), only where there is no OS credential store |
714
+ | `~/.config/cavelon/setup.json` | what `cavelon setup` changed in your coding agents, so `setup --remove` undoes exactly that (0600) |
692
715
  | `~/.cache/cavelon/<instance>/<version>/` | the instance's capabilities, OpenAPI, error catalog, package schema and docs index |
716
+ | `~/.cache/cavelon/update-check.json` | when the latest release was last looked up and announced; `CAVELON_NO_UPDATE_CHECK=1` turns the check off |
693
717
 
694
718
  `CAVELON_CONFIG_DIR` and `CAVELON_CACHE_DIR` move them; `XDG_CONFIG_HOME` and
695
719
  `XDG_CACHE_HOME` are honoured. `CAVELON_CREDENTIAL_STORE=file` skips the OS store.
720
+ A release's cached copies are kept until the instance reports another version.
721
+ A development build (a version with `dev`, `snapshot` or `local` in it) keeps
722
+ one version while what it publishes changes, so its copies are read again after
723
+ a minute, or checked with the ETag the instance sent with them;
724
+ `CAVELON_CONTRACT_TTL_SECONDS` sets that time. `cavelon validate --verbose` says
725
+ which copy of the package schema it used.
696
726
  In the working directory, only `init`, `pull` and `apply` write, as described
697
727
  in "Solution as code", and `artifacts export`, which writes the tar it
698
728
  downloads to a new file.
package/dist/agents.js CHANGED
@@ -1,33 +1,53 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
+ import { embeddedContent } from "./embedded.js";
4
5
  import { usageError } from "./errors.js";
5
6
  import { GENERATED_TOKEN } from "./markers.js";
6
7
  import { KIT_VERSION } from "./version.js";
7
8
  export const MCP_COMMAND = { command: "npx", args: ["-y", "@cavelon/cli@0.1", "mcp"] };
9
+ export const INSTALLED_MCP_COMMAND = { command: "cavelon", args: ["mcp"] };
10
+ export function mcpCommand(platform = process.platform) {
11
+ return platform === "win32" ? { command: "cmd", args: ["/c", MCP_COMMAND.command, ...MCP_COMMAND.args] } : MCP_COMMAND;
12
+ }
13
+ const PLATFORMS = ["win32", "linux"];
14
+ const otherPlatforms = () => PLATFORMS.filter((p) => (p === "win32") !== (process.platform === "win32"));
8
15
  const jsonServer = (file, key = "mcpServers", extra = {}) => ({
9
16
  file,
10
17
  format: "json",
11
18
  keys: [key, "cavelon"],
12
- entry: { ...extra, ...MCP_COMMAND },
19
+ entry: { ...extra, ...mcpCommand() },
20
+ others: [...otherPlatforms().map((p) => ({ ...extra, ...mcpCommand(p) })), { ...extra, ...INSTALLED_MCP_COMMAND }],
13
21
  });
14
- export const AGENTS = [
15
- { name: "claude", label: "Claude Code", mcp: jsonServer(".mcp.json") },
16
- {
17
- name: "codex",
18
- label: "Codex",
19
- mcp: {
20
- file: ".codex/config.toml",
21
- format: "toml",
22
- block: ["[mcp_servers.cavelon]", `command = "${MCP_COMMAND.command}"`, `args = [${MCP_COMMAND.args.map((a) => `"${a}"`).join(", ")}]`].join("\n"),
22
+ const tomlServer = (file) => {
23
+ const block = ({ command, args }) => ["[mcp_servers.cavelon]", `command = "${command}"`, `args = [${args.map((a) => JSON.stringify(a)).join(", ")}]`].join("\n");
24
+ return {
25
+ file,
26
+ format: "toml",
27
+ block: block(mcpCommand()),
28
+ others: [...otherPlatforms().map((p) => block(mcpCommand(p))), block(INSTALLED_MCP_COMMAND)],
29
+ };
30
+ };
31
+ function agent(name, label, mcp) {
32
+ if (!mcp)
33
+ return { name, label };
34
+ return {
35
+ name,
36
+ label,
37
+ get mcp() {
38
+ return mcp();
23
39
  },
24
- },
25
- { name: "cursor", label: "Cursor", mcp: jsonServer(".cursor/mcp.json") },
26
- { name: "copilot", label: "GitHub Copilot in VS Code", mcp: jsonServer(".vscode/mcp.json", "servers", { type: "stdio" }) },
27
- { name: "gemini", label: "Gemini CLI", mcp: jsonServer(".gemini/settings.json") },
28
- { name: "kiro", label: "Kiro", mcp: jsonServer(".kiro/settings/mcp.json") },
29
- { name: "pi", label: "Pi" },
30
- { name: "other", label: "any other agent with a shell" },
40
+ };
41
+ }
42
+ export const AGENTS = [
43
+ agent("claude", "Claude Code", () => jsonServer(".mcp.json")),
44
+ agent("codex", "Codex", () => tomlServer(".codex/config.toml")),
45
+ agent("cursor", "Cursor", () => jsonServer(".cursor/mcp.json")),
46
+ agent("copilot", "GitHub Copilot in VS Code", () => jsonServer(".vscode/mcp.json", "servers", { type: "stdio" })),
47
+ agent("gemini", "Gemini CLI", () => jsonServer(".gemini/settings.json")),
48
+ agent("kiro", "Kiro", () => jsonServer(".kiro/settings/mcp.json")),
49
+ agent("pi", "Pi"),
50
+ agent("other", "any other agent with a shell"),
31
51
  ];
32
52
  const ALIASES = { "claude-code": "claude", vscode: "copilot", "gemini-cli": "gemini" };
33
53
  export function parseAgents(values) {
@@ -51,6 +71,9 @@ export function skillsSource() {
51
71
  return [path.join(here, "skills"), path.resolve(here, "..", "..", "plugin", "skills")];
52
72
  }
53
73
  export async function bundledSkills() {
74
+ const embedded = embeddedContent();
75
+ if (embedded)
76
+ return embedded.skills;
54
77
  for (const dir of skillsSource()) {
55
78
  let entries;
56
79
  try {
@@ -80,10 +103,11 @@ export async function bundledSkills() {
80
103
  }
81
104
  return [];
82
105
  }
83
- export function generatedCopy(file) {
106
+ export function generatedCopy(file, by = "init") {
84
107
  if (!file.path.endsWith(".md"))
85
108
  return file.content;
86
- const mark = `<!-- ${GENERATED_TOKEN}: written by \`cavelon init --agents\` (cavelon ${KIT_VERSION}); \`cavelon init --update\` replaces this file. Put your own notes in another file. -->`;
109
+ const how = by === "init" ? "`cavelon init --agents` (cavelon " + KIT_VERSION + "); `cavelon init --update` replaces this file" : "`cavelon setup` (cavelon " + KIT_VERSION + "); `cavelon setup` replaces it and `cavelon setup --remove` removes it";
110
+ const mark = `<!-- ${GENERATED_TOKEN}: written by ${how}. Put your own notes in another file. -->`;
87
111
  const front = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(file.content);
88
112
  if (front)
89
113
  return `${front[0]}${mark}\n${file.content.slice(front[0].length)}`;
package/dist/choose.js ADDED
@@ -0,0 +1,112 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
2
+ import { readLine } from "./prompt.js";
3
+ export const MAX_LISTED = 20;
4
+ const MAX_TRIES = 5;
5
+ function lower(value) {
6
+ return (value ?? "").toLowerCase();
7
+ }
8
+ export function exactMatch(items, ref) {
9
+ const wanted = ref.trim().toLowerCase();
10
+ return (items.find((t) => t.id === ref.trim()) ??
11
+ items.find((t) => lower(t.slug) === wanted) ??
12
+ (() => {
13
+ const byName = items.filter((t) => lower(t.name) === wanted);
14
+ return byName.length === 1 ? byName[0] : undefined;
15
+ })());
16
+ }
17
+ export function containing(items, text) {
18
+ const wanted = text.trim().toLowerCase();
19
+ return items.filter((t) => lower(t.name).includes(wanted) || lower(t.slug).includes(wanted));
20
+ }
21
+ function editDistance(a, b) {
22
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
23
+ for (let i = 1; i <= a.length; i++) {
24
+ const current = [i];
25
+ for (let j = 1; j <= b.length; j++) {
26
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
27
+ }
28
+ previous = current;
29
+ }
30
+ return previous[b.length];
31
+ }
32
+ export function closest(items, ref, max = 5) {
33
+ const wanted = ref.trim().toLowerCase();
34
+ if (!wanted)
35
+ return items.slice(0, max);
36
+ const scored = items.flatMap((item) => {
37
+ const words = [lower(item.slug), lower(item.name)].filter(Boolean);
38
+ if (words.some((w) => w.includes(wanted)))
39
+ return [{ item, score: 0 }];
40
+ if (words.some((w) => w.length >= 3 && wanted.includes(w)))
41
+ return [{ item, score: 1 }];
42
+ const distance = Math.min(...words.map((w) => editDistance(w, wanted)));
43
+ return distance <= Math.max(2, Math.floor(wanted.length / 3)) ? [{ item, score: distance + 1 }] : [];
44
+ });
45
+ return scored
46
+ .sort((a, b) => a.score - b.score)
47
+ .slice(0, max)
48
+ .map((s) => s.item);
49
+ }
50
+ export function displayName(item) {
51
+ if (item.name && item.slug && item.name !== item.slug)
52
+ return `${item.name} (${item.slug})`;
53
+ return item.name ?? item.slug ?? item.id;
54
+ }
55
+ function line(index, item, extra, preferred) {
56
+ const slug = item.slug && item.slug !== item.name ? ` ${item.slug}` : "";
57
+ const notes = [extra, preferred ? "default, press Enter" : undefined].filter(Boolean).join(", ");
58
+ return ` ${String(index).padStart(2)} ${item.name ?? item.slug ?? item.id}${slug}${notes ? ` (${notes})` : ""}`;
59
+ }
60
+ export async function pick(ctx, options) {
61
+ const write = (text) => ctx.io.stderr.write(`${text}\n`);
62
+ let shown = options.items.slice(0, MAX_LISTED);
63
+ const show = (items) => {
64
+ items.forEach((item, i) => write(line(i + 1, item, options.extra?.(item), item === options.preferred)));
65
+ if (options.other)
66
+ write(` ${String(items.length + 1).padStart(2)} ${options.other.label}`);
67
+ };
68
+ write(options.intro);
69
+ show(shown);
70
+ if (options.items.length > shown.length)
71
+ write(` … and ${options.items.length - shown.length} more: type part of a name to find one.`);
72
+ const hint = shown.length || options.other ? "type its number or part of its name" : "type part of its name";
73
+ for (let tries = 0; tries < MAX_TRIES; tries++) {
74
+ const answer = await readLine(ctx.io, `${options.question} ${ctx.style.dim(`(${hint})`)} `);
75
+ if (!answer) {
76
+ if (options.preferred)
77
+ return { item: options.preferred };
78
+ write("Type a number from the list, or part of a name.");
79
+ continue;
80
+ }
81
+ if (options.other && answer.toLowerCase() === options.other.word)
82
+ return { other: true };
83
+ if (/^\d+$/.test(answer)) {
84
+ const n = Number(answer);
85
+ if (n >= 1 && n <= shown.length)
86
+ return { item: shown[n - 1] };
87
+ if (options.other && n === shown.length + 1)
88
+ return { other: true };
89
+ write(`There is no number ${n} in the list.`);
90
+ continue;
91
+ }
92
+ let found = containing(options.items, answer);
93
+ if (!found.length && options.search)
94
+ found = await options.search(answer);
95
+ const exact = exactMatch(found, answer);
96
+ if (exact)
97
+ return { item: exact };
98
+ if (found.length === 1)
99
+ return { item: found[0] };
100
+ if (!found.length) {
101
+ const near = closest(options.items, answer);
102
+ write(`Nothing is called "${answer}".${near.length ? ` Did you mean ${near.map(displayName).join(", ")}?` : ""} Try another part of the name.`);
103
+ continue;
104
+ }
105
+ shown = found.slice(0, MAX_LISTED);
106
+ write(`${found.length} match "${answer}":`);
107
+ show(shown);
108
+ if (found.length > shown.length)
109
+ write(` … and ${found.length - shown.length} more: type more of the name.`);
110
+ }
111
+ throw new CavelonError(ExitCode.usage, { code: "cancelled", message: "Nothing was chosen.", hint: "Run the command again, or name it with an option." });
112
+ }
package/dist/command.js CHANGED
@@ -2,7 +2,7 @@ import { usageError } from "./errors.js";
2
2
  export const GLOBAL_OPTIONS = {
3
3
  json: { type: "boolean", description: "Print one JSON document instead of text." },
4
4
  instance: { type: "string", value: "<url>", description: "The instance URL (overrides CAVELON_URL and cavelon.yaml)." },
5
- tenant: { type: "string", value: "<tenant>", description: "Tenant slug or id (overrides CAVELON_TENANT and cavelon.yaml)." },
5
+ tenant: { type: "string", value: "<tenant>", description: "Tenant slug, name or id (overrides CAVELON_TENANT and cavelon.yaml)." },
6
6
  help: { type: "boolean", short: "h", description: "Show help for the command." },
7
7
  };
8
8
  export function stringOption(input, name) {
@@ -1,9 +1,11 @@
1
1
  import { promises as fs } from "node:fs";
2
- import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
3
- import { usageError, validationError } from "../errors.js";
2
+ import path from "node:path";
3
+ import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
+ import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
4
5
  import { clip, moreHint, table } from "../format.js";
5
6
  import { readAll } from "../io.js";
6
- import { callOperation } from "../invoke.js";
7
+ import { callOperation, previewRequest } from "../invoke.js";
8
+ import { confinedPath } from "../paths.js";
7
9
  import { describeSchema, findOperation, jsonBodySchema, operations, schemaTypes } from "../openapi.js";
8
10
  import { cavelonCommand } from "../shell.js";
9
11
  export function splitJsonBody(args) {
@@ -43,7 +45,7 @@ export async function readBody(ctx, raw) {
43
45
  if (raw === "-")
44
46
  text = await readAll(ctx.io.stdin);
45
47
  else if (raw.startsWith("@"))
46
- text = await fs.readFile(raw.slice(1), "utf8");
48
+ text = await fs.readFile(await confinedPath(ctx, raw.slice(1), "The body file"), "utf8");
47
49
  try {
48
50
  return JSON.parse(text);
49
51
  }
@@ -63,6 +65,46 @@ function parseParams(input) {
63
65
  }
64
66
  return params;
65
67
  }
68
+ const FOR_A_PERSON = [
69
+ {
70
+ does: "changes a secret",
71
+ hint: "A person sets a secret in their terminal with `cavelon secrets set <name>` (or deletes it with `cavelon secrets delete <name>`).",
72
+ match: (word) => word.includes("secret"),
73
+ },
74
+ {
75
+ does: "creates or revokes a credential",
76
+ hint: "A person creates and revokes tokens and API keys in Cavelon, and signs in with `cavelon login`.",
77
+ match: (word) => /token|api-?keys?|credential|password|mfa/.test(word) || word === "auth",
78
+ },
79
+ {
80
+ does: "decides an approval",
81
+ hint: "A person decides an approval in Cavelon, as someone its approver rule names.",
82
+ match: (word) => word.includes("approv") || word === "decide" || word.startsWith("decision"),
83
+ },
84
+ ];
85
+ function byPathWords(op) {
86
+ const words = op.path.toLowerCase().split("/").filter((word) => word && !word.startsWith("{"));
87
+ return FOR_A_PERSON.find((rule) => words.some((word) => rule.match(word)));
88
+ }
89
+ export function keptForPerson(op, all) {
90
+ if (all.some((o) => o.personOnly)) {
91
+ if (!op.personOnly?.marked)
92
+ return undefined;
93
+ const hint = byPathWords(op)?.hint ?? `A person runs it: in Cavelon, or in their terminal with \`cavelon api ${op.alias}\`.`;
94
+ return { source: "instance", ...(op.personOnly.reason ? { reason: op.personOnly.reason } : {}), hint };
95
+ }
96
+ if (op.readOnly)
97
+ return undefined;
98
+ const rule = byPathWords(op);
99
+ return rule ? { source: "kit", reason: rule.does, hint: rule.hint } : undefined;
100
+ }
101
+ function refusal(op, kept) {
102
+ const named = `${op.alias} (${op.method} ${op.path})`;
103
+ const after = "no tool sends it, with or without confirm.";
104
+ if (kept.source === "kit")
105
+ return `${named} ${kept.reason}; that stays with a person, so ${after}`;
106
+ return `${named} is for a person only, as the instance marks it${kept.reason ? ` (${kept.reason})` : ""}; ${after}`;
107
+ }
66
108
  function truncate(data, limit) {
67
109
  if (limit <= 0)
68
110
  return { data };
@@ -80,7 +122,11 @@ export const api = {
80
122
  summary: "Call any operation the instance publishes in its OpenAPI.",
81
123
  description: "The operation is its operationId or the short name before FastAPI's path suffix (list_harnesses).\n" +
82
124
  "Parameters: -p name=value or name=value. Body: --json '<json>', --json @file.json or --json - (stdin).\n" +
83
- "The body is checked against the operation's schema before it is sent.",
125
+ "The body is checked against the operation's schema before it is sent.\n" +
126
+ "As an MCP tool, an operation that changes something returns what it would send and sends it only with confirm;\n" +
127
+ "one the instance marks for a person only (x-cavelon-person-only) is refused, as are files outside the solution\n" +
128
+ "folder. On an instance that marks none, one that changes a secret, creates or revokes a credential or decides an\n" +
129
+ "approval is refused.",
84
130
  readOnly: false,
85
131
  destructive: true,
86
132
  mcpTool: "api",
@@ -93,6 +139,10 @@ export const api = {
93
139
  body: { type: "string", value: "<json|@file|->", description: "The request body (also accepted as --json <body>)." },
94
140
  file: { type: "string", multiple: true, value: "<field=path>", description: "Attach a file to a multipart body." },
95
141
  output: { type: "string", value: "<file>", description: "Write the response body to a file instead of printing it.", cliOnly: true },
142
+ confirm: {
143
+ type: "boolean",
144
+ description: "As an MCP tool: send an operation that changes something; without it, nothing is sent. The CLI sends at once.",
145
+ },
96
146
  limit: { type: "string", value: "<n>", description: "Show at most n items of a list response (default 50, 0 for all)." },
97
147
  },
98
148
  examples: [
@@ -113,7 +163,27 @@ export const api = {
113
163
  const at = spec.indexOf("=");
114
164
  if (at <= 0)
115
165
  throw usageError(`--file "${spec}" is not field=path.`);
116
- args.files = [...(args.files ?? []), { field: spec.slice(0, at), path: spec.slice(at + 1) }];
166
+ const file = await confinedPath(ctx, spec.slice(at + 1), "The file");
167
+ args.files = [...(args.files ?? []), { field: spec.slice(0, at), path: file }];
168
+ }
169
+ if (ctx.mode === "mcp") {
170
+ const kept = keptForPerson(op, operations(doc));
171
+ if (kept) {
172
+ throw new CavelonError(ExitCode.usage, {
173
+ code: "operation_for_a_person",
174
+ message: refusal(op, kept),
175
+ hint: kept.hint,
176
+ details: { source: kept.source, ...(kept.reason ? { reason: kept.reason } : {}) },
177
+ });
178
+ }
179
+ }
180
+ if (ctx.mode === "mcp" && !op.readOnly && !boolOption(input, "confirm")) {
181
+ const request = previewRequest(doc, op, args);
182
+ const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
183
+ return {
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
+ };
117
187
  }
118
188
  const client = await ctx.client();
119
189
  const result = await callOperation(ctx, client, doc, op, args);
@@ -4,6 +4,7 @@ import { wait, watch } from "./async.js";
4
4
  import { docsGet, docsSearch } from "./docs.js";
5
5
  import { login, logout, status, use, whoami } from "./session.js";
6
6
  import { init } from "./init.js";
7
+ import { setup } from "./setup.js";
7
8
  import { limits } from "./limits.js";
8
9
  import { limitsSet } from "./limits-set.js";
9
10
  import { modelsList, modelsSetLimit } from "./models.js";
@@ -53,6 +54,7 @@ const mcp = {
53
54
  },
54
55
  };
55
56
  export const COMMANDS = [
57
+ setup,
56
58
  login,
57
59
  logout,
58
60
  whoami,