@cavelon/cli 0.1.5 → 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.
@@ -16,8 +16,8 @@ import { readPrincipal, readTenantless } from "../principal.js";
16
16
  import { ENV_DIR, parseProject, PROJECT_FILE } from "../project.js";
17
17
  import { canAsk, readLine } from "../prompt.js";
18
18
  import { pick } from "../choose.js";
19
- import { harnessNotFoundError, listHarnesses, lookupHarness } from "../harness-ref.js";
20
- 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";
21
21
  import { cavelonCommand } from "../shell.js";
22
22
  import { chooseTenant, listsTenants, noTenantError, tenantOpenError, tenantRef, tenantTitle } from "../tenant-choice.js";
23
23
  import { createHarness } from "./tenants.js";
@@ -242,19 +242,6 @@ function solutionYaml(values, tenantNote) {
242
242
  function commentText(text) {
243
243
  return [...text].map((c) => (c < " " || c === "\u007f" ? " " : c)).join("").trim();
244
244
  }
245
- export function slugFromName(name) {
246
- const plain = name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
247
- let slug = plain.replace(/[^a-z0-9]+/g, "-");
248
- while (slug.startsWith("-"))
249
- slug = slug.slice(1);
250
- while (slug.endsWith("-"))
251
- slug = slug.slice(0, -1);
252
- slug = slug.slice(0, 60);
253
- while (slug.endsWith("-"))
254
- slug = slug.slice(0, -1);
255
- return slug;
256
- }
257
- const SLUG = /^[a-z0-9][a-z0-9-]*$/;
258
245
  async function initTenant(ctx, session) {
259
246
  if (session.tokenKind === "api_key")
260
247
  return session.tenant ? { ref: session.tenant } : undefined;
@@ -292,7 +279,7 @@ async function initTenant(ctx, session) {
292
279
  const listed = reach?.tenants.find((t) => t.id === placed);
293
280
  return { ref: listed?.slug ?? placed, id: placed, name: listed?.name ?? undefined, slug: listed?.slug ?? undefined };
294
281
  }
295
- async function initHarness(ctx, given) {
282
+ async function initHarness(ctx, given, displayName = given) {
296
283
  if (given) {
297
284
  let lookup;
298
285
  try {
@@ -304,9 +291,25 @@ async function initHarness(ctx, given) {
304
291
  }
305
292
  if (lookup.harness)
306
293
  return { slug: lookup.harness.slug };
307
- if (SLUG.test(given))
308
- return { slug: given, missing: true };
309
- 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 };
310
313
  }
311
314
  let all;
312
315
  try {
@@ -322,7 +325,7 @@ async function initHarness(ctx, given) {
322
325
  let name;
323
326
  if (all.length) {
324
327
  const picked = await pick(ctx, {
325
- 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:`,
326
329
  question: "Which solution does this folder hold?",
327
330
  items: all,
328
331
  extra: (h) => h.status,
@@ -355,7 +358,7 @@ function envYaml(name, harness) {
355
358
  return [
356
359
  `# Where \`cavelon apply --env ${name}\` goes. Never a token or a secret value.`,
357
360
  "# tenant: <name, slug or id> # default: the tenant in cavelon.yaml",
358
- 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",
359
362
  "# mode: overwrite # or replace",
360
363
  "# runtime_bindings: # the package's runtime requirement key -> this tenant's resource id",
361
364
  "# <key>: <id>",
@@ -410,6 +413,11 @@ async function readImportFile(ctx, from) {
410
413
  throw importFileError(from, "its top level is not a mapping of sections");
411
414
  return value;
412
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
+ }
413
421
  function onlyHarnessSlug(pkg) {
414
422
  const harnesses = Array.isArray(pkg.harnesses) ? pkg.harnesses : [];
415
423
  if (harnesses.length !== 1)
@@ -511,11 +519,15 @@ async function runInit(ctx, input) {
511
519
  await contracts.errorCatalog().catch(() => null);
512
520
  if (!schema)
513
521
  ctx.warn("The instance does not publish its package schema; `validate` will have nothing to check against.");
514
- 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);
515
527
  chosenHarness = decided;
516
528
  const harness = decided.slug;
517
529
  if (decided.missing)
518
- 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.`);
519
531
  const values = { instance: url };
520
532
  if (tenant)
521
533
  values.tenant = tenant.ref;
@@ -534,7 +546,7 @@ async function runInit(ctx, input) {
534
546
  actions.push(...(await folder(root, dir)));
535
547
  }
536
548
  actions.push(...(await folder(root, "seeds")));
537
- const harness = stringOption(input, "harness") ?? project.harness ?? packageHarness;
549
+ const harness = chosenHarness?.slug ?? project.harness ?? stringOption(input, "harness") ?? packageHarness;
538
550
  actions.push(await ownFile(root, `${ENV_DIR}/test.yaml`, envYaml("test", harness)));
539
551
  actions.push(await ownFile(root, `${ENV_DIR}/prod.yaml`, envYaml("prod", undefined)));
540
552
  if (await ensureStateDir(root))
@@ -589,7 +601,7 @@ export const init = {
589
601
  "file that holds something else unless --force, and names the sections the instance's schema does not know.",
590
602
  readOnly: false,
591
603
  destructive: true,
592
- mcpEffect: "Changes nothing on the instance (as a tool it never creates a solution). Writes files in the solution folder; never overwrites a " +
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 " +
593
605
  "file it did not create, and changes only the blocks between its markers in AGENTS.md, CLAUDE.md and .gitignore.",
594
606
  idempotent: true,
595
607
  mcpTool: "init",
@@ -597,7 +609,7 @@ export const init = {
597
609
  harness: {
598
610
  type: "string",
599
611
  value: "<harness>",
600
- 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.",
601
613
  },
602
614
  agents: {
603
615
  type: "string",
@@ -24,6 +24,27 @@ export async function refreshInventory(root, kind, names, now) {
24
24
  inventory.refreshed_at = { ...inventory.refreshed_at, [kind]: now.toISOString() };
25
25
  await writeState(root, INVENTORY_JSON, `${JSON.stringify(inventory, null, 2)}\n`);
26
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
+ }
27
48
  const MAX_ROWS = 100;
28
49
  const COLUMNS = ["slug", "name", "status", "id"];
29
50
  function itemsOf(data) {
@@ -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,6 +1,7 @@
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";
@@ -151,7 +152,7 @@ export const modelsSetLimit = {
151
152
  { name: "limit", description: "Requests the endpoint serves at once (a whole number), or none to clear the limit.", required: true },
152
153
  ],
153
154
  options: {
154
- 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." },
155
156
  env: ENV_OPTION,
156
157
  },
157
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"],
@@ -183,11 +184,13 @@ export const modelsSetLimit = {
183
184
  return { data: { ...base, changed: false, sent: false }, text: `${label} already has max_concurrent_requests ${limitText(limit)}; nothing to change.` };
184
185
  }
185
186
  const sharing = model.shares_endpoint_with?.length ? ` It shares the count with ${model.shares_endpoint_with.join(", ")} (same endpoint).` : "";
186
- if (!boolOption(input, "confirm")) {
187
- 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`);
188
190
  return {
189
- data: { ...base, changed: false, sent: false, confirm },
190
- 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 } : {}),
191
194
  };
192
195
  }
193
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}`);