@cavelon/cli 0.1.4 → 0.1.6

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 (50) hide show
  1. package/README.md +58 -22
  2. package/dist/choose.js +8 -4
  3. package/dist/code-hints.js +74 -0
  4. package/dist/commands/api.js +83 -44
  5. package/dist/commands/async.js +26 -5
  6. package/dist/commands/chat.js +177 -0
  7. package/dist/commands/docs.js +240 -37
  8. package/dist/commands/fmt.js +120 -0
  9. package/dist/commands/index.js +9 -1
  10. package/dist/commands/init.js +64 -30
  11. package/dist/commands/inventory.js +48 -5
  12. package/dist/commands/limits-set.js +9 -6
  13. package/dist/commands/loops.js +15 -9
  14. package/dist/commands/models.js +16 -7
  15. package/dist/commands/sandboxes.js +8 -4
  16. package/dist/commands/schema.js +361 -0
  17. package/dist/commands/session.js +148 -24
  18. package/dist/commands/setup.js +22 -6
  19. package/dist/commands/solution.js +537 -76
  20. package/dist/commands/tenants.js +156 -15
  21. package/dist/commands/values.js +18 -9
  22. package/dist/commands/work.js +343 -35
  23. package/dist/confirm-token.js +72 -0
  24. package/dist/contracts.js +3 -0
  25. package/dist/default-route.js +21 -0
  26. package/dist/errors.js +4 -0
  27. package/dist/git.js +14 -5
  28. package/dist/harness-ref.js +14 -1
  29. package/dist/http.js +27 -4
  30. package/dist/invoke.js +8 -4
  31. package/dist/kit-codes.js +91 -0
  32. package/dist/limits.js +12 -1
  33. package/dist/local-state.js +32 -7
  34. package/dist/main.js +52 -4
  35. package/dist/mcp.js +72 -15
  36. package/dist/openapi.js +77 -21
  37. package/dist/operations.js +4 -3
  38. package/dist/package-check.js +361 -12
  39. package/dist/package-files.js +92 -45
  40. package/dist/package-format.js +222 -0
  41. package/dist/package-references.js +298 -0
  42. package/dist/preview-report.js +152 -0
  43. package/dist/results.js +21 -1
  44. package/dist/skills/cavelon-authoring/SKILL.md +98 -13
  45. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  46. package/dist/skills/cavelon-loop/SKILL.md +129 -21
  47. package/dist/skills/cavelon-testing/SKILL.md +130 -10
  48. package/dist/tenant-choice.js +31 -5
  49. package/dist/trace-view.js +172 -0
  50. package/package.json +1 -1
package/README.md CHANGED
@@ -111,22 +111,23 @@ 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, and where the credential came from. |
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. |
125
125
  | `harness clone <source> [--slug] [--name] [--no-tests] [--no-triggers]` | changing | Copy a solution into a new draft. |
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
- | `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. |
128
+ | `pull [--harness] [--force] [--tenant-wide]` | changing (files) | Write the instance's package into `package/` and `tests/`, the inventory into `.cavelon/`. A solution's tenant-wide sections only with `--tenant-wide`. |
129
+ | `validate [--offline] [--strict]` | read-only | Check the package files against the cached package schema, their references, unknown fields and models; `--strict` fails on warnings. |
130
+ | `schema [<section>[.<field>…] \| <type>] [--offline]` | read-only | The package schema's sections, or the fields of a section, a nested field (`agents.handoffs`) or a type, 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…] [--json <body>]` | changing | Call any operation of the instance's OpenAPI. |
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. A test run with failed cases is a failure. |
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 --json '{"name": "FAQ"}'
172
- cavelon api create_knowledge_base --json @kb.json # or --json - for stdin
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
- Parameters are `name=value` or `-p name=value`; the body is checked against the
178
- operation's schema before it is sent. On `api`, `--json` followed by a value is
179
- the body; a bare `--json` is the output switch as everywhere else.
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,
@@ -590,14 +613,24 @@ cavelon activate --harness support
590
613
  one the tenant's full configuration, and splits it along the top-level sections
591
614
  of the instance's published package schema, so no entity type is built into
592
615
  the binary. A file whose content did not change keeps its bytes, so `git diff`
