@cavelon/cli 0.1.1 → 0.1.2

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
@@ -376,7 +376,8 @@ op read op://dev/crm/token | cavelon secrets set crm_api_token
376
376
  or sends anything (exit 7, `secret_needs_a_person`, as the instance would
377
377
  answer). MCP offers only `secrets_list`; an agent tells the person the exact
378
378
  `cavelon secrets set <name>` command instead.
379
- - `--env <name>` acts in the tenant `env/<name>.yaml` names, like `apply`.
379
+ - `--env <name>` acts in the tenant `env/<name>.yaml` names, like `apply`. A
380
+ name without its env file is refused (exit 2) before anything is sent.
380
381
 
381
382
  ### Long-running work
382
383
 
@@ -390,10 +391,13 @@ cavelon wait op_test_run_… --timeout 5m
390
391
  `wait` returns when every operation has finished or needs a person, or when the
391
392
  timeout passes. It prints the state in every case; when time ran out, the work
392
393
  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
394
+ An operation only says that the work finished: for a test run, `wait`,
395
+ `watch` and `test run --wait` also read the run's summary. A run whose cases
396
+ failed or errored, or that measured nothing comparable (steps not run,
397
+ technical errors, missing results, or no pass rate), exits 1 with the counts,
398
+ the failed cases and the reason the instance recorded; a run whose answers
399
+ wait for a manual verdict or for a value a case needs exits 5 (`--json`:
400
+ `failed_results`, each with `counts`, `comparable` and `exit_code`). `trace <test run>` lists every case that did not pass with
397
401
  its error, the judge's reasoning and the command that opens its traces (by its
398
402
  conversation id, or for a trigger case by the run it started), and the judge's
399
403
  reasoning for each scored pass the instance sent it for. `test run --wait` ends,
@@ -445,7 +449,12 @@ cavelon artifacts export orders-test --path output --wait --out results.tar
445
449
 
446
450
  - **`loop start`** calls the trigger's run-now route; the run acts as you (with
447
451
  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.
