@cavelon/cli 0.1.10 → 0.1.12

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 (45) hide show
  1. package/README.md +34 -15
  2. package/dist/access.js +194 -0
  3. package/dist/acting.js +123 -0
  4. package/dist/agent-env.js +20 -2
  5. package/dist/change-confirmation.js +93 -0
  6. package/dist/commands/api.js +77 -30
  7. package/dist/commands/chat.js +16 -8
  8. package/dist/commands/db.js +474 -0
  9. package/dist/commands/docs.js +83 -7
  10. package/dist/commands/index.js +7 -0
  11. package/dist/commands/limits-set.js +11 -5
  12. package/dist/commands/loops.js +72 -9
  13. package/dist/commands/models.js +12 -6
  14. package/dist/commands/sandboxes.js +7 -2
  15. package/dist/commands/session.js +111 -24
  16. package/dist/commands/setup.js +1 -1
  17. package/dist/commands/solution.js +211 -54
  18. package/dist/commands/tenants.js +55 -12
  19. package/dist/commands/values.js +104 -23
  20. package/dist/commands/work.js +13 -5
  21. package/dist/confirm-token.js +90 -7
  22. package/dist/context.js +5 -1
  23. package/dist/contracts.js +37 -12
  24. package/dist/database-queries.js +301 -0
  25. package/dist/fsutil.js +14 -0
  26. package/dist/http.js +69 -3
  27. package/dist/install.js +30 -0
  28. package/dist/invoke.js +12 -2
  29. package/dist/kit-codes.js +9 -2
  30. package/dist/mcp.js +106 -19
  31. package/dist/openapi.js +7 -0
  32. package/dist/package-check.js +19 -0
  33. package/dist/preview-report.js +2 -2
  34. package/dist/principal.js +24 -2
  35. package/dist/printed.js +5 -0
  36. package/dist/secret-access.js +30 -9
  37. package/dist/session.js +36 -8
  38. package/dist/skills/cavelon-authoring/SKILL.md +93 -10
  39. package/dist/skills/cavelon-long-running/SKILL.md +18 -8
  40. package/dist/skills/cavelon-loop/SKILL.md +126 -41
  41. package/dist/skills/cavelon-testing/SKILL.md +32 -3
  42. package/dist/trace-view.js +10 -0
  43. package/dist/update-check.js +2 -2
  44. package/dist/user-config.js +24 -0
  45. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { originText } from "../capacity.js";
2
2
  import { positional } from "../command.js";
3
3
  import { CavelonError, ExitCode, usageError } from "../errors.js";