593
- shows what changed on the instance; files of sections the schema does not know
594
- are kept byte for byte. It refuses when package files have uncommitted changes
616
+ shows what changed on the instance; a field the export spells out and the file
617
+ leaves out (an empty list or object, `null`, a default) is no change. A test
618
+ suite goes back to the file it came from (`.cavelon/pulled-files.json` records
619
+ which). Files of sections the schema does not know are kept byte for byte. A
620
+ solution's pull leaves the tenant-wide sections out of the folder (those the
621
+ schema marks `x-cavelon-scope: tenant`; on an instance that marks none,
622
+ `tenant_settings` and `model_registry`) unless `--tenant-wide`. It refuses when package files have uncommitted changes
595
623
  (exit 4) unless `--force`, and writes the tenant's solutions, knowledge bases,
596
624
  tools, test suites and sandboxes to `.cavelon/inventory.md`.
597
625
  - **`validate`** checks the files against the package schema that `init`, `pull`
598
626
  or `apply` cached, and the package version against those the instance accepts.
599
- It contacts the instance only when nothing is cached (never with `--offline`).
600
- Each finding has a file, line, path and code; exit 3 on errors. A Model
627
+ It contacts the instance only when nothing is cached, or to read a tenant's
628
+ list (models, skills, tools, knowledge bases, solutions) the package refers to
629
+ and no command has read yet; never with `--offline`, which names the checks it
630
+ skipped instead. Each finding has a file, line, path and code; exit 3 on
631
+ errors, and with `--strict` on warnings too. A reference the import preview
632
+ will block (`package_reference_unknown`, `package_model_unknown`) keeps the
633
+ summary from saying "Valid". A Model
601
634
  Registry row's `max_concurrent_requests` needs a `base_url`
602
635
  (`model_endpoint_limit_without_base_url`); where the package schema does not
603
636
  carry the field, a warning says the import ignores it.
@@ -681,10 +714,13 @@ The same commands as MCP tools over stdio, for agents that prefer tools to a
681
714
  shell. The tools are coarse, one per workflow command plus `api`, `api_list`,
682
715
  `api_describe`, `docs_search` and `docs_get`, and carry the standard read-only and
683
716
  destructive annotations. The repository tools (`init`, `pull`, `validate`,
684
- `apply`, `explain`, `activate`) and `sandbox_seed` and `artifacts_export` work in
685
- the folder the agent started `cavelon mcp` in. They never block: `kb_upload`,
686
- `test_run`, `loop_start`, `sandbox_seed` and `artifacts_export` return operation
687
- ids, `operation_status` reads them, and `loop_iterations` follows a loop
717
+ `package_schema`, `apply`, `explain`, `activate`) and `sandbox_seed` and
718
+ `artifacts_export` work in the folder the agent started `cavelon mcp` in;
719
+ `init` and `pull` change nothing on the instance. Tools that start work never
720
+ block: `kb_upload`, `test_run`, `loop_start`, `sandbox_seed` and
721
+ `artifacts_export` return operation ids, `operation_status` reads them (at
722
+ once, or waiting up to its `timeout`, at most 50 seconds, with `waited_ms` in
723
+ the answer), and `loop_iterations` follows a loop
688
724
  (`loop watch` and `watch` stream, so they are no tools). `loop_cancel`,
689
725
  `sandbox_seed` and `trigger_identity` are marked destructive and change nothing
690
726
  without `confirm: true`. `limits` is read-only; the server's instructions tell
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 === options.preferred)));
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 hint = shown.length || options.other ? "type its number or part of its name" : "type part of its name";
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.preferred)
77
- return { item: options.preferred };
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
+ }
@@ -1,35 +1,41 @@
1
- import { createHash } from "node:crypto";
2
1
  import { promises as fs } from "node:fs";
3
2
  import path from "node:path";
4
3
  import { AGENT_VARIABLES, drivenByAgent } from "../agent-env.js";
5
- import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
+ import { CURSOR_OPTION, intOption, listOption, pageOf, positional, stringOption, } from "../command.js";
6
5
  import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
7
6
  import { clip, moreHint, table } from "../format.js";
8
7
  import { readAll } from "../io.js";
9
8
  import { callOperation, previewRequest } from "../invoke.js";
10
9
  import { confinedPath } from "../paths.js";
