@cavelon/cli 0.1.10 → 0.1.11

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 (40) hide show
  1. package/README.md +23 -10
  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/commands/api.js +38 -19
  6. package/dist/commands/chat.js +10 -5
  7. package/dist/commands/db.js +367 -0
  8. package/dist/commands/docs.js +83 -7
  9. package/dist/commands/index.js +6 -0
  10. package/dist/commands/limits-set.js +4 -2
  11. package/dist/commands/loops.js +60 -5
  12. package/dist/commands/models.js +2 -1
  13. package/dist/commands/sandboxes.js +7 -2
  14. package/dist/commands/session.js +107 -22
  15. package/dist/commands/solution.js +144 -32
  16. package/dist/commands/tenants.js +44 -8
  17. package/dist/commands/values.js +50 -9
  18. package/dist/commands/work.js +13 -5
  19. package/dist/confirm-token.js +12 -4
  20. package/dist/context.js +3 -1
  21. package/dist/contracts.js +37 -12
  22. package/dist/database-queries.js +301 -0
  23. package/dist/fsutil.js +14 -0
  24. package/dist/http.js +36 -2
  25. package/dist/invoke.js +4 -0
  26. package/dist/kit-codes.js +5 -0
  27. package/dist/mcp.js +69 -10
  28. package/dist/package-check.js +19 -0
  29. package/dist/preview-report.js +2 -2
  30. package/dist/principal.js +24 -2
  31. package/dist/secret-access.js +16 -4
  32. package/dist/session.js +36 -8
  33. package/dist/skills/cavelon-authoring/SKILL.md +79 -2
  34. package/dist/skills/cavelon-long-running/SKILL.md +8 -2
  35. package/dist/skills/cavelon-loop/SKILL.md +71 -16
  36. package/dist/skills/cavelon-testing/SKILL.md +28 -1
  37. package/dist/trace-view.js +10 -0
  38. package/dist/update-check.js +2 -2
  39. package/dist/user-config.js +24 -0
  40. package/package.json +1 -1
@@ -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 } 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,69 @@ 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 in a test environment an agent may confirm on its own. Follow the run with `loop watch <run>`, or\n" +
186
+ "`wait <operation>`; `loop cancel <run>` stops it.",
176
187
  readOnly: false,
177
188
  mcpTool: "loop_start",
189
+ operations: ["POST /api/v1/triggers/{trigger_id}/run"],
178
190
  positionals: [{ name: "trigger", description: "Trigger slug, name or id.", required: true }],
179
191
  options: {
180
192
  input: { type: "string", value: "<json|@file|->", description: "The run's payload: JSON, @file.json or - for stdin." },
181
193
  wait: WAIT_OPTION,
182
194
  timeout: TIMEOUT_OPTION,
183
195
  "idempotency-key": UUID_KEY_OPTION,
196
+ confirm: { type: "boolean", mcpToken: true, description: "Start the run (after a person saw the preview)." },
184
197
  },
