@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
@@ -1,15 +1,18 @@
1
1
  import { table } from "../format.js";
2
2
  import { api, apiDescribe, apiList } from "./api.js";
3
3
  import { wait, watch } from "./async.js";
4
+ import { chat, deactivate } from "./chat.js";
4
5
  import { docsGet, docsSearch } from "./docs.js";
5
6
  import { login, logout, status, use, whoami } from "./session.js";
6
7
  import { init } from "./init.js";
8
+ import { fmt } from "./fmt.js";
7
9
  import { setup } from "./setup.js";
8
10
  import { limits } from "./limits.js";
9
11
  import { limitsSet } from "./limits-set.js";
10
12
  import { modelsList, modelsSetLimit } from "./models.js";
11
13
  import { activate, apply, explain, pull, validate } from "./solution.js";
12
- import { harnessClone, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
14
+ import { schema } from "./schema.js";
15
+ import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
13
16
  import { kbUpload, testRun, trace } from "./work.js";
14
17
  import { secretsDelete, secretsList, secretsSet, variablesDelete, variablesGet, variablesList, variablesSet } from "./values.js";
15
18
  import { loopCancel, loopIterations, loopPause, loopResume, loopStart, loopWatch, triggerIdentity } from "./loops.js";
@@ -67,12 +70,17 @@ export const COMMANDS = [
67
70
  tenantCreate,
68
71
  tenantList,
69
72
  harnessList,
73
+ harnessDefault,
70
74
  harnessNew,
71
75
  harnessClone,
72
76
  activate,
77
+ deactivate,
78
+ chat,
73
79
  init,
74
80
  pull,
75
81
  validate,
82
+ fmt,
83
+ schema,
76
84
  apply,
77
85
  explain,
78
86
  variablesList,
@@ -7,16 +7,17 @@ import { CavelonError, ExitCode, usageError } from "../errors.js";
7
7
  import { confinedPath, realPath, within } from "../paths.js";
8
8
  import { readTextFile, withoutBom, writeFileAtomic } from "../fsutil.js";
9
9
  import { git } from "../git.js";
10
- import { ensureStateDir, STATE_DIR } from "../local-state.js";
10
+ import { ensureStateDir, fileDigests, rememberAppliedFiles, STATE_DIR } from "../local-state.js";
11
11
  import { isGenerated, upsertBlock, upsertJsonEntry } from "../markers.js";
12
12
  import { packageVersionOf } from "../package-check.js";
13
- import { defaultLayoutFor, safeSectionName, schemaSections, toYaml, writePackage } from "../package-files.js";
13
+ import { PERSONA_SECTION, personaYaml, sectionFields } from "../package-format.js";
14
+ import { defaultLayoutFor, placeholdersOnly, safeSectionName, schemaSections, toYaml, writePackage } from "../package-files.js";
14
15
  import { readPrincipal, readTenantless } from "../principal.js";
15
16
  import { ENV_DIR, parseProject, PROJECT_FILE } from "../project.js";
16
17
  import { canAsk, readLine } from "../prompt.js";
17
18
  import { pick } from "../choose.js";
18
- import { harnessNotFoundError, listHarnesses, lookupHarness } from "../harness-ref.js";
19
- import { lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
19
+ import { harnessNotFoundError, listHarnesses, lookupHarness, SLUG, slugFromName } from "../harness-ref.js";
20
+ import { isUuid, lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
20
21
  import { cavelonCommand } from "../shell.js";
21
22
  import { chooseTenant, listsTenants, noTenantError, tenantOpenError, tenantRef, tenantTitle } from "../tenant-choice.js";
22
23
  import { createHarness } from "./tenants.js";
@@ -76,6 +77,17 @@ async function ownFile(root, relative, content) {
76
77
  await writeFileAtomic(file, content);
77
78
  return { file: relative, action: "created" };
78
79
  }
80
+ async function personaPlaceholders(ctx, project) {
81
+ const { schema } = await schemaFor(ctx, project.packageVersion, false).catch(() => ({ schema: null }));
82
+ const fields = sectionFields(schema, PERSONA_SECTION);
83
+ if (!fields)
84
+ return undefined;
85
+ const relative = `${project.layout.package}/${PERSONA_SECTION}.yaml`;
86
+ const action = await ownFile(project.root, relative, personaYaml(null, fields));
87
+ if (action.action === "created")
88
+ await rememberAppliedFiles(project.root, await fileDigests(project.root, [relative]));
89
+ return action;
90
+ }
79
91
  async function generatedFile(root, relative, content) {
80
92
  const file = path.join(root, relative);
81
93
  const existing = await readTextFile(file);
@@ -230,19 +242,6 @@ function solutionYaml(values, tenantNote) {
230
242
  function commentText(text) {
231
243
  return [...text].map((c) => (c < " " || c === "\u007f" ? " " : c)).join("").trim();
232
244
  }
233
- export function slugFromName(name) {
234
- const plain = name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
235
- let slug = plain.replace(/[^a-z0-9]+/g, "-");
236
- while (slug.startsWith("-"))
237
- slug = slug.slice(1);
238
- while (slug.endsWith("-"))
239
- slug = slug.slice(0, -1);
240
- slug = slug.slice(0, 60);
241
- while (slug.endsWith("-"))
242
- slug = slug.slice(0, -1);
243
- return slug;
244
- }
245
- const SLUG = /^[a-z0-9][a-z0-9-]*$/;
246
245
  async function initTenant(ctx, session) {
247
246
  if (session.tokenKind === "api_key")
248
247
  return session.tenant ? { ref: session.tenant } : undefined;
@@ -263,7 +262,7 @@ async function initTenant(ctx, session) {
263
262
  const choice = await chooseTenant(ctx, client, reach);
264
263
  if (choice.kind === "none")
265
264
  throw noTenantError(client.url, false);
266
- if (choice.kind === "open") {
265
+ if (choice.kind !== "chosen") {
267
266
  throw tenantOpenError(client.url, reach, "A solution belongs to one tenant. ", {
268
267
  line: (ref) => cavelonCommand("init", "--tenant", ref),
269
268
  template: "cavelon init --tenant <name or slug>",
@@ -280,7 +279,7 @@ async function initTenant(ctx, session) {
280
279
  const listed = reach?.tenants.find((t) => t.id === placed);
281
280
  return { ref: listed?.slug ?? placed, id: placed, name: listed?.name ?? undefined, slug: listed?.slug ?? undefined };
282
281
  }
283
- async function initHarness(ctx, given) {
282
+ async function initHarness(ctx, given, displayName = given) {
284
283
  if (given) {
285
284
  let lookup;
286
285
  try {
@@ -292,9 +291,25 @@ async function initHarness(ctx, given) {
292
291
  }
293
292
  if (lookup.harness)
294
293
  return { slug: lookup.harness.slug };
295
- if (SLUG.test(given))
296
- return { slug: given, missing: true };
297
- throw harnessNotFoundError(given, lookup.candidates, undefined, (slug) => cavelonCommand("init", "--harness", slug));
294
+ const slug = SLUG.test(given) ? given : slugFromName(given);
295
+ const title = (displayName ?? given).trim().slice(0, 255) || slug;
296
+ const create = cavelonCommand("harness", "new", slug, ...(title !== slug ? ["--name", title] : []));
297
+ if (!slug || isUuid(given) || lookup.candidates.length) {
298
+ const error = harnessNotFoundError(given, lookup.candidates, undefined, (s) => cavelonCommand("init", "--harness", s));
299
+ if (!slug || isUuid(given))
300
+ throw error;
301
+ throw new CavelonError(error.exitCode, {
302
+ code: error.code,
303
+ message: error.message,
304
+ hint: `${error.hint} For a new solution of that name: ${create}, then ${cavelonCommand("init", "--harness", slug)}.`,
305
+ details: error.details,
306
+ });
307
+ }
308
+ if (ctx.mode === "mcp")
309
+ return { slug, missing: true, create };
310
+ const created = await createHarness(ctx, { slug, name: title });
311
+ ctx.io.stderr.write(`Created the draft solution ${created.name} (${created.slug}).\n`);
312
+ return { slug: created.slug, created: true };
298
313
  }
299
314
  let all;
300
315
  try {
@@ -310,7 +325,7 @@ async function initHarness(ctx, given) {
310
325
  let name;
311
326
  if (all.length) {
312
327
  const picked = await pick(ctx, {
313
- intro: `This tenant has ${all.length} solution${all.length === 1 ? "" : "s"}:`,
328
+ intro: `This tenant has ${all.length === 1 ? "1 solution; choose it" : `${all.length} solutions; choose one`}, or start a new one:`,
314
329
  question: "Which solution does this folder hold?",
315
330
  items: all,
316
331
  extra: (h) => h.status,
@@ -343,7 +358,7 @@ function envYaml(name, harness) {
343
358
  return [
344
359
  `# Where \`cavelon apply --env ${name}\` goes. Never a token or a secret value.`,
345
360
  "# tenant: <name, slug or id> # default: the tenant in cavelon.yaml",
346
- harness ? `harness: ${harness}` : "# harness: <slug> # created as a draft when it does not exist yet",
361
+ harness ? `harness: ${harness}` : "# harness: <slug> # must exist: init or `cavelon harness new` creates it",
347
362
  "# mode: overwrite # or replace",
348
363
  "# runtime_bindings: # the package's runtime requirement key -> this tenant's resource id",
349
364
  "# <key>: <id>",
@@ -351,12 +366,17 @@ function envYaml(name, harness) {
351
366
  ].join("\n");
352
367
  }
353
368
  async function hasPackageFiles(root, dir) {
369
+ let names;
354
370
  try {
355
- return (await fs.readdir(path.join(root, dir))).some((n) => /\.(ya?ml|json)$/i.test(n));
371
+ names = (await fs.readdir(path.join(root, dir))).filter((n) => /\.(ya?ml|json)$/i.test(n));
356
372
  }
357
373
  catch {
358
374
  return false;
359
375
  }
376
+ for (const name of names)
377
+ if (!(await placeholdersOnly(root, `${dir}/${name}`)))
378
+ return true;
379
+ return false;
360
380
  }
361
381
  const MAX_PACKAGE_FILE_BYTES = 50 * 1024 * 1024;
362
382
  function importFileError(from, reason, hint) {
@@ -393,6 +413,11 @@ async function readImportFile(ctx, from) {
393
413
  throw importFileError(from, "its top level is not a mapping of sections");
394
414
  return value;
395
415
  }
416
+ function onlyHarnessName(pkg) {
417
+ const harnesses = Array.isArray(pkg.harnesses) ? pkg.harnesses : [];
418
+ const name = harnesses.length === 1 ? harnesses[0]?.name : undefined;
419
+ return typeof name === "string" && name.trim() ? name.trim() : undefined;
420
+ }
396
421
  function onlyHarnessSlug(pkg) {
397
422
  const harnesses = Array.isArray(pkg.harnesses) ? pkg.harnesses : [];
398
423
  if (harnesses.length !== 1)
@@ -408,7 +433,7 @@ async function importPackage(ctx, project, from, pkg, force) {
408
433
  const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
409
434
  const overwritten = [];
410
435
  for (const file of planned.written) {
411
- if ((await readTextFile(path.join(project.root, file))) !== undefined)
436
+ if ((await readTextFile(path.join(project.root, file))) !== undefined && !(await placeholdersOnly(project.root, file)))
412
437
  overwritten.push(file);
413
438
  }
414
439
  const conflicts = [...overwritten, ...planned.removed].sort((a, b) => a.localeCompare(b, "en"));
@@ -494,11 +519,15 @@ async function runInit(ctx, input) {
494
519
  await contracts.errorCatalog().catch(() => null);
495
520
  if (!schema)
496
521
  ctx.warn("The instance does not publish its package schema; `validate` will have nothing to check against.");
497
- const decided = stringOption(input, "harness") ? await initHarness(ctx, stringOption(input, "harness")) : packageHarness ? { slug: packageHarness } : await initHarness(ctx, undefined);
522
+ const decided = stringOption(input, "harness")
523
+ ? await initHarness(ctx, stringOption(input, "harness"))
524
+ : packageHarness
525
+ ? await initHarness(ctx, packageHarness, (imported && onlyHarnessName(imported)) ?? packageHarness)
526
+ : await initHarness(ctx, undefined);
498
527
  chosenHarness = decided;
499
528
  const harness = decided.slug;
500
529
  if (decided.missing)
501
- next.push(`Solution ${harness} is not on the instance yet: \`cavelon apply --env test\` creates it as a draft.`);
530
+ next.push(`Solution ${harness} is not on the instance yet: create it as a draft with ${decided.create}, then cavelon apply --env test.`);
502
531
  const values = { instance: url };
503
532
  if (tenant)
504
533
  values.tenant = tenant.ref;
@@ -517,7 +546,7 @@ async function runInit(ctx, input) {
517
546
  actions.push(...(await folder(root, dir)));
518
547
  }
519
548
  actions.push(...(await folder(root, "seeds")));
520
- const harness = stringOption(input, "harness") ?? project.harness ?? packageHarness;
549
+ const harness = chosenHarness?.slug ?? project.harness ?? stringOption(input, "harness") ?? packageHarness;
521
550
  actions.push(await ownFile(root, `${ENV_DIR}/test.yaml`, envYaml("test", harness)));
522
551
  actions.push(await ownFile(root, `${ENV_DIR}/prod.yaml`, envYaml("prod", undefined)));
523
552
  if (await ensureStateDir(root))
@@ -555,6 +584,9 @@ async function runInit(ctx, input) {
555
584
  }
556
585
  else
557
586
  next.unshift("Bring an existing solution into package/: cavelon pull --harness <name or slug> (or write package files, then cavelon validate)");
587
+ const persona = await personaPlaceholders(ctx, project);
588
+ if (persona)
589
+ actions.push(persona);
558
590
  }
559
591
  return { root, actions, next, imported: result, harness: chosenHarness };
560
592
  }
@@ -569,13 +601,15 @@ export const init = {
569
601
  "file that holds something else unless --force, and names the sections the instance's schema does not know.",
570
602
  readOnly: false,
571
603
  destructive: true,
604
+ mcpEffect: "Changes nothing on the instance (as a tool it never creates a solution; it names the `harness_new` call for one that is missing). Writes files in the solution folder; never overwrites a " +
605
+ "file it did not create, and changes only the blocks between its markers in AGENTS.md, CLAUDE.md and .gitignore.",
572
606
  idempotent: true,
573
607
  mcpTool: "init",
574
608
  options: {
575
609
  harness: {
576
610
  type: "string",
577
611
  value: "<harness>",
578
- description: "The solution (harness) this folder holds, by name, slug or id; its slug goes into cavelon.yaml. Without it, init asks on a terminal.",
612
+ description: "The solution (harness) this folder holds, by name, slug or id; its slug goes into cavelon.yaml. One that is not on the instance yet is created as a draft with that name. Without it, init asks on a terminal.",
579
613
  },
580
614
  agents: {
581
615
  type: "string",
@@ -1,14 +1,50 @@
1
+ import path from "node:path";
1
2
  import { CavelonError } from "../errors.js";
2
3
  import { table } from "../format.js";
4
+ import { readJsonFile } from "../fsutil.js";
3
5
  import { callStable } from "../invoke.js";
4
- import { STATE_DIR, writeState } from "../local-state.js";
6
+ import { STATE_DIR, stateDir, writeState } from "../local-state.js";
5
7
  const LISTINGS = [
6
- { label: "solutions", path: "/api/v1/harnesses" },
7
- { label: "knowledge bases", path: "/api/v1/knowledge-bases", query: { page_size: 100 } },
8
- { label: "tools", path: "/api/v1/tools" },
8
+ { label: "solutions", path: "/api/v1/harnesses", kind: "solutions", field: "slug" },
9
+ { label: "knowledge bases", path: "/api/v1/knowledge-bases", query: { page_size: 100 }, kind: "knowledge_bases", field: "name" },
10
+ { label: "tools", path: "/api/v1/tools", kind: "tools", field: "slug" },
11
+ { label: "skills", path: "/api/v1/skills", kind: "skills", field: "slug" },
12
+ { label: "models", path: "/api/v1/model-registry", kind: "models", field: "model_id" },
9
13
  { label: "test suites", path: "/api/v1/test-suites" },
10
14
  { label: "sandboxes", path: "/api/v1/sandboxes" },
11
15
  ];
16
+ const INVENTORY_JSON = "inventory.json";
17
+ export async function readInventory(root) {
18
+ const inventory = await readJsonFile(path.join(stateDir(root), INVENTORY_JSON));
19
+ return inventory && typeof inventory === "object" && inventory.names && typeof inventory.names === "object" ? inventory : undefined;
20
+ }
21
+ export async function refreshInventory(root, kind, names, now) {
22
+ const inventory = (await readInventory(root)) ?? { written_at: now.toISOString(), names: {} };
23
+ inventory.names[kind] = [...new Set(names)].sort((a, b) => a.localeCompare(b, "en"));
24
+ inventory.refreshed_at = { ...inventory.refreshed_at, [kind]: now.toISOString() };
25
+ await writeState(root, INVENTORY_JSON, `${JSON.stringify(inventory, null, 2)}\n`);
26
+ }
27
+ export async function readInventoryKinds(ctx, root, kinds, now) {
28
+ const failed = [];
29
+ for (const kind of kinds) {
30
+ const listing = LISTINGS.find((l) => l.kind === kind);
31
+ if (!listing) {
32
+ failed.push(kind);
33
+ continue;
34
+ }
35
+ try {
36
+ const data = await callStable(ctx, "GET", listing.path, `listing ${listing.label}`, { query: listing.query });
37
+ const names = itemsOf(data)
38
+ .map((i) => i[listing.field])
39
+ .filter((v) => typeof v === "string");
40
+ await refreshInventory(root, kind, names, now);
41
+ }
42
+ catch {
43
+ failed.push(kind);
44
+ }
45
+ }
46
+ return failed;
47
+ }
12
48
  const MAX_ROWS = 100;
13
49
  const COLUMNS = ["slug", "name", "status", "id"];
14
50
  function itemsOf(data) {
@@ -17,7 +53,7 @@ function itemsOf(data) {
17
53
  }
18
54
  function row(item) {
19
55
  const out = {};
20
- out.slug = item.slug ?? item.key ?? null;
56
+ out.slug = item.slug ?? item.key ?? item.model_id ?? null;
21
57
  out.name = item.name ?? item.display_name ?? null;
22
58
  out.status = item.status ?? item.lifecycle_state ?? item.scope ?? null;
23
59
  out.id = item.id ?? null;
@@ -26,12 +62,15 @@ function row(item) {
26
62
  export async function writeInventory(ctx, root, now) {
27
63
  const sections = [];
28
64
  const counts = [];
65
+ const names = {};
29
66
  for (const listing of LISTINGS) {
30
67
  let body;
31
68
  try {
32
69
  const data = await callStable(ctx, "GET", listing.path, `listing ${listing.label}`, { query: listing.query });
33
70
  const items = itemsOf(data);
34
71
  counts.push({ label: listing.label, count: items.length });
72
+ if (listing.kind)
73
+ names[listing.kind] = [...new Set(items.map((i) => i[listing.field]).filter((v) => typeof v === "string"))].sort((a, b) => a.localeCompare(b, "en"));
35
74
  const rows = items.slice(0, MAX_ROWS).map(row);
36
75
  const columns = COLUMNS.filter((c) => rows.some((r) => r[c] !== null && r[c] !== undefined));
37
76
  body = items.length
@@ -40,6 +79,8 @@ export async function writeInventory(ctx, root, now) {
40
79
  }
41
80
  catch (error) {
42
81
  counts.push({ label: listing.label, count: null });
82
+ if (listing.kind)
83
+ names[listing.kind] = null;
43
84
  body = `Not readable here: ${error instanceof CavelonError ? error.message : String(error)}`;
44
85
  }
45
86
  sections.push(`## ${listing.label[0].toUpperCase()}${listing.label.slice(1)}\n\n${body}`);
@@ -52,5 +93,7 @@ export async function writeInventory(ctx, root, now) {
52
93
  ...sections.flatMap((s) => [s, ""]),
53
94
  ].join("\n");
54
95
  await writeState(root, "inventory.md", text);
96
+ const inventory = { written_at: now.toISOString(), names };
97
+ await writeState(root, INVENTORY_JSON, `${JSON.stringify(inventory, null, 2)}\n`);
55
98
  return { file: `${STATE_DIR}/inventory.md`, counts };
56
99
  }
@@ -1,6 +1,7 @@
1
1
  import { originText } from "../capacity.js";
2
- import { boolOption, positional } from "../command.js";
2
+ import { positional } from "../command.js";
3
3
  import { CavelonError, ExitCode, usageError } from "../errors.js";
4
+ import { confirmation } from "../confirm-token.js";
4
5
  import { callOperation, openapiOrWarn, workflowOperation } from "../invoke.js";
5
6
  import { changedBy, docsPage, formatValue, isOperatorChange, LIMIT_ABOVE_CEILING, limitRef, quotaSetting, readLimits, } from "../limits.js";
6
7
  import { deref, jsonBodySchema, operationForPath, validateBody } from "../openapi.js";
@@ -484,7 +485,7 @@ export const limitsSet = {
484
485
  },
485
486
  ],
486
487
  options: {
487
- confirm: { type: "boolean", description: "Change it; without this nothing is changed." },
488
+ confirm: { type: "boolean", mcpToken: true, description: "Change it; without this nothing is changed." },
488
489
  env: ENV_OPTION,
489
490
  },
490
491
  examples: [
@@ -573,8 +574,9 @@ export const limitsSet = {
573
574
  const allowed = operator
574
575
  ? `a personal access token in Platform mode of a ${anyOf(change.requires_role ?? [], "platform role")}`
575
576
  : `a credential with ${anyOf(change.permissions)} (a session, a personal access token, or an admin API key of the tenant)`;
576
- if (!boolOption(input, "confirm")) {
577
- const confirm = `cavelon limits set ${shellWord(key)} ${shellWord(argText(value))}${flags} --confirm`;
577
+ const gate = await confirmation(ctx, input, "limits_set", { key, value, previous: previous ?? null, operation });
578
+ if (!gate.confirmed) {
579
+ const confirm = gate.confirm(`cavelon limits set ${shellWord(key)} ${shellWord(argText(value))}${flags} --confirm`);
578
580
  const source = target.limit && target.kind === "limit" ? ` (source now: ${target.limit.source}${target.limit.origin ? `, origin: ${target.limit.origin}` : ""})` : "";
579
581
  const what = target.scope === "platform" && target.limit?.tenant_change
580
582
  ? [`This changes the platform's cap for every tenant without its own; --tenant <id|slug> sets one tenant's own cap.`]
@@ -582,8 +584,9 @@ export const limitsSet = {
582
584
  ? [`For tenant ${params.tenant_id[0]} only.`]
583
585
  : [];
584
586
  return {
585
- data: { ...base, changed: false, sent: false, confirm },
586
- text: [`${key}: ${from} → ${to}${source}.`, ...what, `Sends: ${sends}`, `Allowed: ${allowed}.`, `Nothing was changed. Change it with: ${confirm}`].join("\n"),
587
+ data: { ...base, changed: false, sent: false, confirm, ...gate.fields },
588
+ text: [`${key}: ${from} → ${to}${source}.`, ...what, `Sends: ${sends}`, `Allowed: ${allowed}.`, ...(gate.mismatch ? [gate.mismatch] : []), `Nothing was changed. Change it with: ${confirm}`].join("\n"),
589
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
587
590
  };
588
591
  }
589
592
  let result;
@@ -1,6 +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 { confirmation } from "../confirm-token.js";
4
5
  import { idempotencyKey, requireFeature, UUID_KEY_OPTION, withRetryKey } from "../features.js";
5
6
  import { clip, keyValues, moreHint, table } from "../format.js";
6
7
  import { callStable } from "../invoke.js";
@@ -232,7 +233,7 @@ export const loopCancel = {
232
233
  mcpTool: "loop_cancel",
233
234
  positionals: [{ name: "run", description: "The trigger run id (from `loop start`).", required: true }],
234
235
  options: {
235
- confirm: { type: "boolean", description: "Stop the run; without it nothing is stopped." },
236
+ confirm: { type: "boolean", mcpToken: true, description: "Stop the run; without it nothing is stopped." },
236
237
  },
237
238
  examples: ["cavelon loop cancel <run>", "cavelon loop cancel <run> --confirm"],
238
239
  async run(ctx, input) {
@@ -243,14 +244,17 @@ export const loopCancel = {
243
244
  return { data: { cancelled: false, run: runSummary(run, note) }, text: `Run ${run.id} is already ${run.status}; nothing to stop.${noteLines(note)}` };
244
245
  }
245
246
  const loops = (await loopsOf(ctx, run.id)).map(loopSummary);
246
- if (!boolOption(input, "confirm")) {
247
- const confirm = `cavelon loop cancel ${run.id} --confirm`;
247
+ const gate = await confirmation(ctx, input, "loop_cancel", { run: run.id });
248
+ if (!gate.confirmed) {
249
+ const confirm = gate.confirm(`cavelon loop cancel ${run.id} --confirm`);
248
250
  return {
249
- data: { cancelled: false, run: runSummary(run, note), loops, confirm },
251
+ data: { cancelled: false, run: runSummary(run, note), loops, confirm, ...gate.fields },
250
252
  text: `Run ${run.id} (${run.workflow_name}) is ${run.status}` +
251
253
  (loops.length ? `, with loops:\n${table(loops, ["loop_id", "node", "state", "iteration"])}\n` : ".\n") +
252
254
  (note ? `${noteLines(note).slice(1)}\n` : "") +
255
+ (gate.mismatch ? `${gate.mismatch}\n` : "") +
253
256
  `Nothing was stopped. Stop it with: ${confirm}`,
257
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
254
258
  };
255
259
  }
256
260
  const cancelled = await callStable(ctx, "POST", "/api/v1/triggers/runs/{run_id}/cancel", "cancelling runs", { params: { run_id: [run.id] } });
@@ -756,7 +760,7 @@ export const triggerIdentity = {
756
760
  ],
757
761
  options: {
758
762
  clear: { type: "boolean", description: "Remove the binding; scheduled and webhook runs then cannot start." },
759
- confirm: { type: "boolean", description: "Make the change; without it nothing changes." },
763
+ confirm: { type: "boolean", mcpToken: true, description: "Make the change; without it nothing changes." },
760
764
  },
761
765
  examples: ["cavelon trigger identity orders", "cavelon trigger identity orders loop-runner --confirm", "cavelon trigger identity orders --clear --confirm"],
762
766
  async run(ctx, input) {
@@ -777,11 +781,13 @@ export const triggerIdentity = {
777
781
  }
778
782
  const keyName = key && "name" in key ? key.name : wanted;
779
783
  const change = wanted ? `bind API key "${keyName}"` : "clear the binding";
780
- if (!boolOption(input, "confirm")) {
781
- const confirm = cavelonCommand("trigger", "identity", trigger.slug, keyRef ?? "--clear", "--confirm");
784
+ const gate = await confirmation(ctx, input, "trigger_identity", { trigger: trigger.id, from: current.api_key_id ?? null, to: wanted });
785
+ if (!gate.confirmed) {
786
+ const confirm = gate.confirm(cavelonCommand("trigger", "identity", trigger.slug, keyRef ?? "--clear", "--confirm"));
782
787
  return {
783
- data: { trigger: trigger.slug, changed: false, would: change, current: view, confirm },
784
- text: `${identityText(trigger, view)}\n\nNothing changed. To ${change}: ${confirm}`,
788
+ data: { trigger: trigger.slug, changed: false, would: change, current: view, confirm, ...gate.fields },
789
+ text: `${identityText(trigger, view)}\n\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing changed. To ${change}: ${confirm}`,
790
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
785
791
  };
786
792
  }
787
793
  const updated = await callStable(ctx, "PUT", route, "execution identities", {
@@ -1,11 +1,14 @@
1
1
  import { CAPACITY_TUTORIAL_PAGE } from "../capacity.js";
2
- import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption } from "../command.js";
2
+ import { CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption } from "../command.js";
3
3
  import { CavelonError, ExitCode, usageError } from "../errors.js";
4
+ import { confirmation } from "../confirm-token.js";
4
5
  import { moreHint, table } from "../format.js";
5
6
  import { callStable, workflowOperation } from "../invoke.js";
6
7
  import { deref, jsonBodySchema, validateBody } from "../openapi.js";
7
8
  import { cavelonCommand, shellWord } from "../shell.js";
9
+ import { STATE_DIR } from "../local-state.js";
8
10
  import { listedPages } from "./docs.js";
11
+ import { refreshInventory } from "./inventory.js";
9
12
  import { ENV_OPTION, targetFlags } from "./values.js";
10
13
  const LIST_ROUTE = "/api/v1/model-registry";
11
14
  const ROW_ROUTE = "/api/v1/model-registry/{model_registry_id}";
@@ -103,8 +106,12 @@ export const modelsList = {
103
106
  examples: ["cavelon models list", "cavelon models list --json"],
104
107
  async run(ctx, input) {
105
108
  const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
106
- const flags = targetFlags(await ctx.session());
109
+ const session = await ctx.session();
110
+ const flags = targetFlags(session);
107
111
  const rows = await readRows(ctx);
112
+ if (session.project) {
113
+ await refreshInventory(session.project.root, "models", rows.map((r) => r.model_id), ctx.io.now()).catch((error) => ctx.warn(`Could not keep the model list for validate in ${STATE_DIR}/ (${error instanceof Error ? error.message : String(error)}).`));
114
+ }
108
115
  const page = pageOf(rows, limit, stringOption(input, "cursor"));
109
116
  const items = page.items.map((row) => rowView(row, rows));
110
117
  if (!items.length) {
@@ -145,7 +152,7 @@ export const modelsSetLimit = {
145
152
  { name: "limit", description: "Requests the endpoint serves at once (a whole number), or none to clear the limit.", required: true },
146
153
  ],
147
154
  options: {
148
- confirm: { type: "boolean", description: "Change it; without this nothing is changed." },
155
+ confirm: { type: "boolean", mcpToken: true, description: "Change it; without this nothing is changed." },
149
156
  env: ENV_OPTION,
150
157
  },
151
158
  examples: ["cavelon models set-limit llama-70b 8", "cavelon models set-limit llama-70b 8 --confirm", "cavelon models set-limit llama-70b none --confirm"],
@@ -177,11 +184,13 @@ export const modelsSetLimit = {
177
184
  return { data: { ...base, changed: false, sent: false }, text: `${label} already has max_concurrent_requests ${limitText(limit)}; nothing to change.` };
178
185
  }
179
186
  const sharing = model.shares_endpoint_with?.length ? ` It shares the count with ${model.shares_endpoint_with.join(", ")} (same endpoint).` : "";
180
- if (!boolOption(input, "confirm")) {
181
- const confirm = `cavelon models set-limit ${shellWord(row.model_id)} ${limitText(limit)}${flags} --confirm`;
187
+ const gate = await confirmation(ctx, input, "models_set_limit", { row: row.id, previous, limit });
188
+ if (!gate.confirmed) {
189
+ const confirm = gate.confirm(`cavelon models set-limit ${shellWord(row.model_id)} ${limitText(limit)}${flags} --confirm`);
182
190
  return {
183
- data: { ...base, changed: false, sent: false, confirm },
184
- text: `${label}: max_concurrent_requests ${limitText(previous)} → ${limitText(limit)}.${sharing}\nNothing was changed. Change it with: ${confirm}`,
191
+ data: { ...base, changed: false, sent: false, confirm, ...gate.fields },
192
+ text: `${label}: max_concurrent_requests ${limitText(previous)} → ${limitText(limit)}.${sharing}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was changed. Change it with: ${confirm}`,
193
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
185
194
  };
186
195
  }
187
196
  const saved = await callStable(ctx, "PATCH", ROW_ROUTE, "changing Model Registry rows", {
@@ -3,6 +3,7 @@ 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 { confirmation } from "../confirm-token.js";
6
7
  import { confinedPath } from "../paths.js";
7
8
  import { idempotencyKey, instanceModes, requireFeature, stableKey, UUID_KEY_OPTION, withRetryKey } from "../features.js";
8
9
  import { clip, keyValues, moreHint, table } from "../format.js";
@@ -470,7 +471,7 @@ export const sandboxSeed = {
470
471
  options: {
471
472
  harness: HARNESS_OPTION,
472
473
  revision: REVISION_OPTION,
473
- confirm: { type: "boolean", description: "Send it; without it nothing changes." },
474
+ confirm: { type: "boolean", mcpToken: true, description: "Send it; without it nothing changes." },
474
475
  wait: WAIT_OPTION,
475
476
  timeout: TIMEOUT_OPTION,
476
477
  "idempotency-key": UUID_KEY_OPTION,
@@ -496,12 +497,15 @@ export const sandboxSeed = {
496
497
  if (sandbox.writer_owner_run_id)
497
498
  ctx.warn(`Run ${sandbox.writer_owner_run_id} holds the Sandbox's writer; the instance refuses a seed until it ends.`);
498
499
  const what = archive.files >= 0 ? `${archive.files} files in ${archive.directories} folders` : "the tar archive";
499
- if (!boolOption(input, "confirm")) {
500
- const confirm = seedCommand(sandbox, input);
500
+ const gate = await confirmation(ctx, input, "sandbox_seed", { sandbox: sandbox.id, harness, revision, sha256: archive.sha256 });
501
+ if (!gate.confirmed) {
502
+ const confirm = gate.confirm(seedCommand(sandbox, input));
501
503
  return {
502
- data: { ...summary, seeded: false, confirm },
504
+ data: { ...summary, seeded: false, confirm, ...gate.fields },
503
505
  text: `Would replace the workspace of "${sandbox.name}" (${revision}) with ${what}, ${archive.bytes.length} bytes, sha256 ${archive.sha256}.\n` +
506
+ (gate.mismatch ? `${gate.mismatch}\n` : "") +
504
507
  `Nothing was sent. Seed it with: ${confirm}`,
508
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
505
509
  };
506
510
  }
507
511
  const key = stringOption(input, "idempotency-key") !== undefined ? idempotencyKey(input) : stableKey(`seed:${sandbox.id}:${revision}:${archive.sha256}`);