452
+ operation id, so `wait` and `watch` follow it (and `trace <operation>` reads
453
+ the run's traces); a paused loop makes `wait` exit 5. It sends an
454
+ `Idempotency-Key` (`--idempotency-key`, a new UUID by default; `--json`:
455
+ `idempotency_key`). When the start ends in exit 8 (a timeout, a cut
456
+ connection, a 5xx), the run may have started: the error's hint names the key,
457
+ and the same command with `--idempotency-key <key>` starts no second run.
449
458
  With `--wait`, a run that ended without starting a loop exits 1 and names the
450
459
  stage that recorded an error.
451
460
  - **`loop watch`** prints each iteration once the loop decided on it: accepted
@@ -468,7 +477,8 @@ cavelon artifacts export orders-test --path output --wait --out results.tar
468
477
  the stage that recorded an error. `loop iterations` reads the same a page at
469
478
  a time; `trace <child_run_id>` reads one iteration's run.
470
479
  - **`loop pause`**, **`loop resume`** send the loop's version and an
471
- `Idempotency-Key` (`--idempotency-key` makes a retry safe); a loop that
480
+ `Idempotency-Key` (`--idempotency-key` makes a retry safe; an exit-8 error
481
+ names the key it sent); a loop that
472
482
  changed in between answers 409 (exit 4). `loop resume --reason` must be the
473
483
  loop's pause reason (exit 2 otherwise, before anything is sent). A pause that
474
484
  needs a review and has none exits 5 (`loop_resume_review_required`) with the
@@ -693,6 +703,12 @@ an agent only with a new plugin or `init --update`. With `cavelon` installed,
693
703
 
694
704
  `CAVELON_CONFIG_DIR` and `CAVELON_CACHE_DIR` move them; `XDG_CONFIG_HOME` and
695
705
  `XDG_CACHE_HOME` are honoured. `CAVELON_CREDENTIAL_STORE=file` skips the OS store.
706
+ A release's cached copies are kept until the instance reports another version.
707
+ A development build (a version with `dev`, `snapshot` or `local` in it) keeps
708
+ one version while what it publishes changes, so its copies are read again after
709
+ a minute, or checked with the ETag the instance sent with them;
710
+ `CAVELON_CONTRACT_TTL_SECONDS` sets that time. `cavelon validate --verbose` says
711
+ which copy of the package schema it used.
696
712
  In the working directory, only `init`, `pull` and `apply` write, as described
697
713
  in "Solution as code", and `artifacts export`, which writes the tar it
698
714
  downloads to a new file.
package/dist/agents.js CHANGED
@@ -5,29 +5,45 @@ import { usageError } from "./errors.js";
5
5
  import { GENERATED_TOKEN } from "./markers.js";
6
6
  import { KIT_VERSION } from "./version.js";
7
7
  export const MCP_COMMAND = { command: "npx", args: ["-y", "@cavelon/cli@0.1", "mcp"] };
8
+ export function mcpCommand(platform = process.platform) {
9
+ return platform === "win32" ? { command: "cmd", args: ["/c", MCP_COMMAND.command, ...MCP_COMMAND.args] } : MCP_COMMAND;
10
+ }
11
+ const PLATFORMS = ["win32", "linux"];
12
+ const otherPlatforms = () => PLATFORMS.filter((p) => (p === "win32") !== (process.platform === "win32"));
8
13
  const jsonServer = (file, key = "mcpServers", extra = {}) => ({
9
14
  file,
10
15
  format: "json",
11
16
  keys: [key, "cavelon"],
12
- entry: { ...extra, ...MCP_COMMAND },
17
+ entry: { ...extra, ...mcpCommand() },
18
+ others: otherPlatforms().map((p) => ({ ...extra, ...mcpCommand(p) })),
13
19
  });
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"),
20
+ const tomlServer = (file) => {
21
+ const block = (platform) => {
22
+ const { command, args } = mcpCommand(platform);
23
+ return ["[mcp_servers.cavelon]", `command = "${command}"`, `args = [${args.map((a) => `"${a}"`).join(", ")}]`].join("\n");
24
+ };
25
+ return { file, format: "toml", block: block(process.platform), others: otherPlatforms().map(block) };
26
+ };
27
+ function agent(name, label, mcp) {
28
+ if (!mcp)
29
+ return { name, label };
30
+ return {
31
+ name,
32
+ label,
33
+ get mcp() {
34
+ return mcp();
23
35
  },
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" },
36
+ };
37
+ }
38
+ export const AGENTS = [
39
+ agent("claude", "Claude Code", () => jsonServer(".mcp.json")),
40
+ agent("codex", "Codex", () => tomlServer(".codex/config.toml")),
41
+ agent("cursor", "Cursor", () => jsonServer(".cursor/mcp.json")),
42
+ agent("copilot", "GitHub Copilot in VS Code", () => jsonServer(".vscode/mcp.json", "servers", { type: "stdio" })),
43
+ agent("gemini", "Gemini CLI", () => jsonServer(".gemini/settings.json")),
44
+ agent("kiro", "Kiro", () => jsonServer(".kiro/settings/mcp.json")),
45
+ agent("pi", "Pi"),
46
+ agent("other", "any other agent with a shell"),
31
47
  ];
32
48
  const ALIASES = { "claude-code": "claude", vscode: "copilot", "gemini-cli": "gemini" };
33
49
  export function parseAgents(values) {
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,7 +4,8 @@ import { parseDocument } from "yaml";
4
4
  import { boolOption, listOption, stringOption } from "../command.js";
5
5
  import { AGENTS, bundledSkills, generatedCopy, parseAgents, SKILL_ROOTS } from "../agents.js";
6
6
  import { CavelonError, ExitCode, usageError } from "../errors.js";
7
- import { readTextFile, writeFileAtomic } from "../fsutil.js";
7
+ import { confinedPath, realPath, within } from "../paths.js";
8
+ import { readTextFile, withoutBom, writeFileAtomic } from "../fsutil.js";
8
9
  import { git } from "../git.js";
9
10
  import { ensureStateDir, STATE_DIR } from "../local-state.js";
10
11
  import { isGenerated, upsertBlock, upsertJsonEntry } from "../markers.js";
@@ -117,6 +118,8 @@ async function writeSkills(root, roots) {
117
118
  async function writeMcp(root, target, onlyExisting) {
118
119
  const file = path.join(root, target.file);
119
120
  const existing = await readTextFile(file);
121
+ if (existing !== undefined && holdsOtherForm(existing, target))
122
+ return { file: target.file, action: "unchanged" };
120
123
  if (target.format === "toml")
121
124
  return applyBlock(root, file, upsertBlock(existing, target.block, "hash", { onlyExisting }));
122
125
  if (onlyExisting) {
@@ -136,6 +139,20 @@ async function writeMcp(root, target, onlyExisting) {
136
139
  }
137
140
  return applyBlock(root, file, result);
138
141
  }
142
+ function holdsOtherForm(existing, target) {
143
+ if (target.format === "toml") {
144
+ const text = existing.replace(/\r\n/g, "\n");
145
+ return target.others.some((block) => text.includes(`# cavelon:begin\n${block}\n# cavelon:end`));
146
+ }
147
+ let current;
148
+ try {
149
+ current = target.keys.reduce((node, key) => (node && typeof node === "object" ? node[key] : undefined), JSON.parse(existing));
150
+ }
151
+ catch {
152
+ return false;
153
+ }
154
+ return target.others.some((entry) => JSON.stringify(entry) === JSON.stringify(current));
155
+ }
139
156
  async function installedFallback(root) {
140
157
  const skillRoots = [];
141
158
  for (const skillRoot of SKILL_ROOTS) {
@@ -168,6 +185,18 @@ async function installHook(root, onlyExisting) {
168
185
  return { file: ".git/hooks/pre-commit", action: "skipped", reason: "this folder is not in a git repository" };
169
186
  }
170
187
  const file = path.resolve(root, hooks, "pre-commit");
188
+ const top = (await git(["rev-parse", "--show-toplevel"], root))?.trim();
189
+ const common = (await git(["rev-parse", "--git-common-dir"], root))?.trim();
190
+ const own = [top, common].filter((dir) => Boolean(dir)).map((dir) => path.resolve(root, dir));
191
+ const hooksDir = await realPath(path.dirname(file));
192
+ const inside = await Promise.all(own.map(async (dir) => within(await realPath(dir), hooksDir)));
193
+ if (!inside.includes(true)) {
194
+ return {
195
+ file: rel(root, file),
196
+ action: "skipped",
197
+ reason: `core.hooksPath points to ${path.dirname(file)}, outside this repository, where other repositories' hooks may be; add the block yourself if you want it there`,
198
+ };
199
+ }
171
200
  const body = HOOK_LINES(prefix).join("\n");
172
201
  const existing = await readTextFile(file);
173
202
  let result = upsertBlock(existing, body, "hash", { onlyExisting, afterShebang: true });
@@ -216,14 +245,14 @@ function importFileError(from, reason, hint) {
216
245
  hint: hint ?? "Pass a package export: a JSON or YAML file with one key per section (manifest, harnesses, agents, …).",
217
246
  });
218
247
  }
219
- async function readImportFile(cwd, from) {
220
- const file = path.resolve(cwd, from);
248
+ async function readImportFile(ctx, from) {
249
+ const file = await confinedPath(ctx, from, "The package file");
221
250
  const stat = await fs.stat(file).catch(() => undefined);
222
251
  if (!stat?.isFile())
223
252
  throw usageError(`No file ${from}.`, "Pass the path of a package export (JSON or YAML) to --from.");
224
253
  if (stat.size > MAX_PACKAGE_FILE_BYTES)
225
254
  throw importFileError(from, `it is larger than ${MAX_PACKAGE_FILE_BYTES / 1024 / 1024} MB`);
226
- const text = (await readTextFile(file)) ?? "";
255
+ const text = withoutBom((await readTextFile(file)) ?? "");
227
256
  let value;
228
257
  if (/\.json$/i.test(file)) {
229
258
  try {
@@ -297,7 +326,7 @@ async function runInit(ctx, input) {
297
326
  throw usageError("--from and --update do not go together.", "Run `cavelon init --from <file>` and `cavelon init --update` one after the other.");
298
327
  if (boolOption(input, "force") && !from)
299
328
  throw usageError("--force only applies to --from.");
300
- const imported = from ? await readImportFile(ctx.io.cwd, from) : undefined;
329
+ const imported = from ? await readImportFile(ctx, from) : undefined;
301
330
  if (update) {
302
331
  if (!session.project)
303
332
  throw usageError("No cavelon.yaml here or above.", "Run `cavelon init` first.");
@@ -418,7 +447,7 @@ export const init = {
418
447
  multiple: true,
419
448
  description: `Write the fallback for these agents: ${AGENTS.map((a) => a.name).join(", ")} or all (comma-separated).`,
420
449
  },
421
- hook: { type: "boolean", description: "Add a git pre-commit hook that runs `cavelon validate`." },
450
+ hook: { type: "boolean", description: "Add a git pre-commit hook that runs `cavelon validate`; never in a hooks folder outside the repository." },
422
451
  update: { type: "boolean", description: "Only bring the marked blocks and fallback files to this version." },
423
452
  from: { type: "string", value: "<file>", description: "Write this package file (a JSON or YAML export) into package/ and tests/." },
424
453
  force: { type: "boolean", description: "With --from: replace package files that hold something else." },
@@ -389,10 +389,10 @@ async function previousValue(ctx, published, target) {
389
389
  if (target.flag)
390
390
  return target.flag.enabled;
391
391
  if (target.kind === "quota") {
392
+ if (target.quota)
393
+ return capValue(target.quota.value);
392
394
  const row = await quotaSetting(ctx, published, target.key).catch(() => undefined);
393
- if (row && (typeof row.value === "number" || row.value === null))
394
- return row.value;
395
- return target.quota ? target.quota.value : undefined;
395
+ return row && (typeof row.value === "number" || row.value === null) ? row.value : undefined;
396
396
  }
397
397
  const limit = target.limit;
398
398
  if (target.scope === "one_tenant")
@@ -401,11 +401,16 @@ async function previousValue(ctx, published, target) {
401
401
  return limit.source === "tenant" ? undefined : limit.value;
402
402
  return limit.value;
403
403
  }
404
+ function capValue(value) {
405
+ return typeof value === "number" && value <= 0 ? null : value;
406
+ }
404
407
  function noChange(target, previous, value, from) {
405
408
  if (target.flag)
406
409
  return previous === value ? `${target.key} is already ${from} (${target.flag.setting})` : undefined;
407
- if (target.kind === "quota")
408
- return previous !== undefined && sameValue(previous, value) ? `${target.key} is already ${from}` : undefined;
410
+ if (target.kind === "quota") {
411
+ const wanted = target.quota ? capValue(value) : value;
412
+ return previous !== undefined && sameValue(previous, wanted) ? `${target.key} is already ${from}` : undefined;
413
+ }
409
414
  const limit = target.limit;
410
415
  if (target.scope === "one_tenant") {
411
416
  if (value === null && previous === null)
@@ -449,6 +454,10 @@ function answeredValue(target, data, sent) {
449
454
  const own = changed.find((c) => c?.setting === target.limit?.setting);
450
455
  return { value: own && "new" in own ? own.new : sent, changed };
451
456
  }
457
+ function reportsChange(changes) {
458
+ const pairs = changes.filter((c) => typeof c === "object" && c !== null && "old" in c && "new" in c);
459
+ return pairs.length < changes.length || changes.length === 0 || pairs.some((c) => !sameValue(c.old, c.new));
460
+ }
452
461
  function explicitTenant(session) {
453
462
  return session.tenantSource === "option" && Boolean(session.tenant);
454
463
  }
@@ -615,7 +624,7 @@ export const limitsSet = {
615
624
  ...(answered.source ? { source: answered.source } : {}),
616
625
  ...(answered.origin ? { origin: answered.origin } : {}),
617
626
  changes: answered.changed,
618
- changed: true,
627
+ changed: reportsChange(answered.changed),
619
628
  sent: true,
620
629
  },
621
630
  text: `Changed ${key}: ${from} → ${now}${where}.`,
@@ -62,7 +62,7 @@ export const limits = {
62
62
  if (!published.published) {
63
63
  ctx.warn("This instance does not publish its limits (it is older than the limits in /api/v1/meta/capabilities); none is assumed.");
64
64
  return {
65
- data: { published: false, groups: [], tenant_quotas: null, near: [], branch_concurrency: null },
65
+ data: { published: false, groups: [], tenant_quotas: null, quota_values: [], near: [], branch_concurrency: null },
66
66
  text: "This instance does not publish its limits. Commands send as they are, and the instance answers for itself.",
67
67
  };
68
68
  }
@@ -1,7 +1,7 @@
1
1
  import { noteLines, runCapacityNote } from "../capacity.js";
2
2
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, positional, stringOption, } from "../command.js";
3
3
  import { CavelonError, ExitCode, usageError } from "../errors.js";
4
- import { idempotencyKey, requireFeature, UUID_KEY_OPTION } from "../features.js";
4
+ import { idempotencyKey, requireFeature, UUID_KEY_OPTION, withRetryKey } from "../features.js";
5
5
  import { clip, keyValues, moreHint, table } from "../format.js";
6
6
  import { callStable } from "../invoke.js";
7
7
  import { catalogEntry } from "../package-check.js";
@@ -179,6 +179,7 @@ export const loopStart = {
179
179
  input: { type: "string", value: "<json|@file|->", description: "The run's payload: JSON, @file.json or - for stdin." },
180
180
  wait: WAIT_OPTION,
181
181
  timeout: TIMEOUT_OPTION,
182
+ "idempotency-key": UUID_KEY_OPTION,
182
183
  },
183
184
  examples: ["cavelon loop start counter", "cavelon loop start orders --input @orders-request.json --json"],
184
185
  async run(ctx, input) {
@@ -188,13 +189,17 @@ export const loopStart = {
188
189
  const payload = raw === undefined ? {} : await readBody(ctx, raw);
189
190
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
190
191
  throw usageError("--input must be a JSON object.");
192
+ const key = idempotencyKey(input);
191
193
  const run = await callStable(ctx, "POST", "/api/v1/triggers/{trigger_id}/run", "starting triggers", {
192
194
  params: { trigger_id: [trigger.id] },
195
+ headers: { "Idempotency-Key": key },
193
196
  body: { payload },
197
+ }).catch((error) => {
198
+ throw withRetryKey(error, key);
194
199
  });
195
200
  if (!trigger.is_active)
196
201
  ctx.warn(`Trigger "${trigger.slug}" is not active: its schedule and webhook start no runs, though this manual start did.`);
197
- const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run) };
202
+ const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run), idempotency_key: key };
198
203
  if (boolOption(input, "wait") && ctx.mode === "cli" && run.operation_id) {
199
204
  const waited = await waitAndReport(ctx, [run.operation_id], timeoutMs(ctx, stringOption(input, "timeout")));
200
205
  const text = `Started run ${run.id} of ${trigger.slug}.\n${waited.text}`;
@@ -601,13 +606,14 @@ function controlCommand(action) {
601
606
  let receipt;
602
607
  try {
603
608
  receipt = await callStable(ctx, "POST", `/api/v1/triggers/runs/{run_id}/loops/{loop_id}/${action}`, `${action} loops`, {
604
- params: { run_id: [loop.owner_run_id], loop_id: [loop.id], "Idempotency-Key": [key] },
609
+ params: { run_id: [loop.owner_run_id], loop_id: [loop.id] },
610
+ headers: { "Idempotency-Key": key },
605
611
  body: { expected_version: loop.version, ...(reason ? { reviewed_reason: reason } : {}) },
606
612
  });
607
613
  }
608
614
  catch (error) {
609
- if (pausing || !(error instanceof CavelonError))
610
- throw error;
615
+ if (pausing || !(error instanceof CavelonError) || error.exitCode === ExitCode.server)
616
+ throw withRetryKey(error, key);
611
617
  throw await resumeRefused(ctx, error, loop, reason);
612
618
  }
613
619
  const text = pausing
@@ -3,8 +3,10 @@ import { promises as fs } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, positional, stringOption, } from "../command.js";
5
5
  import { CavelonError, ExitCode, usageError } from "../errors.js";
6
- import { idempotencyKey, instanceModes, requireFeature, stableKey, UUID_KEY_OPTION } from "../features.js";
6
+ import { confinedPath } from "../paths.js";
7
+ import { idempotencyKey, instanceModes, requireFeature, stableKey, UUID_KEY_OPTION, withRetryKey } from "../features.js";
7
8
  import { clip, keyValues, moreHint, table } from "../format.js";
9
+ import { bodyBytes } from "../http.js";
8
10
  import { buildRequest, callStable, workflowOperation } from "../invoke.js";
9
11
  import { isUuid } from "../session.js";
10
12
  import { cavelonCommand } from "../shell.js";
@@ -170,7 +172,8 @@ export const sandboxValidate = {
170
172
  async run(ctx, input) {
171
173
  const sandbox = await resolveSandbox(ctx, positional(input, "sandbox"));
172
174
  const result = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/validate", "validating Sandboxes", {
173
- params: { sandbox_id: [sandbox.id], "if-match": [`"${sandbox.config_version}"`] },
175
+ params: { sandbox_id: [sandbox.id] },
176
+ headers: { "If-Match": `"${sandbox.config_version}"` },
174
177
  timeoutMs: 90_000,
175
178
  });
176
179
  const checks = result.readiness?.checks ?? [];
@@ -386,9 +389,13 @@ export const sandboxRefresh = {
386
389
  async run(ctx, input) {
387
390
  const sandbox = await resolveSandbox(ctx, positional(input, "sandbox"));
388
391
  requireOffer(ctx, sandbox, "refresh", "sandbox refresh");
392
+ const key = idempotencyKey(input);
389
393
  const result = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/refresh-workspace", "refreshing Sandboxes", {
390
- params: { sandbox_id: [sandbox.id], "idempotency-key": [idempotencyKey(input)], "if-match": [`"${sandbox.config_version}"`] },
394
+ params: { sandbox_id: [sandbox.id] },
395
+ headers: { "Idempotency-Key": key, "If-Match": `"${sandbox.config_version}"` },
391
396
  timeoutMs: 90_000,
397
+ }).catch((error) => {
398
+ throw withRetryKey(error, key);
392
399
  });
393
400
  return {
394
401
  data: { ...sandboxView(result), previous_revision: sandbox.observed_revision },
@@ -472,7 +479,7 @@ export const sandboxSeed = {
472
479
  async run(ctx, input) {
473
480
  const sandbox = await resolveSandbox(ctx, positional(input, "sandbox"));
474
481
  requireOffer(ctx, sandbox, "archive", "sandbox seed");
475
- const source = path.resolve(ctx.io.cwd, positional(input, "source"));
482
+ const source = await confinedPath(ctx, positional(input, "source"), "The source");
476
483
  const archive = await archiveFrom(source, await maxArchiveBytes(ctx));
477
484
  const harness = await harnessFor(ctx, input, sandbox);
478
485
  const revision = await currentRevision(ctx, input, sandbox, harness);
@@ -499,7 +506,8 @@ export const sandboxSeed = {
499
506
  }
500
507
  const key = stringOption(input, "idempotency-key") !== undefined ? idempotencyKey(input) : stableKey(`seed:${sandbox.id}:${revision}:${archive.sha256}`);
501
508
  let job = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/artifact-jobs", "archive jobs", {
502
- params: { sandbox_id: [sandbox.id], "idempotency-key": [key] },
509
+ params: { sandbox_id: [sandbox.id] },
510
+ headers: { "Idempotency-Key": key },
503
511
  body: { harness_id: harness, direction: "import", expected_workspace_revision: revision, sha256: archive.sha256, size_bytes: archive.bytes.length },
504
512
  });
505
513
  const until = Date.now() + UPLOAD_READY_MS;
@@ -535,12 +543,9 @@ async function upload(ctx, sandboxId, jobId, bytes) {
535
543
  const client = await ctx.client();
536
544
  const { op } = await workflowOperation(ctx, "PUT", `${JOB_ROUTE}/content`, "archive uploads");
537
545
  const { path: target } = buildRequest(op, { params: { sandbox_id: [sandboxId], job_id: [jobId] }, bytes });
538
- const response = await client.fetchRaw("PUT", target, {
539
- bytes,
540
- headers: { "Content-Type": "application/octet-stream" },
541
- signal: AbortSignal.timeout(Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 120_000),
542
- });
543
- const text = await response.text();
546
+ const signal = AbortSignal.timeout(Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 120_000);
547
+ const response = await client.fetchRaw("PUT", target, { bytes, headers: { "Content-Type": "application/octet-stream" }, signal });
548
+ const text = new TextDecoder().decode(await bodyBytes(response, client.resolve(target), signal));
544
549
  let data = text;
545
550
  try {
546
551
  data = JSON.parse(text);
@@ -554,15 +559,13 @@ async function upload(ctx, sandboxId, jobId, bytes) {
554
559
  async function download(ctx, sandbox, job, out) {
555
560
  if (!isUuid(job.id))
556
561
  throw new CavelonError(ExitCode.failure, { code: "invalid_job_id", message: `The instance returned an unexpected job id.` });
557
- const file = path.resolve(ctx.io.cwd, out ?? `sandbox-${job.id}.tar`);
562
+ const file = await confinedPath(ctx, out ?? `sandbox-${job.id}.tar`, "The archive file");
558
563
  const client = await ctx.client();
559
564
  const { op } = await workflowOperation(ctx, "GET", `${JOB_ROUTE}/content`, "archive downloads");
560
565
  const { path: target } = buildRequest(op, { params: { sandbox_id: [sandbox.id], job_id: [job.id] } });
561
- const response = await client.fetchRaw("GET", target, {
562
- accept: "application/x-tar",
563
- signal: AbortSignal.timeout(Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 120_000),
564
- });
565
- const bytes = new Uint8Array(await response.arrayBuffer());
566
+ const signal = AbortSignal.timeout(Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 120_000);
567
+ const response = await client.fetchRaw("GET", target, { accept: "application/x-tar", signal });
568
+ const bytes = await bodyBytes(response, client.resolve(target), signal);
566
569
  if (!response.ok) {
567
570
  const text = new TextDecoder().decode(bytes);
568
571
  let data = text;
@@ -633,9 +636,13 @@ export const artifactsExport = {
633
636
  const harness = await harnessFor(ctx, input, sandbox);
634
637
  const revision = await currentRevision(ctx, input, sandbox, harness);
635
638
  const paths = listOption(input, "path");
639
+ const key = idempotencyKey(input);
636
640
  job = await callStable(ctx, "POST", "/api/v1/sandboxes/{sandbox_id}/artifact-jobs", "archive jobs", {
637
- params: { sandbox_id: [sandbox.id], "idempotency-key": [idempotencyKey(input)] },
641
+ params: { sandbox_id: [sandbox.id] },
642
+ headers: { "Idempotency-Key": key },
638
643
  body: { harness_id: harness, direction: "export", expected_workspace_revision: revision, ...(paths.length ? { paths } : {}) },
644
+ }).catch((error) => {
645
+ throw withRetryKey(error, key);
639
646
  });
640
647
  }
641
648
  const later = cavelonCommand("artifacts", "export", sandbox.name, "--job", job.id, ...(out ? ["--out", out] : []));
@@ -10,7 +10,7 @@ import { readAll } from "../io.js";
10
10
  import { listPreviews, readPull } from "../local-state.js";
11
11
  import { expiryOf, readPrincipal } from "../principal.js";
12
12
  import { readHidden } from "../prompt.js";
13
- import { lookupTenantId, requireInstance, requireToken } from "../session.js";
13
+ import { lookupTenantId, requireInstance, requireToken, TENANT_REF_HINT } from "../session.js";
14
14
  import { loadUserConfig, saveUserConfig, tokenKind, updateInstance } from "../user-config.js";
15
15
  async function readCapabilities(contracts, refresh) {
16
16
  const caps = await contracts.capabilities({ refresh });
@@ -77,13 +77,17 @@ export const login = {
77
77
  let tenant;
78
78
  if (session.tenant && kind !== "api_key") {
79
79
  const found = await lookupTenantId(client, session.tenant);
80
- if (!found)
81
- throw new CavelonError(ExitCode.failure, { code: "tenant_not_found", message: `No tenant "${session.tenant}" for this token.` });
80
+ if (!found) {
81
+ throw new CavelonError(ExitCode.failure, { code: "tenant_not_found", message: `No tenant "${session.tenant}" for this token.`, hint: TENANT_REF_HINT });
82
+ }
82
83
  tenant = { ref: session.tenant, ...found };
83
84
  client.target.tenantId = found.id;
84
85
  }
85
86
  const { caps, needsTenant } = await readCapabilities(contracts, true);
86
87
  const me = await readMe(client);
88
+ if (!caps && !needsTenant && !me) {
89
+ await client.get("/api/v1/knowledge-bases", { query: { page_size: 1 }, allow: [400, 403, 404, 422] });
90
+ }
87
91
  if (needsTenant && !me) {
88
92
  throw new CavelonError(ExitCode.validation, {
89
93
  code: "tenant_required",
@@ -286,7 +290,7 @@ export const use = {
286
290
  throw new CavelonError(ExitCode.failure, {
287
291
  code: "tenant_not_found",
288
292
  message: `No tenant "${ref}" that this token can see.`,
289
- hint: "`cavelon tenant list` shows the tenants and their ids.",
293
+ hint: TENANT_REF_HINT,
290
294
  });
291
295
  }
292
296
  const probe = new ApiClient({ ...client.target, tenantId: found.id }, ctx.io.env);