185
- examples: ["cavelon loop start counter", "cavelon loop start orders --input @orders-request.json --json"],
198
+ examples: [
199
+ "cavelon loop start counter",
200
+ "cavelon loop start counter --confirm",
201
+ "cavelon loop start counter --confirm <token>",
202
+ "cavelon loop start orders --input @orders-request.json --confirm --json",
203
+ ],
186
204
  async run(ctx, input) {
205
+ if (ctx.mode === "mcp" && input.options.confirm === true)
206
+ throw confirmTokenRequired("loop_start");
187
207
  await requireFeature(ctx, "masterloop_enabled", "masterloop_feature_disabled", "Masterloop");
188
208
  const trigger = await resolveTrigger(ctx, positional(input, "trigger"));
189
209
  const raw = stringOption(input, "input");
190
210
  const payload = raw === undefined ? {} : await readBody(ctx, raw);
191
211
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
192
212
  throw usageError("--input must be a JSON object.");
213
+ const gate = await confirmation(ctx, input, "loop_start", { trigger: trigger.id, payload });
214
+ if (!gate.confirmed) {
215
+ const solution = await triggerSolution(ctx, trigger);
216
+ const given = stringOption(input, "idempotency-key");
217
+ const words = ["loop", "start", trigger.slug, ...(raw !== undefined ? ["--input", raw] : []), ...(given ? ["--idempotency-key", given] : [])];
218
+ const confirm = gate.confirm(cavelonCommand(...words, "--confirm"));
219
+ const payloadText = clip(JSON.stringify(payload), 500);
220
+ return {
221
+ data: {
222
+ started: false,
223
+ would: "start_run",
224
+ trigger: { id: trigger.id, slug: trigger.slug, name: trigger.name, type: trigger.trigger_type, is_active: trigger.is_active },
225
+ solution,
226
+ payload,
227
+ confirm,
228
+ ...gate.fields,
229
+ },
230
+ text: [
231
+ `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.`,
232
+ !solution
233
+ ? "Solution: none named by the trigger."
234
+ : solution.status
235
+ ? `Solution: ${solution.name ?? solution.id}${solution.slug ? ` (${solution.slug})` : ""}, ${solution.status}.`
236
+ : `Solution: ${solution.id} (not readable).`,
237
+ `Payload: ${payloadText}`,
238
+ gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
239
+ `Nothing was started. Show this to a person; with their yes: ${confirm}`,
240
+ ].join("\n"),
241
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
242
+ };
243
+ }
193
244
  const key = idempotencyKey(input);
194
245
  const run = await callStable(ctx, "POST", "/api/v1/triggers/{trigger_id}/run", "starting triggers", {
195
246
  params: { trigger_id: [trigger.id] },
@@ -231,6 +282,7 @@ export const loopCancel = {
231
282
  destructive: true,
232
283
  idempotent: true,
233
284
  mcpTool: "loop_cancel",
285
+ operations: ["POST /api/v1/triggers/runs/{run_id}/cancel"],
234
286
  positionals: [{ name: "run", description: "The trigger run id (from `loop start`).", required: true }],
235
287
  options: {
236
288
  confirm: { type: "boolean", mcpToken: true, description: "Stop the run; without it nothing is stopped." },
@@ -252,6 +304,7 @@ export const loopCancel = {
252
304
  text: `Run ${run.id} (${run.workflow_name}) is ${run.status}` +
253
305
  (loops.length ? `, with loops:\n${table(loops, ["loop_id", "node", "state", "iteration"])}\n` : ".\n") +
254
306
  (note ? `${noteLines(note).slice(1)}\n` : "") +
307
+ `${gate.where}\n` +
255
308
  (gate.mismatch ? `${gate.mismatch}\n` : "") +
256
309
  `Nothing was stopped. Stop it with: ${confirm}`,
257
310
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
@@ -590,6 +643,7 @@ function controlCommand(action) {
590
643
  "the command); any other pause resumes without it. A pause that cannot be resumed is refused with what to do instead.",
591
644
  readOnly: false,
592
645
  mcpTool: `loop_${action}`,
646
+ operations: [`POST /api/v1/triggers/runs/{run_id}/loops/{loop_id}/${action}`],
593
647
  positionals: [{ name: "run", description: "The trigger run id.", required: true }],
594
648
  options: {
595
649
  loop: LOOP_OPTION,
@@ -755,6 +809,7 @@ export const triggerIdentity = {
755
809
  destructive: true,
756
810
  idempotent: true,
757
811
  mcpTool: "trigger_identity",
812
+ operations: ["PUT /api/v1/triggers/{trigger_id}/execution-identity"],
758
813
  positionals: [
759
814
  { name: "trigger", description: "Trigger slug, name or id.", required: true },
760
815
  { name: "key", description: "The API key's name or id (never its value)." },
@@ -792,7 +847,7 @@ export const triggerIdentity = {
792
847
  const confirm = gate.confirm(cavelonCommand("trigger", "identity", trigger.slug, keyRef ?? "--clear", "--confirm"));
793
848
  return {
794
849
  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}`,
850
+ text: `${identityText(trigger, view)}\n\n${gate.where}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing changed. To ${change}: ${confirm}`,
796
851
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
797
852
  };
798
853
  }
@@ -146,6 +146,7 @@ export const modelsSetLimit = {
146
146
  destructive: true,
147
147
  idempotent: true,
148
148
  mcpTool: "models_set_limit",
149
+ operations: ["PATCH /api/v1/model-registry/{model_registry_id}"],
149
150
  positionals: [
150
151
  { name: "model", description: "The row's model_id, id or display name (`cavelon models list`).", required: true },
151
152
  { name: "limit", description: "Requests the endpoint serves at once (a whole number), or none to clear the limit.", required: true },
@@ -188,7 +189,7 @@ export const modelsSetLimit = {
188
189
  const confirm = gate.confirm(cavelonCommand("models", "set-limit", row.model_id, limitText(limit), "--confirm"));
189
190
  return {
190
191
  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}`,
192
+ 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
193
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
193
194
  };
194
195
  }
@@ -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],
439
+ ["may activate", activateText(data.credential.may_activate, access)],
430
440
  ["may set secrets", secretsText(data.credential.may_set_secrets)],
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,6 +449,39 @@ export const whoami = {
435
449
  };
436
450
  },
437
451
  };
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) {
466
+ if (may === null)
467
+ return undefined;
468
+ return may ? "yes" : "no (a tenant Owner sets them, in the Admin or with their own token)";
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
+ }
438
485
  function secretsText(may) {
439
486
  if (may === null)
440
487
  return undefined;
@@ -445,7 +492,9 @@ export const use = {
445
492
  summary: "Choose the tenant this instance's commands act in.",
446
493
  description: "Stored per instance for your user. CAVELON_TENANT, --tenant and a cavelon.yaml tenant take precedence over it.\n" +
447
494
  "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.",
495
+ "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" +
496
+ "As an MCP tool it never changes the tenant stored for your user: it chooses the tenant for that MCP session only, " +
497
+ "until the session ends or it is cleared, so an agent's choice never moves where your own commands go.",
449
498
  readOnly: false,
450
499
  idempotent: true,
451
500
  mcpTool: "use_tenant",
@@ -456,7 +505,17 @@ export const use = {
456
505
  const session = await ctx.session();
457
506
  const url = requireInstance(session);
458
507
  requireToken(session);
508
+ const inSession = ctx.mode === "mcp";
509
+ if (inSession && !ctx.globals.sessionTenants)
510
+ throw usageError("This MCP server keeps no session, so use_tenant cannot choose a tenant; pass tenant to each tool instead.");
459
511
  if (boolOption(input, "clear")) {
512
+ if (inSession) {
513
+ ctx.globals.sessionTenants.delete(url);
514
+ return {
515
+ data: { instance: url, tenant: null, scope: "session" },
516
+ text: `No tenant chosen for ${url} in this MCP session; tools act in the tenant chosen for this folder or with \`cavelon use\` again.`,
517
+ };
518
+ }
460
519
  await updateInstance(ctx.io.env, url, (c) => ({ ...c, tenant: undefined, tenant_id: undefined, tenant_name: undefined, tenant_slug: undefined }));
461
520
  return { data: { instance: url, tenant: null }, text: `No tenant chosen for ${url}.` };
462
521
  }
@@ -496,21 +555,27 @@ export const use = {
496
555
  const probe = new ApiClient({ ...client.target, tenantId: found.id }, ctx.io.env);
497
556
  await probe.get("/api/v1/meta/capabilities", { allow: [404] });
498
557
  const stored = found.slug ?? ref;
558
+ const title = tenantTitle({ id: found.id, name: found.name, slug: found.slug ?? (isUuid(ref) ? undefined : ref) });
559
+ if (session.tenantSource && session.tenantSource !== "use" && session.tenantSource !== "session") {
560
+ ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over \`use\` here.`);
561
+ }
562
+ const shown = { ref: stored, id: found.id, name: found.name ?? null, slug: found.slug ?? null };
563
+ if (inSession) {
564
+ ctx.globals.sessionTenants.set(url, { ref: stored, id: found.id, ...(found.name ? { name: found.name } : {}), ...(found.slug ? { slug: found.slug } : {}) });
565
+ return {
566
+ data: { instance: url, tenant: shown, scope: "session" },
567
+ text: `Using tenant ${title} on ${url} for this MCP session; the tenant stored for your user (\`cavelon use\` in a terminal) is unchanged.`,
568
+ };
569
+ }
570
+ const token = requireToken(session);
499
571
  await updateInstance(ctx.io.env, url, (c) => ({
500
- ...c,
572
+ ...withTenantRefs(c, [ref, stored], found.id, token, ctx.io.now()),
501
573
  tenant: stored,
502
574
  tenant_id: found.id,
503
575
  tenant_name: found.name ?? (c.tenant_id === found.id ? c.tenant_name : undefined),
504
576
  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
577
  }));
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
- };
578
+ return { data: { instance: url, tenant: shown }, text: `Using tenant ${title} on ${url}.` };
514
579
  },
515
580
  };
516
581
  async function nearQuotas(ctx) {
@@ -585,8 +650,10 @@ export const status = {
585
650
  let published;
586
651
  let reachError;
587
652
  let client;
653
+ let access;
588
654
  if (offline && session.url) {
589
- const cached = await new Contracts(new ApiClient({ url: session.url }, ctx.io.env), ctx.io.env, ctx.io.now)
655
+ const target = { url: session.url, token: session.token, tenantId: knownTenantId(session, ctx.io.now()) };
656
+ const cached = await new Contracts(new ApiClient(target, ctx.io.env), ctx.io.env, ctx.io.now)
590
657
  .cachedOnly("capabilities.json")
591
658
  .catch(() => undefined);
592
659
  if (cached?.value?.instance?.version) {
@@ -606,6 +673,15 @@ export const status = {
606
673
  shown.name = stored?.tenant_name ?? described.name ?? null;
607
674
  shown.slug = stored?.tenant_slug ?? described.slug ?? null;
608
675
  }
676
+ access = await accessFor(client);
677
+ if (access && data.credential) {
678
+ Object.assign(data.credential, {
679
+ scopes: access.scopes,
680
+ permissions: access.permissions,
681
+ may_activate: mayActivate(access),
682
+ needs_a_person: access.complete ? access.needsAPerson.length : null,
683
+ });
684
+ }
609
685
  const contracts = await ctx.contracts();
610
686
  const caps = await contracts.liveCapabilities();
611
687
  data.instance_version = caps?.instance.version ?? null;
@@ -661,6 +737,8 @@ export const status = {
661
737
  const lines = [
662
738
  ["instance", session.url ? `${session.url} (${session.urlSource})` : `none (\`${cavelonCommand("login", "--instance", fill("url"))}\`)`],
663
739
  ["credential", session.token ? `${session.tokenKind} from ${credentialSource(session)}` : "none"],
740
+ ["scopes", access?.scopes ? access.scopes.join(", ") || "none" : undefined],
741
+ ["permissions", permissionsText(access)],
664
742
  ["tenant", tenantText],
665
743
  ["solution", session.project ? session.project.file : "none (no cavelon.yaml here or above)"],
666
744
  ];
@@ -753,12 +831,19 @@ async function operationSolutions(ctx, operations) {
753
831
  return owners;
754
832
  }
755
833
  export async function rememberTenant(ctx, url, tenant) {
834
+ if (ctx.mode === "mcp") {
835
+ if (!ctx.globals.sessionTenants)
836
+ throw usageError("This MCP server keeps no session to choose the new tenant in; pass tenant to each tool instead.");
837
+ ctx.globals.sessionTenants.set(url, tenant);
838
+ return "session";
839
+ }
840
+ const token = requireToken(await ctx.session());
756
841
  await updateInstance(ctx.io.env, url, (c) => ({
757
- ...c,
842
+ ...withTenantRefs(c, [tenant.ref], tenant.id, token, ctx.io.now()),
758
843
  tenant: tenant.ref,
759
844
  tenant_id: tenant.id,
760
845
  tenant_name: tenant.name,
761
846
  tenant_slug: tenant.slug,
762
- tenant_ids: { ...c.tenant_ids, [tenant.ref]: tenant.id },
763
847
  }));
848
+ return "user";
764
849
  }