11
- import { describeSchema, findOperation, jsonBodySchema, operations, schemaTypes, secretFields } from "../openapi.js";
12
- import { canonical } from "../package-files.js";
10
+ import { describeSchema, findOperation, jsonBodySchema, matchedLoosely, operations, schemaTypes, secretFields, secretPaths } from "../openapi.js";
11
+ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
12
+ import { CONFIRM_TOKEN, confirmToken, confirmTokenRequired, confirmWith } from "../confirm-token.js";
13
13
  import { cavelonCommand } from "../shell.js";
14
- export function splitJsonBody(args) {
14
+ 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. " +
15
+ "--json alone prints JSON, as on every command.";
16
+ export function splitJsonBody(args, warn) {
15
17
  const out = [];
18
+ let aliased = false;
16
19
  for (let i = 0; i < args.length; i++) {
17
20
  const arg = args[i];
18
21
  if (arg.startsWith("--json=")) {
19
22
  out.push(`--body=${arg.slice("--json=".length)}`);
23
+ aliased = true;
20
24
  continue;
21
25
  }
22
26
  const next = args[i + 1];
23
27
  if (arg === "--json" && next !== undefined && looksLikeBody(next)) {
24
28
  out.push("--body", next);
29
+ aliased = true;
25
30
  i++;
26
31
  continue;
27
32
  }
28
33
  out.push(arg);
29
34
  }
35
+ if (aliased)
36
+ warn?.(JSON_BODY_DEPRECATED);
30
37
  return out;
31
38
  }
32
- const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
33
39
  export function splitConfirm(args) {
34
40
  const out = [];
35
41
  for (let i = 0; i < args.length; i++) {
@@ -72,7 +78,7 @@ export async function readBody(ctx, raw, confine = ctx.mode === "mcp") {
72
78
  return JSON.parse(text);
73
79
  }
74
80
  catch (error) {
75
- throw usageError(`The body is not JSON: ${error instanceof Error ? error.message : String(error)}`, "Pass --json '{\"key\": \"value\"}', @file.json or - for stdin.");
81
+ throw usageError(`The body is not JSON: ${error instanceof Error ? error.message : String(error)}`, "Pass --body '{\"key\": \"value\"}', @file.json or - for stdin.");
76
82
  }
77
83
  }
78
84
  function parseParams(input) {
@@ -150,7 +156,7 @@ function secretsIn(doc, op, args) {
150
156
  }
151
157
  function secretRefusal(op, fields, driven) {
152
158
  const named = fields.map((f) => `"${f}"`).join(", ");
153
- return new CavelonError(ExitCode.usage, {
159
+ return new CavelonError(ExitCode.needsAction, {
154
160
  code: "secret_field_for_a_person",
155
161
  message: `The request to ${op.alias} sets ${named}, which the instance marks as a secret value (x-cavelon-secret); ` +
156
162
  `a person enters secret values, so ${notSentBy(driven)}`,
@@ -158,12 +164,6 @@ function secretRefusal(op, fields, driven) {
158
164
  details: { fields },
159
165
  });
160
166
  }
161
- function confirmToken(target, request, files) {
162
- return createHash("sha256")
163
- .update(canonical({ instance: target.url ?? null, tenant: target.tenant ?? null, request, files }))
164
- .digest("hex")
165
- .slice(0, 12);
166
- }
167
167
  function truncate(data, limit) {
168
168
  if (limit <= 0)
169
169
  return { data };
@@ -176,20 +176,42 @@ function truncate(data, limit) {
176
176
  }
177
177
  return { data };
178
178
  }
179
+ const PERSONA_ROUTE = "/api/v1/bot-persona";
180
+ async function solutionForPersona(ctx, op, params) {
181
+ if (op.path !== PERSONA_ROUTE && !op.path.startsWith(`${PERSONA_ROUTE}/`))
182
+ return;
183
+ if (params.harness_id || !op.parameters.some((p) => p.name === "harness_id" && p.in === "query"))
184
+ return;
185
+ const session = await ctx.session();
186
+ const ref = session.envFile?.harness ?? session.project?.harness;
187
+ if (!ref)
188
+ return;
189
+ const source = session.envFile?.harness ? `env/${session.envFile.name}.yaml` : "cavelon.yaml";
190
+ const { harness, candidates } = await lookupHarness(ctx, ref);
191
+ if (!harness)
192
+ throw harnessNotFoundError(ref, candidates, source, (slug) => `harness_id=<id of ${slug}>`);
193
+ params.harness_id = [harness.id];
194
+ ctx.warn(`Sent harness_id=${harness.id}, the solution ${harness.slug} from ${source}: without it, ${op.alias} reaches the tenant's default route. ` +
195
+ "Pass harness_id=<id> for another solution.");
196
+ }
179
197
  export const api = {
180
198
  name: "api",
181
199
  summary: "Call any operation the instance publishes in its OpenAPI.",
182
200
  description: "The operation is its operationId or the short name before FastAPI's path suffix (list_harnesses).\n" +
183
- "Parameters: -p name=value or name=value. Body: --json '<json>', --json @file.json or --json - (stdin).\n" +
201
+ "Parameters: -p name=value or name=value (not --name). Body: --body '<json>', --body @file.json or --body - (stdin);\n" +
202
+ "--json <body> still works for now but is deprecated: --json alone prints JSON, as on every command.\n" +
184
203
  "The body is checked against the operation's schema before it is sent.\n" +
185
204
  "As an MCP tool, or run by a coding agent (" +
186
205
  AGENT_VARIABLES.filter((v) => v.variable !== "CAVELON_AGENT").map((v) => v.variable).join(", ") +
187
- "\nor CAVELON_AGENT=1 is set), an operation that changes something returns what it would send and sends it only\n" +
188
- "with confirm (as an MCP tool) or --confirm <token> (the token the preview printed).\n" +
206
+ "\nor CAVELON_AGENT=1 is set), an operation that changes something returns what it would send and a confirm token,\n" +
207
+ "and sends it only with that token: --confirm <token>, or confirm: \"<token>\" as an MCP tool. A changed request\n" +
208
+ "needs a new preview; confirm: true is refused.\n" +
189
209
  "Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
190
210
  "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
191
211
  "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
192
- "approval is refused. A person's own terminal sends at once.",
212
+ "approval is refused. A person's own terminal sends at once.\n" +
213
+ "In a solution folder, the persona operations (get_bot_persona, upsert_bot_persona, …) get the folder's solution as\n" +
214
+ "harness_id when none is passed, since without it they reach the tenant's default route.",
193
215
  readOnly: false,
194
216
  destructive: true,
195
217
  mcpTool: "api",
@@ -199,14 +221,14 @@ export const api = {
199
221
  ],
200
222
  options: {
201
223
  param: { type: "string", short: "p", multiple: true, value: "<name=value>", description: "A path, query or header parameter." },
202
- body: { type: "string", value: "<json|@file|->", description: "The request body (also accepted as --json <body>)." },
224
+ body: { type: "string", value: "<json|@file|->", description: "The request body: JSON, @file.json or - for stdin (--json <body> is a deprecated alias)." },
203
225
  file: { type: "string", multiple: true, value: "<field=path>", description: "Attach a file to a multipart body." },
204
226
  output: { type: "string", value: "<file>", description: "Write the response body to a file instead of printing it.", cliOnly: true },
205
227
  confirm: {
206
228
  type: "string",
207
229
  value: "<token>",
208
- mcpBoolean: true,
209
- description: "Send an operation that changes something: run by a coding agent, the token its preview printed; as an MCP tool, true. " +
230
+ mcpToken: true,
231
+ description: "Send an operation that changes something: run by a coding agent or as an MCP tool, the token its preview returned. " +
210
232
  "Without it, nothing is sent. A person's terminal sends at once.",
211
233
  },
212
234
  limit: { type: "string", value: "<n>", description: "Show at most n items of a list response (default 50, 0 for all)." },
@@ -214,16 +236,19 @@ export const api = {
214
236
  examples: [
215
237
  "cavelon api list_harnesses",
216
238
  "cavelon api get_harness_by_slug slug=support",
217
- "cavelon api create_knowledge_base --json '{\"name\": \"FAQ\"}'",
239
+ "cavelon api create_knowledge_base --body '{\"name\": \"FAQ\"}'",
218
240
  ],
219
- preprocess: (args) => splitConfirm(splitJsonBody(args)),
241
+ preprocess: (args, warn) => splitConfirm(splitJsonBody(args, warn)),
220
242
  async run(ctx, input) {
221
243
  const name = positional(input, "operation");
222
244
  const doc = await (await ctx.contracts()).openapi();
223
245
  const op = findOperation(doc, name);
246
+ if (matchedLoosely(op, name))
247
+ ctx.warn(`"${name}" is taken as ${op.alias} (${op.method} ${op.path}).`);
224
248
  const driven = drivenByAgent(ctx);
225
249
  const confine = driven !== undefined;
226
250
  const args = { params: parseParams(input) };
251
+ await solutionForPersona(ctx, op, args.params);
227
252
  const rawBody = stringOption(input, "body");
228
253
  if (rawBody !== undefined)
229
254
  args.body = await readBody(ctx, rawBody, confine);
@@ -239,7 +264,7 @@ export const api = {
239
264
  if (driven) {
240
265
  const kept = keptForPerson(op, operations(doc));
241
266
  if (kept) {
242
- throw new CavelonError(ExitCode.usage, {
267
+ throw new CavelonError(ExitCode.needsAction, {
243
268
  code: "operation_for_a_person",
244
269
  message: refusal(op, kept, driven),
245
270
  hint: personHint(kept.hint, driven),
@@ -275,27 +300,26 @@ export const api = {
275
300
  },
276
301
  };
277
302
  async function previewUnlessConfirmed(ctx, input, doc, op, args, driven) {
278
- if (driven.by === "mcp" && boolOption(input, "confirm"))
279
- return undefined;
303
+ const given = input.options.confirm;
304
+ if (given === true)
305
+ throw confirmTokenRequired("api");
280
306
  const request = previewRequest(doc, op, args);
281
307
  const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
282
- const shown = { operation: op.alias, ...request, ...(files.length ? { files } : {}), sent: false };
283
- if (driven.by === "mcp") {
284
- return {
285
- data: { ...shown, confirm: "Call api again with the same arguments and confirm: true." },
286
- text: `Would send ${request.method} ${request.path}. Nothing was sent.`,
287
- };
288
- }
289
308
  const session = await ctx.session();
290
- const token = confirmToken({ url: session.url, tenant: session.tenant }, request, files);
291
- const given = stringOption(input, "confirm");
292
- if (given === token)
309
+ const token = confirmToken({ url: session.url, tenant: session.tenant }, "api", { request, files });
310
+ if (typeof given === "string" && given === token)
293
311
  return undefined;
294
- const stale = Boolean(given);
295
- const confirm = `Show the person this request, then run the same command again with --confirm ${token} to send exactly it.`;
312
+ const stale = typeof given === "string" && given !== "";
313
+ const bare = given === "" && driven.by === "agent";
314
+ const confirm = driven.by === "mcp"
315
+ ? confirmWith("api", token)
316
+ : `Show the person this request, then run the same command again with --confirm ${token} to send exactly it.`;
317
+ const shown = { operation: op.alias, ...request, ...(files.length ? { files } : {}), sent: false };
296
318
  const lines = [`Would send ${request.method} ${request.path}. Nothing was sent.`];
297
319
  if (stale)
298
- lines.push("The --confirm token is not this request's: the request changed since its preview, or the token is another one's.");
320
+ lines.push("The confirm token is not this request's: the request changed since its preview, or the token is another one's.");
321
+ if (bare && driven.by === "agent")
322
+ lines.push(`--confirm alone does not send it when a coding agent runs cavelon (${driven.variable} is set).`);
299
323
  if (Object.keys(request.query).length)
300
324
  lines.push(`Query: ${JSON.stringify(request.query)}`);
301
325
  if (Object.keys(request.headers).length)
@@ -306,9 +330,9 @@ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven) {
306
330
  lines.push(`File: ${f.field} = ${f.file}`);
307
331
  lines.push(confirm);
308
332
  return {
309
- data: { ...shown, confirm_token: token, confirm, ...(stale ? { token_mismatch: true } : {}) },
333
+ data: { ...shown, confirm_token: token, confirm, ...(stale ? { token_mismatch: true } : {}), ...(bare ? { token_required: true } : {}) },
310
334
  text: lines.join("\n"),
311
- ...(stale ? { exitCode: ExitCode.conflict } : {}),
335
+ ...(stale ? { exitCode: ExitCode.conflict } : bare ? { exitCode: ExitCode.needsAction } : {}),
312
336
  };
313
337
  }
314
338
  export const apiList = {
@@ -322,7 +346,7 @@ export const apiList = {
322
346
  search: { type: "string", value: "<text>", description: "Only operations whose name, path or summary contains the text." },
323
347
  method: { type: "string", value: "<method>", description: "Only this HTTP method (GET, POST, …)." },
324
348
  tags: { type: "boolean", description: "List the tags with their operation counts instead." },
325
- limit: LIMIT_OPTION,
349
+ limit: { type: "string", value: "<n>", description: "Return at most n operations (default 50, 0 for all)." },
326
350
  cursor: CURSOR_OPTION,
327
351
  },
328
352
  async run(ctx, input) {
@@ -349,7 +373,8 @@ export const apiList = {
349
373
  if (search) {
350
374
  ops = ops.filter((o) => [o.operationId, o.path, o.summary ?? ""].some((s) => s.toLowerCase().includes(search)));
351
375
  }
352
- const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
376
+ const wanted = intOption(input, "limit", { min: 0, max: 1000, fallback: 50 });
377
+ const limit = wanted === 0 ? Math.max(ops.length, 1) : wanted;
353
378
  const page = pageOf(ops.map((o) => ({
354
379
  operation: o.alias,
355
380
  operation_id: o.operationId,
@@ -377,18 +402,25 @@ export const apiDescribe = {
377
402
  positionals: [{ name: "operation", description: "operationId or its short name.", required: true }],
378
403
  async run(ctx, input) {
379
404
  const doc = await (await ctx.contracts()).openapi();
380
- const op = findOperation(doc, positional(input, "operation"));
405
+ const name = positional(input, "operation");
406
+ const op = findOperation(doc, name);
407
+ if (matchedLoosely(op, name))
408
+ ctx.warn(`"${name}" is taken as ${op.alias}; that is the name \`cavelon api\` takes.`);
381
409
  const bodyTypes = Object.keys(op.requestBody?.content ?? {});
382
410
  const bodySchema = jsonBodySchema(op) ?? op.requestBody?.content?.[bodyTypes[0] ?? ""]?.schema;
383
411
  const responses = Object.fromEntries(Object.entries(op.responses)
384
412
  .filter(([code]) => code.startsWith("2"))
385
413
  .map(([code, r]) => [code, describeSchema(doc, r.content?.["application/json"]?.schema)]));
414
+ const kept = keptForPerson(op, operations(doc));
415
+ const secrets = secretPaths(doc, bodySchema);
386
416
  const data = {
387
417
  operation: op.alias,
388
418
  operation_id: op.operationId,
389
419
  method: op.method,
390
420
  path: op.path,
391
421
  read_only: op.readOnly,
422
+ person_only: kept ? { source: kept.source, reason: kept.reason ?? null, hint: kept.hint } : null,
423
+ secret_fields: secrets,
392
424
  tags: op.tags,
393
425
  summary: op.summary ?? null,
394
426
  description: op.description ? clip(op.description, 1500) : null,
@@ -405,6 +437,13 @@ export const apiDescribe = {
405
437
  responses,
406
438
  };
407
439
  const lines = [`${op.method} ${op.path} (${op.readOnly ? "read-only" : "changing"})`, op.summary ?? ""];
440
+ if (kept) {
441
+ lines.push(kept.source === "instance"
442
+ ? `For a person only (x-cavelon-person-only${kept.reason ? `: ${kept.reason}` : ""}): an agent does not send it. ${kept.hint}`
443
+ : `For a person: it ${kept.reason}, and this instance marks no operation, so an agent does not send it. ${kept.hint}`);
444
+ }
445
+ if (secrets.length)
446
+ lines.push(`Secret values (x-cavelon-secret): ${secrets.join(", ")}. A person enters them; an agent leaves them out.`);
408
447
  if (data.description && data.description !== op.summary)
409
448
  lines.push("", data.description);
410
449
  if (data.parameters.length) {
@@ -6,6 +6,7 @@ import { failureLines, resultFailure } from "../results.js";
6
6
  import { readEvents } from "../sse.js";
7
7
  export const DEFAULT_WAIT = "90s";
8
8
  const MCP_TIMEOUT_MS = 0;
9
+ export const MCP_MAX_WAIT_MS = 50_000;
9
10
  export const TIMEOUT_OPTION = {
10
11
  type: "string",
11
12
  value: "<duration>",
@@ -20,10 +21,22 @@ function intervalMs(ctx) {
20
21
  const fromEnv = Number(ctx.io.env.CAVELON_POLL_INTERVAL_MS);
21
22
  return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 1000;
22
23
  }
24
+ function waitTimeoutMs(ctx, raw) {
25
+ if (ctx.mode !== "mcp")
26
+ return parseDuration(raw ?? DEFAULT_WAIT);
27
+ if (raw === undefined || raw === "")
28
+ return 0;
29
+ const asked = parseDuration(raw);
30
+ if (asked > MCP_MAX_WAIT_MS) {
31
+ ctx.warn(`operation_status waits at most ${MCP_MAX_WAIT_MS / 1000} s, not ${raw}; call it again to keep waiting.`);
32
+ return MCP_MAX_WAIT_MS;
33
+ }
34
+ return asked;
35
+ }
23
36
  export async function waitAndReport(ctx, ids, timeout) {
24
37
  const client = await ctx.client();
25
38
  const progress = !ctx.json && ctx.io.stderr.isTTY && ctx.mode === "cli";
26
- const { operations, timedOut } = await waitFor(ctx, client, ids, {
39
+ const { operations, timedOut, waitedMs } = await waitFor(ctx, client, ids, {
27
40
  timeoutMs: timeout,
28
41
  intervalMs: intervalMs(ctx),
29
42
  onChange: progress ? (op) => ctx.io.stderr.write(`${ctx.style.dim(describe(op).split("\n")[0])}\n`) : undefined,
@@ -39,6 +52,8 @@ export async function waitAndReport(ctx, ids, timeout) {
39
52
  operations,
40
53
  settled: pending.length === 0,
41
54
  timed_out: timedOut,
55
+ timeout_ms: timeout,
56
+ waited_ms: waitedMs,
42
57
  ...(pending.length ? { resume: `cavelon wait ${pending.join(" ")}` } : {}),
43
58
  ...(waits.length ? { capacity_waits: waits } : {}),
44
59
  ...(refusals.length ? { capacity_refusals: refusals } : {}),
@@ -59,19 +74,25 @@ export const wait = {
59
74
  name: "wait",
60
75
  summary: "Wait until operations finish, need a person, or the timeout passes.",
61
76
  description: "Exit 0 when all succeeded, 1 when one failed or was cancelled, 5 when one needs a person,\n" +
62
- "6 when the timeout passed first. A test run that finished with failed cases counts as failed, and its cases are named.\n" +
63
- "The state is printed in every case, and a second `wait` resumes.",
77
+ "6 when one still runs at the end (timed_out says whether it waited the whole timeout; --timeout 0 reads the state once).\n" +
78
+ "A test run that finished with failed cases counts as failed, and its cases are named.\n" +
79
+ "The state is printed in every case with waited_ms, and a second `wait` resumes. As the MCP tool operation_status it\n" +
80
+ `returns the state at once unless given a timeout, and waits at most ${MCP_MAX_WAIT_MS / 1000} s.`,
64
81
  readOnly: true,
65
82
  idempotent: true,
66
83
  mcpTool: "operation_status",
67
84
  positionals: [{ name: "operation", description: "Operation ids (op_…).", required: true, variadic: true }],
68
85
  options: {
69
- timeout: TIMEOUT_OPTION,
86
+ timeout: {
87
+ ...TIMEOUT_OPTION,
88
+ description: `Stop waiting after this long (90s, 5m; default ${DEFAULT_WAIT}). The work goes on; run wait again to resume. ` +
89
+ `As an MCP tool: none by default (returns at once), at most ${MCP_MAX_WAIT_MS / 1000}s.`,
90
+ },
70
91
  },
71
92
  examples: ["cavelon wait op_test_run_0f…", "cavelon wait op_a op_b --timeout 5m --json"],
72
93
  async run(ctx, input) {
73
94
  const ids = input.positionals.operation.filter(Boolean);
74
- return waitAndReport(ctx, [...new Set(ids)], timeoutMs(ctx, stringOption(input, "timeout")));
95
+ return waitAndReport(ctx, [...new Set(ids)], waitTimeoutMs(ctx, stringOption(input, "timeout")));
75
96
  },
76
97
  };
77
98
  export const watch = {