4
- import { confirmation } from "../confirm-token.js";
4
+ import { confirmation, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
5
5
  import { callOperation, openapiOrWarn, workflowOperation } from "../invoke.js";
6
6
  import { changedBy, docsPage, formatValue, isOperatorChange, LIMIT_ABOVE_CEILING, limitRef, quotaSetting, readLimits, } from "../limits.js";
7
7
  import { deref, jsonBodySchema, operationForPath, validateBody } from "../openapi.js";
@@ -471,7 +471,8 @@ export const limitsSet = {
471
471
  "An operator's change (a run cap) is sent only with a personal access token in Platform mode of a role it names, without\n" +
472
472
  "X-Tenant-Id; --tenant <id|slug> then sets one tenant's own run cap. An environment or licence limit, a value out of bounds,\n" +
473
473
  "an instance that does not publish how to change the limit, and a credential without the permission or the role are refused\n" +
474
- "before anything is sent. Propose the change to the person; never raise a limit on your own.",
474
+ "before anything is sent. Propose the change to the person; never raise a limit on your own.\n" +
475
+ PERSON_CONFIRMS_HELP,
475
476
  readOnly: false,
476
477
  destructive: true,
477
478
  idempotent: true,
@@ -491,7 +492,6 @@ export const limitsSet = {
491
492
  examples: [
492
493
  "cavelon limits set kb_upload_max_file_size_mb 50",
493
494
  "cavelon limits set kb_upload_max_file_size_mb 50 --confirm",
494
- "cavelon limits set kb_upload_max_file_size_mb 50 --confirm <token>",
495
495
  "cavelon limits set rate_limit_chat_rpm none --confirm",
496
496
  "cavelon limits set monthly_inference_token_budget 2000000",
497
497
  "cavelon limits set monthly_processing_step_cap none --confirm",
@@ -574,7 +574,13 @@ export const limitsSet = {
574
574
  const allowed = operator
575
575
  ? `a personal access token in Platform mode of a ${anyOf(change.requires_role ?? [], "platform role")}`
576
576
  : `a credential with ${anyOf(change.permissions)} (a session, a personal access token, or an admin API key of the tenant)`;
577
- const gate = await confirmation(ctx, input, "limits_set", { key, value, previous: previous ?? null, operation });
577
+ const gate = await confirmation(ctx, input, "limits_set", { key, value, previous: previous ?? null, operation }, {
578
+ platform: operator ? (target.scope === "one_tenant" ? "tenant" : "outside") : undefined,
579
+ person: {
580
+ what: `${key}: ${from} → ${to}${target.scope === "platform" ? ", the platform's cap for every tenant without its own" : ""}.`,
581
+ words: ["limits", "set", key, argText(value), "--confirm"],
582
+ },
583
+ });
578
584
  if (!gate.confirmed) {
579
585
  const confirm = gate.confirm(cavelonCommand("limits", "set", key, argText(value), "--confirm"));
580
586
  const source = target.limit && target.kind === "limit" ? ` (source now: ${target.limit.source}${target.limit.origin ? `, origin: ${target.limit.origin}` : ""})` : "";
@@ -585,7 +591,7 @@ export const limitsSet = {
585
591
  : [];
586
592
  return {
587
593
  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"),
594
+ text: [`${key}: ${from} → ${to}${source}.`, ...what, `Sends: ${sends}`, `Allowed: ${allowed}.`, gate.where, ...(gate.mismatch ? [gate.mismatch] : []), `Nothing was changed. Change it with: ${confirm}`].join("\n"),
589
595
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
590
596
  };
591
597
  }
@@ -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 { confirmation } from "../confirm-token.js";
4
+ import { confirmation, confirmTokenRequired, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
5
5
  import { idempotencyKey, requireFeature, UUID_KEY_OPTION, withRetryKey } from "../features.js";
6
6
  import { clip, keyValues, moreHint, table } from "../format.js";
7
7
  import { callStable } from "../invoke.js";
@@ -18,6 +18,14 @@ const MAX_ITERATION_CURSOR = 100;
18
18
  const LOOP_TERMINAL = new Set(["completed", "failed", "cancelled", "stopped"]);
19
19
  const LOOP_SETTLED = new Set([...LOOP_TERMINAL, "paused"]);
20
20
  const RUN_TERMINAL = new Set(["completed", "failed", "blocked", "rejected", "skipped_budget", "expired", "cancelled", "debug_stopped"]);
21
+ async function triggerSolution(ctx, trigger) {
22
+ if (!trigger.harness_id)
23
+ return null;
24
+ const harness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}", "reading solutions", {
25
+ params: { harness_id: [trigger.harness_id] },
26
+ }).catch(() => undefined);
27
+ return { id: trigger.harness_id, slug: harness?.slug ?? null, name: harness?.name ?? null, status: harness?.status ?? null };
28
+ }
21
29
  export async function resolveTrigger(ctx, ref) {
22
30
  if (isUuid(ref)) {
23
31
  return callStable(ctx, "GET", "/api/v1/triggers/{trigger_id}", "triggers", { params: { trigger_id: [ref] } });
@@ -170,26 +178,74 @@ function loopExitCode(state) {
170
178
  }
171
179
  export const loopStart = {
172
180
  name: "loop start",
173
- summary: "Start a loop through its trigger, as you; returns the run and operation ids.",
181
+ summary: "Start a loop through its trigger, as you; previews first, --confirm starts it and returns the run and operation ids.",
174
182
  description: "Calls the trigger's run-now route. The run (and its loop) acts as the caller: with a personal access token, the person.\n" +
175
- "Follow it with `loop watch <run>`, or `wait <operation>`; `loop cancel <run>` stops it.",
183
+ "It runs on its own and spends the tenant's model budget, so without --confirm nothing starts: the preview names the\n" +
184
+ "trigger, its solution and the payload. Show it to a person and confirm only with their yes. For a trigger of a draft\n" +
185
+ "solution an agent confirms with the preview's token (--confirm <token>, or confirm over MCP); for any other,\n" +
186
+ "a coding agent cannot confirm it: over MCP the client asks the person, and from an agent's shell the person runs the\n" +
187
+ "confirm in their own terminal. Follow the run with `loop watch <run>`, or `wait <operation>`; `loop cancel <run>` stops it.",
176
188
  readOnly: false,
177
189
  mcpTool: "loop_start",
190
+ operations: ["POST /api/v1/triggers/{trigger_id}/run"],
178
191
  positionals: [{ name: "trigger", description: "Trigger slug, name or id.", required: true }],
179
192
  options: {
180
193
  input: { type: "string", value: "<json|@file|->", description: "The run's payload: JSON, @file.json or - for stdin." },
181
194
  wait: WAIT_OPTION,
182
195
  timeout: TIMEOUT_OPTION,
183
196
  "idempotency-key": UUID_KEY_OPTION,
197
+ confirm: { type: "boolean", mcpToken: true, description: "Start the run (after a person saw the preview)." },
184
198
  },
185
- examples: ["cavelon loop start counter", "cavelon loop start orders --input @orders-request.json --json"],
199
+ examples: [
200
+ "cavelon loop start counter",
201
+ "cavelon loop start counter --confirm",
202
+ "cavelon loop start counter --confirm <token>",
203
+ "cavelon loop start orders --input @orders-request.json --confirm --json",
204
+ ],
186
205
  async run(ctx, input) {
206
+ if (ctx.mode === "mcp" && input.options.confirm === true)
207
+ throw confirmTokenRequired("loop_start");
187
208
  await requireFeature(ctx, "masterloop_enabled", "masterloop_feature_disabled", "Masterloop");
188
209
  const trigger = await resolveTrigger(ctx, positional(input, "trigger"));
189
210
  const raw = stringOption(input, "input");
190
211
  const payload = raw === undefined ? {} : await readBody(ctx, raw);
191
212
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
192
213
  throw usageError("--input must be a JSON object.");
214
+ const solution = await triggerSolution(ctx, trigger);
215
+ const given = stringOption(input, "idempotency-key");
216
+ const words = ["loop", "start", trigger.slug, ...(raw !== undefined ? ["--input", raw] : []), ...(given ? ["--idempotency-key", given] : [])];
217
+ const gate = await confirmation(ctx, input, "loop_start", { trigger: trigger.id, payload }, {
218
+ ...(solution?.status === "draft"
219
+ ? {}
220
+ : { person: { what: `Start a run of the trigger ${trigger.slug}, which acts as the person and spends the tenant's model budget.`, words: [...words, "--confirm"] } }),
221
+ });
222
+ if (!gate.confirmed) {
223
+ const confirm = gate.confirm(cavelonCommand(...words, "--confirm"));
224
+ const payloadText = clip(JSON.stringify(payload), 500);
225
+ return {
226
+ data: {
227
+ started: false,
228
+ would: "start_run",
229
+ trigger: { id: trigger.id, slug: trigger.slug, name: trigger.name, type: trigger.trigger_type, is_active: trigger.is_active },
230
+ solution,
231
+ payload,
232
+ confirm,
233
+ ...gate.fields,
234
+ },
235
+ text: [
236
+ `Starting ${trigger.slug} (${trigger.trigger_type}) starts a run that acts as you, runs on its own and spends the tenant's model budget until it ends or is cancelled.`,
237
+ !solution
238
+ ? "Solution: none named by the trigger."
239
+ : solution.status
240
+ ? `Solution: ${solution.name ?? solution.id}${solution.slug ? ` (${solution.slug})` : ""}, ${solution.status}.`
241
+ : `Solution: ${solution.id} (not readable).`,
242
+ `Payload: ${payloadText}`,
243
+ gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
244
+ `Nothing was started. Show this to a person; with their yes: ${confirm}`,
245
+ ].join("\n"),
246
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
247
+ };
248
+ }
193
249
  const key = idempotencyKey(input);
194
250
  const run = await callStable(ctx, "POST", "/api/v1/triggers/{trigger_id}/run", "starting triggers", {
195
251
  params: { trigger_id: [trigger.id] },
@@ -231,6 +287,7 @@ export const loopCancel = {
231
287
  destructive: true,
232
288
  idempotent: true,
233
289
  mcpTool: "loop_cancel",
290
+ operations: ["POST /api/v1/triggers/runs/{run_id}/cancel"],
234
291
  positionals: [{ name: "run", description: "The trigger run id (from `loop start`).", required: true }],
235
292
  options: {
236
293
  confirm: { type: "boolean", mcpToken: true, description: "Stop the run; without it nothing is stopped." },
@@ -252,6 +309,7 @@ export const loopCancel = {
252
309
  text: `Run ${run.id} (${run.workflow_name}) is ${run.status}` +
253
310
  (loops.length ? `, with loops:\n${table(loops, ["loop_id", "node", "state", "iteration"])}\n` : ".\n") +
254
311
  (note ? `${noteLines(note).slice(1)}\n` : "") +
312
+ `${gate.where}\n` +
255
313
  (gate.mismatch ? `${gate.mismatch}\n` : "") +
256
314
  `Nothing was stopped. Stop it with: ${confirm}`,
257
315
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
@@ -590,6 +648,7 @@ function controlCommand(action) {
590
648
  "the command); any other pause resumes without it. A pause that cannot be resumed is refused with what to do instead.",
591
649
  readOnly: false,
592
650
  mcpTool: `loop_${action}`,
651
+ operations: [`POST /api/v1/triggers/runs/{run_id}/loops/{loop_id}/${action}`],
593
652
  positionals: [{ name: "run", description: "The trigger run id.", required: true }],
594
653
  options: {
595
654
  loop: LOOP_OPTION,
@@ -750,11 +809,13 @@ export const triggerIdentity = {
750
809
  summary: "Show, bind or clear the API key a trigger's unattended runs act as (binding needs --confirm).",
751
810
  description: "Without <key> or --clear, shows the binding. Binding gives the trigger standing authority, so it is never part of\n" +
752
811
  "`apply`: show the person, then run it with --confirm. It needs settings.manage and triggers.manage. Creating keys\n" +
753
- "and Sandbox Access stay in the Admin. A personal access token is never an execution identity.",
812
+ "and Sandbox Access stay in the Admin. A personal access token is never an execution identity.\n" +
813
+ PERSON_CONFIRMS_HELP,
754
814
  readOnly: false,
755
815
  destructive: true,
756
816
  idempotent: true,
757
817
  mcpTool: "trigger_identity",
818
+ operations: ["PUT /api/v1/triggers/{trigger_id}/execution-identity"],
758
819
  positionals: [
759
820
  { name: "trigger", description: "Trigger slug, name or id.", required: true },
760
821
  { name: "key", description: "The API key's name or id (never its value)." },
@@ -766,7 +827,6 @@ export const triggerIdentity = {
766
827
  examples: [
767
828
  "cavelon trigger identity orders",
768
829
  "cavelon trigger identity orders loop-runner --confirm",
769
- "cavelon trigger identity orders loop-runner --confirm <token>",
770
830
  "cavelon trigger identity orders --clear --confirm",
771
831
  ],
772
832
  async run(ctx, input) {
@@ -787,12 +847,15 @@ export const triggerIdentity = {
787
847
  }
788
848
  const keyName = key && "name" in key ? key.name : wanted;
789
849
  const change = wanted ? `bind API key "${keyName}"` : "clear the binding";
790
- const gate = await confirmation(ctx, input, "trigger_identity", { trigger: trigger.id, from: current.api_key_id ?? null, to: wanted });
850
+ const words = ["trigger", "identity", trigger.slug, keyRef ?? "--clear", "--confirm"];
851
+ const gate = await confirmation(ctx, input, "trigger_identity", { trigger: trigger.id, from: current.api_key_id ?? null, to: wanted }, {
852
+ person: { what: `Trigger ${trigger.slug}: ${change}, which its runs act as.`, words },
853
+ });
791
854
  if (!gate.confirmed) {
792
- const confirm = gate.confirm(cavelonCommand("trigger", "identity", trigger.slug, keyRef ?? "--clear", "--confirm"));
855
+ const confirm = gate.confirm(cavelonCommand(...words));
793
856
  return {
794
857
  data: { trigger: trigger.slug, changed: false, would: change, current: view, confirm, ...gate.fields },
795
- text: `${identityText(trigger, view)}\n\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing changed. To ${change}: ${confirm}`,
858
+ text: `${identityText(trigger, view)}\n\n${gate.where}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing changed. To ${change}: ${confirm}`,
796
859
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
797
860
  };
798
861
  }
@@ -1,7 +1,7 @@
1
1
  import { CAPACITY_TUTORIAL_PAGE } from "../capacity.js";
2
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
+ import { confirmation, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
5
5
  import { moreHint, table } from "../format.js";
6
6
  import { callStable, workflowOperation } from "../invoke.js";
7
7
  import { deref, jsonBodySchema, validateBody } from "../openapi.js";
@@ -141,11 +141,13 @@ export const modelsSetLimit = {
141
141
  description: "Sets the row's max_concurrent_requests to <n>, or clears it with none. Without --confirm, shows the old and new value\n" +
142
142
  "and changes nothing. A row without a base_url is refused before anything is sent: it reaches its provider through the\n" +
143
143
  "platform's routes, which have their own limits. Every row with the same base_url shares the count. Propose a value to\n" +
144
- "the person and let them decide; the instance's capacity tutorial says how to find it.",
144
+ "the person and let them decide; the instance's capacity tutorial says how to find it.\n" +
145
+ PERSON_CONFIRMS_HELP,
145
146
  readOnly: false,
146
147
  destructive: true,
147
148
  idempotent: true,
148
149
  mcpTool: "models_set_limit",
150
+ operations: ["PATCH /api/v1/model-registry/{model_registry_id}"],
149
151
  positionals: [
150
152
  { name: "model", description: "The row's model_id, id or display name (`cavelon models list`).", required: true },
151
153
  { name: "limit", description: "Requests the endpoint serves at once (a whole number), or none to clear the limit.", required: true },
@@ -154,8 +156,7 @@ export const modelsSetLimit = {
154
156
  confirm: { type: "boolean", mcpToken: true, description: "Change it; without this nothing is changed." },
155
157
  env: ENV_OPTION,
156
158
  },
157
- examples: ["cavelon models set-limit llama-70b 8", "cavelon models set-limit llama-70b 8 --confirm",
158
- "cavelon models set-limit llama-70b 8 --confirm <token>", "cavelon models set-limit llama-70b none --confirm"],
159
+ examples: ["cavelon models set-limit llama-70b 8", "cavelon models set-limit llama-70b 8 --confirm", "cavelon models set-limit llama-70b none --confirm"],
159
160
  async run(ctx, input) {
160
161
  const ref = positional(input, "model");
161
162
  const limit = parseLimit(positional(input, "limit"));
@@ -183,12 +184,17 @@ 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
- const gate = await confirmation(ctx, input, "models_set_limit", { row: row.id, previous, limit });
187
+ const gate = await confirmation(ctx, input, "models_set_limit", { row: row.id, previous, limit }, {
188
+ person: {
189
+ what: `${label}: max_concurrent_requests ${limitText(previous)} → ${limitText(limit)}.${sharing}`,
190
+ words: ["models", "set-limit", row.model_id, limitText(limit), "--confirm"],
191
+ },
192
+ });
187
193
  if (!gate.confirmed) {
188
194
  const confirm = gate.confirm(cavelonCommand("models", "set-limit", row.model_id, limitText(limit), "--confirm"));
189
195
  return {
190
196
  data: { ...base, changed: false, sent: false, confirm, ...gate.fields },
191
- text: `${label}: max_concurrent_requests ${limitText(previous)} → ${limitText(limit)}.${sharing}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was changed. Change it with: ${confirm}`,
197
+ text: `${label}: max_concurrent_requests ${limitText(previous)} → ${limitText(limit)}.${sharing}\n${gate.where}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was changed. Change it with: ${confirm}`,
192
198
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
193
199
  };
194
200
  }
@@ -168,6 +168,7 @@ export const sandboxValidate = {
168
168
  readOnly: false,
169
169
  idempotent: true,
170
170
  mcpTool: "sandbox_validate",
171
+ operations: ["POST /api/v1/sandboxes/{sandbox_id}/validate"],
171
172
  positionals: [{ name: "sandbox", description: "Sandbox name or id.", required: true }],
172
173
  examples: ["cavelon sandbox validate orders-test"],
173
174
  async run(ctx, input) {
@@ -384,6 +385,7 @@ export const sandboxRefresh = {
384
385
  readOnly: false,
385
386
  idempotent: true,
386
387
  mcpTool: "sandbox_refresh",
388
+ operations: ["POST /api/v1/sandboxes/{sandbox_id}/refresh-workspace"],
387
389
  positionals: [{ name: "sandbox", description: "Sandbox name or id.", required: true }],
388
390
  options: { "idempotency-key": UUID_KEY_OPTION },
389
391
  examples: ["cavelon sandbox refresh spec-vm"],
@@ -464,6 +466,7 @@ export const sandboxSeed = {
464
466
  destructive: true,
465
467
  idempotent: true,
466
468
  mcpTool: "sandbox_seed",
469
+ operations: ["POST /api/v1/sandboxes/{sandbox_id}/artifact-jobs"],
467
470
  positionals: [
468
471
  { name: "sandbox", description: "Sandbox name or id.", required: true },
469
472
  { name: "source", description: "A folder, an uncompressed .tar, or one file.", required: true },
@@ -505,6 +508,7 @@ export const sandboxSeed = {
505
508
  return {
506
509
  data: { ...summary, seeded: false, confirm, ...gate.fields },
507
510
  text: `Would replace the workspace of "${sandbox.name}" (${revision}) with ${what}, ${archive.bytes.length} bytes, sha256 ${archive.sha256}.\n` +
511
+ `${gate.where}\n` +
508
512
  (gate.mismatch ? `${gate.mismatch}\n` : "") +
509
513
  `Nothing was sent. Seed it with: ${confirm}`,
510
514
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
@@ -560,7 +564,7 @@ async function upload(ctx, sandboxId, jobId, bytes) {
560
564
  catch {
561
565
  }
562
566
  if (!response.ok)
563
- throw await client.refusal(response.status, data, `PUT ${target}`, response.headers);
567
+ throw await client.refusal(response.status, data, `PUT ${target}`, response.headers, { method: "PUT", path: new URL(client.resolve(target)).pathname });
564
568
  return data;
565
569
  }
566
570
  async function download(ctx, sandbox, job, out) {
@@ -581,7 +585,7 @@ async function download(ctx, sandbox, job, out) {
581
585
  }
582
586
  catch {
583
587
  }
584
- throw await client.refusal(response.status, data, `GET ${target}`, response.headers);
588
+ throw await client.refusal(response.status, data, `GET ${target}`, response.headers, { method: "GET", path: new URL(client.resolve(target)).pathname });
585
589
  }
586
590
  const sha256 = createHash("sha256").update(bytes).digest("hex");
587
591
  const declared = response.headers.get("x-content-sha256");
@@ -614,6 +618,7 @@ export const artifactsExport = {
614
618
  "(default sandbox-<job>.tar), never over an existing file. On a customer VM, read results with `sandbox cat`.",
615
619
  readOnly: false,
616
620
  mcpTool: "artifacts_export",
621
+ operations: ["POST /api/v1/sandboxes/{sandbox_id}/artifact-jobs"],
617
622
  positionals: [{ name: "sandbox", description: "Sandbox name or id.", required: true }],
618
623
  options: {
619
624
  path: { type: "string", multiple: true, value: "<path>", description: "Export only these workspace paths (repeatable; default: all)." },
@@ -3,7 +3,7 @@ import { boolOption, positional } from "../command.js";
3
3
  import { compareContracts, Contracts } from "../contracts.js";
4
4
  import { deleteToken, saveToken } from "../credentials.js";
5
5
  import { CavelonError, ExitCode, usageError } from "../errors.js";
6
- import { keyValues } from "../format.js";
6
+ import { clip, keyValues } from "../format.js";
7
7
  import { callStable } from "../invoke.js";
8
8
  import { formatQuota, formatValue, limitRef, readLimits, readQuotas } from "../limits.js";
9
9
  import { ApiClient, tokensDisabledError } from "../http.js";
@@ -13,10 +13,12 @@ import { solutionState, solutionStateLines } from "./solution.js";
13
13
  import { expiryOf, readPrincipal, readTenantless } from "../principal.js";
14
14
  import { maySetSecrets } from "../secret-access.js";
15
15
  import { readHidden } from "../prompt.js";
16
- import { isUuid, lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
16
+ import { isUuid, knownTenantId, lookupTenantId, requireInstance, requireToken, tenantRequiredError } from "../session.js";
17
17
  import { cavelonCommand, fill } from "../printed.js";
18
18
  import { choicesOf, chooseTenant, commandLines, describeTenant, listsTenants, noTenantError, tenantOpenError, tenantRef, tenantTitle } from "../tenant-choice.js";
19
- import { loadUserConfig, saveUserConfig, tokenKind, updateInstance } from "../user-config.js";
19
+ import { loadUserConfig, saveUserConfig, tokenKind, updateInstance, withTenantRefs } from "../user-config.js";
20
+ import { checkKeyTenant } from "../acting.js";
21
+ import { accessFor, accessOf, mayActivate, operationAccess } from "../access.js";
20
22
  async function readCapabilities(contracts, refresh) {
21
23
  const caps = await contracts.capabilities({ refresh });
22
24
  return { caps, needsTenant: contracts.needsTenant };
@@ -101,6 +103,8 @@ export const login = {
101
103
  ctx.warn("The token starts with neither cvpat_ nor cbp_; the instance may refuse it.");
102
104
  const client = new ApiClient({ url, token }, ctx.io.env);
103
105
  const contracts = new Contracts(client, ctx.io.env, ctx.io.now);
106
+ if (kind === "api_key")
107
+ await checkKeyTenant(client, { ...session, token, tokenKind: kind }, (m) => ctx.warn(m));
104
108
  let tenant;
105
109
  let chosen;
106
110
  if (session.tenant && kind !== "api_key") {
@@ -153,7 +157,7 @@ export const login = {
153
157
  const store = await saveToken(ctx.io.env, url, token);
154
158
  const remember = tenant && chosen;
155
159
  await updateInstance(ctx.io.env, url, (current) => ({
156
- ...current,
160
+ ...withTenantRefs(current, remember ? [tenant.ref, tenant.slug] : [], tenant?.id ?? "", token, ctx.io.now()),
157
161
  credential_store: store.kind,
158
162
  token_kind: kind,
159
163
  logged_in_at: ctx.io.now().toISOString(),
@@ -163,7 +167,6 @@ export const login = {
163
167
  tenant_id: tenant.id,
164
168
  tenant_name: tenant.name,
165
169
  tenant_slug: tenant.slug,
166
- tenant_ids: { ...current.tenant_ids, [tenant.ref]: tenant.id, ...(tenant.slug ? { [tenant.slug]: tenant.id } : {}) },
167
170
  }
168
171
  : {}),
169
172
  }), { makeCurrent: true });
@@ -286,6 +289,8 @@ function tenantSourceText(session) {
286
289
  return session.project
287
290
  ? "`cavelon use` (this folder's cavelon.yaml names no tenant for this instance)"
288
291
  : "`cavelon use`, for every folder without a cavelon.yaml (--tenant chooses another for one command)";
292
+ case "session":
293
+ return "use_tenant, for this MCP session only (the tenant stored for your user is unchanged)";
289
294
  default:
290
295
  return session.tenantSource;
291
296
  }
@@ -348,8 +353,9 @@ export const whoami = {
348
353
  }
349
354
  const listed = reach?.tenants.find((t) => t.id === contextTenant);
350
355
  const stored = session.settings.tenant_id === contextTenant ? session.settings : undefined;
351
- let tenantName = listed?.name ?? membership?.tenant_name ?? stored?.tenant_name ?? null;
352
- let tenantSlug = listed?.slug ?? membership?.tenant_slug ?? stored?.tenant_slug ?? null;
356
+ const acting = principal?.tenant?.id === contextTenant ? principal.tenant : undefined;
357
+ let tenantName = acting?.name ?? listed?.name ?? membership?.tenant_name ?? stored?.tenant_name ?? null;
358
+ let tenantSlug = acting?.slug ?? listed?.slug ?? membership?.tenant_slug ?? stored?.tenant_slug ?? null;
353
359
  if (contextTenant && (!tenantName || !tenantSlug)) {
354
360
  const described = await describeTenant(client, contextTenant);
355
361
  tenantName ??= described.name ?? null;
@@ -363,6 +369,7 @@ export const whoami = {
363
369
  const expiry = expiryOf(principal, ctx.io.now());
364
370
  if (expiry.warning)
365
371
  ctx.warn(expiry.warning);
372
+ const access = accessOf(principal);
366
373
  const data = {
367
374
  instance: {
368
375
  url: session.url,
@@ -378,11 +385,14 @@ export const whoami = {
378
385
  prefix: principal?.token?.prefix ?? principal?.api_key?.prefix ?? null,
379
386
  expires_at: expiry.expires_at,
380
387
  expires_in_days: expiry.days_left,
381
- may_activate: principal?.token ? principal.token.may_activate : null,
388
+ may_activate: mayActivate(access),
382
389
  may_set_secrets: maySetSecrets(principal),
390
+ may_set_variables: maySetVariables(access),
383
391
  ceiling_role: principal?.token?.ceiling_role ?? null,
384
392
  platform_mode_allowed: principal?.token?.platform_mode_allowed ?? null,
385
393
  scopes: principal?.api_key?.scopes ?? null,
394
+ permissions: access?.permissions ?? null,
395
+ needs_a_person: access?.complete ? access.needsAPerson : null,
386
396
  published: Boolean(principal),
387
397
  },
388
398
  owner: me
@@ -426,8 +436,12 @@ export const whoami = {
426
436
  ["role", data.role ?? undefined],
427
437
  ["credential", `${session.tokenKind === "api_key" ? "tenant API key" : session.tokenKind === "personal_access_token" ? "personal access token" : "token"}${tokenName} from ${credentialSource(session)}`],
428
438
  ["expires", expires],
429
- ["may activate", principal?.token ? (principal.token.may_activate ? "yes" : "no (a person activates in the Admin)") : undefined],
430
- ["may set secrets", secretsText(data.credential.may_set_secrets)],
439
+ ["may activate", activateText(data.credential.may_activate, access)],
440
+ ["may set secrets", secretsText(data.credential.may_set_secrets, access?.complete === true)],
441
+ ["may set variables", variablesText(data.credential.may_set_variables)],
442
+ ["scopes", data.credential.scopes ? data.credential.scopes.join(", ") || "none" : undefined],
443
+ ["permissions", permissionsText(access)],
444
+ ["needs a person", needsAPersonText(access)],
431
445
  ["platform mode", typeof principal?.token?.platform_mode_allowed === "boolean" ? platformModeText(principal.token) : undefined],
432
446
  ["reaches", reach ? reachText(reach) : undefined],
433
447
  ["version", data.instance.version ? `${data.instance.version}${versionCachedAt ? ` (cached at ${versionCachedAt})` : ""}` : undefined],
@@ -435,17 +449,54 @@ export const whoami = {
435
449
  };
436
450
  },
437
451
  };
438
- function secretsText(may) {
452
+ const LISTED = 12;
453
+ function activateText(may, access) {
454
+ if (may === null)
455
+ return undefined;
456
+ if (may)
457
+ return "yes";
458
+ return access?.principal.token && !access.principal.token.may_activate
459
+ ? "no (the token was created without \"may activate\"; a person activates in the Admin)"
460
+ : "no (a person whose role may activate does it, in the Admin)";
461
+ }
462
+ export function maySetVariables(access) {
463
+ return operationAccess(access, "PUT /api/v1/variables/{name}").allowed;
464
+ }
465
+ function variablesText(may) {
439
466
  if (may === null)
440
467
  return undefined;
441
468
  return may ? "yes" : "no (a tenant Owner sets them, in the Admin or with their own token)";
442
469
  }
470
+ function permissionsText(access) {
471
+ if (!access?.permissions)
472
+ return access ? "not published for this credential by this instance" : undefined;
473
+ const all = access.permissions;
474
+ if (!all.length)
475
+ return "none";
476
+ return `${all.slice(0, LISTED).join(", ")}${all.length > LISTED ? `, … ${all.length - LISTED} more (--json)` : ""}`;
477
+ }
478
+ function needsAPersonText(access) {
479
+ if (!access?.complete || !access.needsAPerson.length)
480
+ return undefined;
481
+ const all = access.needsAPerson;
482
+ const shown = all.slice(0, LISTED).map((o) => `\n ${o.method} ${o.path}${o.reason ? ` (${clip(o.reason, 80)})` : ""}`);
483
+ return `${all.length} operation${all.length === 1 ? "" : "s"} a person runs, not this credential:${shown.join("")}${all.length > LISTED ? `\n … ${all.length - LISTED} more (--json)` : ""}`;
484
+ }
485
+ function secretsText(may, inAdmin) {
486
+ if (may === null)
487
+ return undefined;
488
+ if (may)
489
+ return "yes";
490
+ return inAdmin ? "no (a tenant Owner sets them, signed in to the Admin under Settings › Secrets)" : "no (a tenant Owner sets them, in the Admin or with their own token)";
491
+ }
443
492
  export const use = {
444
493
  name: "use",
445
494
  summary: "Choose the tenant this instance's commands act in.",
446
495
  description: "Stored per instance for your user. CAVELON_TENANT, --tenant and a cavelon.yaml tenant take precedence over it.\n" +
447
496
  "Without a tenant, it lists the tenants the token reaches: a person chooses one on a terminal by number or part of its name; " +
448
- "without a terminal it prints one `cavelon use` line per tenant, and as an MCP tool it returns them as choices and changes nothing.",
497
+ "without a terminal it prints one `cavelon use` line per tenant, and as an MCP tool it returns them as choices and changes nothing.\n" +
498
+ "As an MCP tool it never changes the tenant stored for your user: it chooses the tenant for that MCP session only, " +
499
+ "until the session ends or it is cleared, so an agent's choice never moves where your own commands go.",
449
500
  readOnly: false,
450
501
  idempotent: true,
451
502
  mcpTool: "use_tenant",
@@ -456,7 +507,17 @@ export const use = {
456
507
  const session = await ctx.session();
457
508
  const url = requireInstance(session);
458
509
  requireToken(session);
510
+ const inSession = ctx.mode === "mcp";
511
+ if (inSession && !ctx.globals.sessionTenants)
512
+ throw usageError("This MCP server keeps no session, so use_tenant cannot choose a tenant; pass tenant to each tool instead.");
459
513
  if (boolOption(input, "clear")) {
514
+ if (inSession) {
515
+ ctx.globals.sessionTenants.delete(url);
516
+ return {
517
+ data: { instance: url, tenant: null, scope: "session" },
518
+ text: `No tenant chosen for ${url} in this MCP session; tools act in the tenant chosen for this folder or with \`cavelon use\` again.`,
519
+ };
520
+ }
460
521
  await updateInstance(ctx.io.env, url, (c) => ({ ...c, tenant: undefined, tenant_id: undefined, tenant_name: undefined, tenant_slug: undefined }));
461
522
  return { data: { instance: url, tenant: null }, text: `No tenant chosen for ${url}.` };
462
523
  }
@@ -496,21 +557,27 @@ export const use = {
496
557
  const probe = new ApiClient({ ...client.target, tenantId: found.id }, ctx.io.env);
497
558
  await probe.get("/api/v1/meta/capabilities", { allow: [404] });
498
559
  const stored = found.slug ?? ref;
560
+ const title = tenantTitle({ id: found.id, name: found.name, slug: found.slug ?? (isUuid(ref) ? undefined : ref) });
561
+ if (session.tenantSource && session.tenantSource !== "use" && session.tenantSource !== "session") {
562
+ ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over \`use\` here.`);
563
+ }
564
+ const shown = { ref: stored, id: found.id, name: found.name ?? null, slug: found.slug ?? null };
565
+ if (inSession) {
566
+ ctx.globals.sessionTenants.set(url, { ref: stored, id: found.id, ...(found.name ? { name: found.name } : {}), ...(found.slug ? { slug: found.slug } : {}) });
567
+ return {
568
+ data: { instance: url, tenant: shown, scope: "session" },
569
+ text: `Using tenant ${title} on ${url} for this MCP session; the tenant stored for your user (\`cavelon use\` in a terminal) is unchanged.`,
570
+ };
571
+ }
572
+ const token = requireToken(session);
499
573
  await updateInstance(ctx.io.env, url, (c) => ({
500
- ...c,
574
+ ...withTenantRefs(c, [ref, stored], found.id, token, ctx.io.now()),
501
575
  tenant: stored,
502
576
  tenant_id: found.id,
503
577
  tenant_name: found.name ?? (c.tenant_id === found.id ? c.tenant_name : undefined),
504
578
  tenant_slug: found.slug ?? (c.tenant_id === found.id ? c.tenant_slug : undefined),
505
- tenant_ids: { ...c.tenant_ids, [ref]: found.id, [stored]: found.id },
506
579
  }));
507
- if (session.tenantSource && session.tenantSource !== "use") {
508
- ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over \`use\` here.`);
509
- }
510
- return {
511
- data: { instance: url, tenant: { ref: stored, id: found.id, name: found.name ?? null, slug: found.slug ?? null } },
512
- text: `Using tenant ${tenantTitle({ id: found.id, name: found.name, slug: found.slug ?? (isUuid(ref) ? undefined : ref) })} on ${url}.`,
513
- };
580
+ return { data: { instance: url, tenant: shown }, text: `Using tenant ${title} on ${url}.` };
514
581
  },
515
582
  };
516
583
  async function nearQuotas(ctx) {
@@ -585,8 +652,10 @@ export const status = {
585
652
  let published;
586
653
  let reachError;
587
654
  let client;
655
+ let access;
588
656
  if (offline && session.url) {
589
- const cached = await new Contracts(new ApiClient({ url: session.url }, ctx.io.env), ctx.io.env, ctx.io.now)
657
+ const target = { url: session.url, token: session.token, tenantId: knownTenantId(session, ctx.io.now()) };
658
+ const cached = await new Contracts(new ApiClient(target, ctx.io.env), ctx.io.env, ctx.io.now)
590
659
  .cachedOnly("capabilities.json")
591
660
  .catch(() => undefined);
592
661
  if (cached?.value?.instance?.version) {
@@ -606,6 +675,15 @@ export const status = {
606
675
  shown.name = stored?.tenant_name ?? described.name ?? null;
607
676
  shown.slug = stored?.tenant_slug ?? described.slug ?? null;
608
677
  }
678
+ access = await accessFor(client);
679
+ if (access && data.credential) {
680
+ Object.assign(data.credential, {
681
+ scopes: access.scopes,
682
+ permissions: access.permissions,
683
+ may_activate: mayActivate(access),
684
+ needs_a_person: access.complete ? access.needsAPerson.length : null,
685
+ });
686
+ }
609
687
  const contracts = await ctx.contracts();
610
688
  const caps = await contracts.liveCapabilities();
611
689
  data.instance_version = caps?.instance.version ?? null;
@@ -661,6 +739,8 @@ export const status = {
661
739
  const lines = [
662
740
  ["instance", session.url ? `${session.url} (${session.urlSource})` : `none (\`${cavelonCommand("login", "--instance", fill("url"))}\`)`],
663
741
  ["credential", session.token ? `${session.tokenKind} from ${credentialSource(session)}` : "none"],
742
+ ["scopes", access?.scopes ? access.scopes.join(", ") || "none" : undefined],
743
+ ["permissions", permissionsText(access)],
664
744
  ["tenant", tenantText],
665
745
  ["solution", session.project ? session.project.file : "none (no cavelon.yaml here or above)"],
666
746
  ];
@@ -753,12 +833,19 @@ async function operationSolutions(ctx, operations) {
753
833
  return owners;
754
834
  }
755
835
  export async function rememberTenant(ctx, url, tenant) {
836
+ if (ctx.mode === "mcp") {
837
+ if (!ctx.globals.sessionTenants)
838
+ throw usageError("This MCP server keeps no session to choose the new tenant in; pass tenant to each tool instead.");
839
+ ctx.globals.sessionTenants.set(url, tenant);
840
+ return "session";
841
+ }
842
+ const token = requireToken(await ctx.session());
756
843
  await updateInstance(ctx.io.env, url, (c) => ({
757
- ...c,
844
+ ...withTenantRefs(c, [tenant.ref], tenant.id, token, ctx.io.now()),
758
845
  tenant: tenant.ref,
759
846
  tenant_id: tenant.id,
760
847
  tenant_name: tenant.name,
761
848
  tenant_slug: tenant.slug,
762
- tenant_ids: { ...c.tenant_ids, [tenant.ref]: tenant.id },
763
849
  }));
850
+ return "user";
764
851
  }
@@ -99,7 +99,7 @@ async function confirm(ctx, question, defaultYes) {
99
99
  }
100
100
  function confirmationRequired(what, details) {
101
101
  return new CavelonError(ExitCode.usage, {
102
- code: "confirmation_required",
102
+ code: "yes_required",
103
103
  message: `Nothing was changed: ${what}, and there is no terminal to ask.`,
104
104
  hint: "Read the plan in details, then run the same command with --yes.",
105
105
  details,