@cavelon/cli 0.1.4 → 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 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, 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. |
@@ -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…] [--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,
@@ -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 `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
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
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
+ }
@@ -8,25 +8,33 @@ import { clip, moreHint, table } from "../format.js";
8
8
  import { readAll } from "../io.js";
9
9
  import { callOperation, previewRequest } from "../invoke.js";
10
10
  import { confinedPath } from "../paths.js";
11
- import { describeSchema, findOperation, jsonBodySchema, operations, schemaTypes, secretFields } from "../openapi.js";
11
+ import { describeSchema, findOperation, jsonBodySchema, matchedLoosely, operations, schemaTypes, secretFields } from "../openapi.js";
12
12
  import { canonical } from "../package-files.js";
13
+ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
13
14
  import { cavelonCommand } from "../shell.js";
14
- export function splitJsonBody(args) {
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) {
15
18
  const out = [];
19
+ let aliased = false;
16
20
  for (let i = 0; i < args.length; i++) {
17
21
  const arg = args[i];
18
22
  if (arg.startsWith("--json=")) {
19
23
  out.push(`--body=${arg.slice("--json=".length)}`);
24
+ aliased = true;
20
25
  continue;
21
26
  }
22
27
  const next = args[i + 1];
23
28
  if (arg === "--json" && next !== undefined && looksLikeBody(next)) {
24
29
  out.push("--body", next);
30
+ aliased = true;
25
31
  i++;
26
32
  continue;
27
33
  }
28
34
  out.push(arg);
29
35
  }
36
+ if (aliased)
37
+ warn?.(JSON_BODY_DEPRECATED);
30
38
  return out;
31
39
  }
32
40
  const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
@@ -72,7 +80,7 @@ export async function readBody(ctx, raw, confine = ctx.mode === "mcp") {
72
80
  return JSON.parse(text);
73
81
  }
74
82
  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.");
83
+ throw usageError(`The body is not JSON: ${error instanceof Error ? error.message : String(error)}`, "Pass --body '{\"key\": \"value\"}', @file.json or - for stdin.");
76
84
  }
77
85
  }
78
86
  function parseParams(input) {
@@ -176,11 +184,30 @@ function truncate(data, limit) {
176
184
  }
177
185
  return { data };
178
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
+ }
179
205
  export const api = {
180
206
  name: "api",
181
207
  summary: "Call any operation the instance publishes in its OpenAPI.",
182
208
  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" +
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" +
184
211
  "The body is checked against the operation's schema before it is sent.\n" +
185
212
  "As an MCP tool, or run by a coding agent (" +
186
213
  AGENT_VARIABLES.filter((v) => v.variable !== "CAVELON_AGENT").map((v) => v.variable).join(", ") +
@@ -189,7 +216,9 @@ export const api = {
189
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" +
190
217
  "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
191
218
  "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.",
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.",
193
222
  readOnly: false,
194
223
  destructive: true,
195
224
  mcpTool: "api",
@@ -199,7 +228,7 @@ export const api = {
199
228
  ],
200
229
  options: {
201
230
  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>)." },
231
+ body: { type: "string", value: "<json|@file|->", description: "The request body: JSON, @file.json or - for stdin (--json <body> is a deprecated alias)." },
203
232
  file: { type: "string", multiple: true, value: "<field=path>", description: "Attach a file to a multipart body." },
204
233
  output: { type: "string", value: "<file>", description: "Write the response body to a file instead of printing it.", cliOnly: true },
205
234
  confirm: {
@@ -214,16 +243,19 @@ export const api = {
214
243
  examples: [
215
244
  "cavelon api list_harnesses",
216
245
  "cavelon api get_harness_by_slug slug=support",
217
- "cavelon api create_knowledge_base --json '{\"name\": \"FAQ\"}'",
246
+ "cavelon api create_knowledge_base --body '{\"name\": \"FAQ\"}'",
218
247
  ],
219
- preprocess: (args) => splitConfirm(splitJsonBody(args)),
248
+ preprocess: (args, warn) => splitConfirm(splitJsonBody(args, warn)),
220
249
  async run(ctx, input) {
221
250
  const name = positional(input, "operation");
222
251
  const doc = await (await ctx.contracts()).openapi();
223
252
  const op = findOperation(doc, name);
253
+ if (matchedLoosely(op, name))
254
+ ctx.warn(`"${name}" is taken as ${op.alias} (${op.method} ${op.path}).`);
224
255
  const driven = drivenByAgent(ctx);
225
256
  const confine = driven !== undefined;
226
257
  const args = { params: parseParams(input) };
258
+ await solutionForPersona(ctx, op, args.params);
227
259
  const rawBody = stringOption(input, "body");
228
260
  if (rawBody !== undefined)
229
261
  args.body = await readBody(ctx, rawBody, confine);
@@ -377,7 +409,10 @@ export const apiDescribe = {
377
409
  positionals: [{ name: "operation", description: "operationId or its short name.", required: true }],
378
410
  async run(ctx, input) {
379
411
  const doc = await (await ctx.contracts()).openapi();
380
- const op = findOperation(doc, positional(input, "operation"));
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.`);
381
416
  const bodyTypes = Object.keys(op.requestBody?.content ?? {});
382
417
  const bodySchema = jsonBodySchema(op) ?? op.requestBody?.content?.[bodyTypes[0] ?? ""]?.schema;
383
418
  const responses = Object.fromEntries(Object.entries(op.responses)
@@ -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 = {