@cavelon/cli 0.1.9 → 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 (64) 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/branches.js +4 -3
  6. package/dist/capacity.js +3 -2
  7. package/dist/code-hints.js +5 -4
  8. package/dist/command.js +6 -0
  9. package/dist/commands/api.js +40 -21
  10. package/dist/commands/async.js +7 -4
  11. package/dist/commands/chat.js +18 -15
  12. package/dist/commands/db.js +367 -0
  13. package/dist/commands/docs.js +87 -9
  14. package/dist/commands/fmt.js +6 -4
  15. package/dist/commands/index.js +8 -0
  16. package/dist/commands/init.js +106 -28
  17. package/dist/commands/limits-set.js +12 -11
  18. package/dist/commands/limits.js +4 -3
  19. package/dist/commands/loops.js +75 -19
  20. package/dist/commands/models.js +12 -13
  21. package/dist/commands/sandboxes.js +22 -16
  22. package/dist/commands/schema.js +6 -5
  23. package/dist/commands/session.js +134 -37
  24. package/dist/commands/setup.js +4 -2
  25. package/dist/commands/solution.js +289 -93
  26. package/dist/commands/tenants.js +58 -22
  27. package/dist/commands/values.js +110 -45
  28. package/dist/commands/work.js +31 -17
  29. package/dist/confirm-token.js +15 -5
  30. package/dist/context.js +3 -1
  31. package/dist/contracts.js +39 -13
  32. package/dist/database-queries.js +301 -0
  33. package/dist/default-route.js +1 -1
  34. package/dist/features.js +2 -1
  35. package/dist/fsutil.js +14 -0
  36. package/dist/harness-ref.js +6 -4
  37. package/dist/http.js +39 -4
  38. package/dist/invoke.js +7 -2
  39. package/dist/kit-codes.js +14 -2
  40. package/dist/limits.js +1 -1
  41. package/dist/main.js +13 -1
  42. package/dist/mcp.js +105 -26
  43. package/dist/openapi.js +5 -2
  44. package/dist/operations.js +3 -2
  45. package/dist/package-check.js +29 -4
  46. package/dist/package-files.js +5 -1
  47. package/dist/package-format.js +10 -0
  48. package/dist/preview-report.js +46 -7
  49. package/dist/principal.js +24 -2
  50. package/dist/printed.js +182 -0
  51. package/dist/project.js +2 -1
  52. package/dist/results.js +1 -1
  53. package/dist/secret-access.js +42 -0
  54. package/dist/session.js +39 -19
  55. package/dist/shell.js +0 -3
  56. package/dist/skills/cavelon-authoring/SKILL.md +88 -4
  57. package/dist/skills/cavelon-long-running/SKILL.md +9 -3
  58. package/dist/skills/cavelon-loop/SKILL.md +81 -19
  59. package/dist/skills/cavelon-testing/SKILL.md +28 -1
  60. package/dist/tenant-choice.js +7 -7
  61. package/dist/trace-view.js +11 -1
  62. package/dist/update-check.js +2 -2
  63. package/dist/user-config.js +24 -0
  64. package/package.json +1 -1
@@ -6,11 +6,12 @@ import { callStable } from "../invoke.js";
6
6
  import { formatQuota, limitError, limitsOrWarn, readQuotas } from "../limits.js";
7
7
  import { containing } from "../choose.js";
8
8
  import { readPrincipal, readTenantless } from "../principal.js";
9
- import { contextFlags, requireInstance } from "../session.js";
9
+ import { ACTIVATOR, accessFor, mayActivate } from "../access.js";
10
+ import { requireInstance } from "../session.js";
10
11
  import { listsTenants, searchTenants } from "../tenant-choice.js";
11
12
  import { harnessNotFoundError, lookupHarness, resolveHarnessId } from "../harness-ref.js";
12
13
  import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
13
- import { cavelonCommand } from "../shell.js";
14
+ import { cavelonCommand, fill } from "../printed.js";
14
15
  import { rememberTenant } from "./session.js";
15
16
  function idempotency(key) {
16
17
  return key ? { "Idempotency-Key": key } : undefined;
@@ -75,21 +76,32 @@ async function entersTenant(client, tenantId) {
75
76
  }
76
77
  export const tenantCreate = {
77
78
  name: "tenant create",
78
- summary: "Create a tenant (personal access token in Platform mode with tenants.manage).",
79
+ tenantless: true,
80
+ summary: "Create a tenant (personal access token in Platform mode with tenants.manage); previews first, --confirm creates it.",
79
81
  description: "A tenant API key never can. Before sending, the token is checked: one that may not enter Platform mode, or enters it\n" +
80
- "without tenants.manage, is refused with exit 7 and nothing is sent. With --use, the new tenant is chosen only once the\n" +
81
- "instance confirms the token acts in it. Inviting people and assigning roles stay in the Admin.",
82
+ "without tenants.manage, is refused with exit 7 and nothing is sent. Without --confirm nothing is created: the preview\n" +
83
+ "names the tenant, its plan and the instance it would be created on. A tenant is a platform change, so show the preview\n" +
84
+ "to a person and confirm only with their yes. With --use, the new tenant is chosen only once the instance confirms the\n" +
85
+ "token acts in it. Inviting people and assigning roles stay in the Admin.",
82
86
  readOnly: false,
83
87
  mcpTool: "tenant_create",
84
88
  positionals: [{ name: "slug", description: "Lower-case letters, digits and dashes.", required: true }],
85
89
  options: {
86
90
  name: { type: "string", value: "<name>", description: "Display name (default: the slug)." },
87
91
  plan: { type: "string", value: "<plan>", description: "Licence plan, when the instance knows several." },
88
- use: { type: "boolean", description: "Switch to the new tenant afterwards (`cavelon use`), once the token is known to act in it." },
92
+ use: {
93
+ type: "boolean",
94
+ description: "Switch to the new tenant afterwards (`cavelon use`), once the token is known to act in it.",
95
+ mcpDescription: "Switch to the new tenant afterwards for this MCP session only (as use_tenant does), once the token is known to act in it.",
96
+ },
89
97
  "idempotency-key": IDEMPOTENCY_OPTION,
98
+ confirm: { type: "boolean", mcpToken: true, description: "Create the tenant (after a person saw the preview)." },
90
99
  },
100
+ examples: ["cavelon tenant create newco --name NewCo", "cavelon tenant create newco --name NewCo --confirm", "cavelon tenant create newco --name NewCo --confirm <token>"],
91
101
  async run(ctx, input) {
92
102
  const session = await ctx.session();
103
+ if (ctx.mode === "mcp" && input.options.confirm === true)
104
+ throw confirmTokenRequired("tenant_create");
93
105
  if (session.tokenKind === "api_key") {
94
106
  throw new CavelonError(ExitCode.unauthorized, {
95
107
  code: "api_key_cannot_create_tenants",
@@ -104,6 +116,23 @@ export const tenantCreate = {
104
116
  const plan = stringOption(input, "plan");
105
117
  if (plan)
106
118
  body.plan = plan;
119
+ const gate = await confirmation(ctx, input, "tenant_create", body, { platform: "outside" });
120
+ if (!gate.confirmed) {
121
+ const words = ["tenant", "create", slug, "--name", body.name, ...(plan ? ["--plan", plan] : []), ...(boolOption(input, "use") ? ["--use"] : [])];
122
+ const key = stringOption(input, "idempotency-key");
123
+ if (key)
124
+ words.push("--idempotency-key", key);
125
+ const confirm = gate.confirm(cavelonCommand(...words, "--confirm"));
126
+ return {
127
+ data: { created: false, would: "create_tenant", tenant: { slug, name: body.name, plan: plan ?? null }, confirm, ...gate.fields },
128
+ text: [
129
+ `Creating tenant ${body.name} (${slug})${plan ? ` on plan ${plan}` : ""} adds a tenant to the platform: it holds its own solutions, people, limits and budget.`,
130
+ gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
131
+ `Nothing was created. Show this to a person; with their yes: ${confirm}`,
132
+ ].join("\n"),
133
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
134
+ };
135
+ }
107
136
  const tenant = await callStable(ctx, "POST", "/api/v1/tenants", "creating tenants", {
108
137
  body,
109
138
  sendTenant: false,
@@ -119,12 +148,16 @@ export const tenantCreate = {
119
148
  `\`${cavelonCommand("use", tenant.slug)}\`.`);
120
149
  return { data: { ...tenant, used: false }, text: `${created} Not switched: this token does not act in it.` };
121
150
  }
122
- await rememberTenant(ctx, requireInstance(session), { ref: tenant.slug, id: tenant.id, name: tenant.name });
123
- return { data: { ...tenant, used: true }, text: `${created} Now using it.` };
151
+ const scope = await rememberTenant(ctx, requireInstance(session), { ref: tenant.slug, id: tenant.id, name: tenant.name, slug: tenant.slug });
152
+ return {
153
+ data: { ...tenant, used: true, ...(scope === "session" ? { used_in: "session" } : {}) },
154
+ text: scope === "session" ? `${created} Now using it in this MCP session; the tenant stored for your user is unchanged.` : `${created} Now using it.`,
155
+ };
124
156
  },
125
157
  };
126
158
  export const tenantList = {
127
159
  name: "tenant list",
160
+ tenantless: true,
128
161
  summary: "List the tenants this token can see, with name, slug and id.",
129
162
  description: "A personal access token in Platform mode sees every tenant; any other sees the tenants it reaches. " +
130
163
  "An operator's token that reaches every tenant lists the person's own and finds any other with --search.",
@@ -139,7 +172,7 @@ export const tenantList = {
139
172
  async run(ctx, input) {
140
173
  const session = await ctx.session();
141
174
  if (session.tokenKind === "api_key") {
142
- throw usageError("A tenant API key sees only its own tenant.", "`cavelon whoami` shows it.");
175
+ throw usageError("A tenant API key sees only its own tenant.", `\`${cavelonCommand("whoami")}\` shows it.`);
143
176
  }
144
177
  const limit = intOption(input, "limit", { min: 1, max: 200, fallback: 50 });
145
178
  const cursor = stringOption(input, "cursor");
@@ -173,8 +206,8 @@ export const tenantList = {
173
206
  page.listed = "own_memberships";
174
207
  page.note = "This token reaches every tenant; items and total count only your own memberships. Find any tenant with --search <part of the name>.";
175
208
  note = all.length
176
- ? `\nThese are your own memberships; this token reaches every tenant on ${client.url}. Find any other: cavelon tenant list --search <part of the name>`
177
- : `No memberships of your own; this token reaches every tenant on ${client.url}. Find any tenant with: cavelon tenant list --search <part of the name>`;
209
+ ? `\nThese are your own memberships; this token reaches every tenant on ${client.url}. Find any other: ${cavelonCommand("tenant", "list", "--search", fill("part of the name"))}`
210
+ : `No memberships of your own; this token reaches every tenant on ${client.url}. Find any tenant with: ${cavelonCommand("tenant", "list", "--search", fill("part of the name"))}`;
178
211
  }
179
212
  }
180
213
  else {
@@ -187,10 +220,10 @@ export const tenantList = {
187
220
  }
188
221
  const columns = page.source === "platform" ? ["name", "slug", "status", "id"] : ["name", "slug", "role", "id"];
189
222
  const empty = search ? `No tenant's name or slug contains "${search}".` : note ? "" : "No tenants.";
190
- const next = page.items.length ? `\nChoose one: cavelon use <slug> (or \`cavelon use\` to pick from a list)` : "";
223
+ const next = page.items.length ? `\nChoose one: ${cavelonCommand("use", fill("slug"))} (or \`${cavelonCommand("use")}\` to pick from a list)` : "";
191
224
  return {
192
225
  data: page,
193
- text: ((table(page.items, columns) || empty) + moreHint(page.next_cursor, "cavelon tenant list") + note + next).trimStart(),
226
+ text: ((table(page.items, columns) || empty) + moreHint(page.next_cursor, cavelonCommand("tenant", "list")) + note + next).trimStart(),
194
227
  };
195
228
  },
196
229
  };
@@ -225,7 +258,7 @@ export const harnessList = {
225
258
  const columns = ["slug", "name", "status", ...(marksDefault ? ["default"] : []), ...(boolOption(input, "readiness") ? ["ready_to_activate"] : []), "id"];
226
259
  return {
227
260
  data: page,
228
- text: (table(rows, columns) || "No solutions yet. Create one: cavelon harness new <slug>") + moreHint(page.next_cursor, "cavelon harness list"),
261
+ text: (table(rows, columns) || `No solutions yet. Create one: ${cavelonCommand("harness", "new", fill("slug"))}`) + moreHint(page.next_cursor, cavelonCommand("harness", "list")),
229
262
  };
230
263
  },
231
264
  };
@@ -240,6 +273,7 @@ export const harnessDefault = {
240
273
  readOnly: false,
241
274
  idempotent: true,
242
275
  mcpTool: "harness_default",
276
+ operations: ["POST /api/v1/harnesses/{harness_id}/default"],
243
277
  positionals: [{ name: "solution", description: "Name, slug or id of the solution; default: cavelon.yaml's harness." }],
244
278
  options: {
245
279
  confirm: { type: "boolean", mcpToken: true, description: "Change the default route (after a person saw the preview)." },
@@ -249,14 +283,12 @@ export const harnessDefault = {
249
283
  const session = await ctx.session();
250
284
  const ref = positional(input, "solution") ?? session.envFile?.harness ?? session.project?.harness;
251
285
  if (!ref)
252
- throw usageError("Which solution?", "Pass its name or slug (`cavelon harness list` shows them), or run it in a folder whose cavelon.yaml names one.");
286
+ throw usageError("Which solution?", `Pass its name or slug (\`${cavelonCommand("harness", "list")}\` shows them), or run it in a folder whose cavelon.yaml names one.`);
253
287
  if (ctx.mode === "mcp" && input.options.confirm === true)
254
288
  throw confirmTokenRequired("harness_default");
255
289
  const { harness, candidates } = await lookupHarness(ctx, ref);
256
- if (!harness) {
257
- const flags = contextFlags(session);
258
- throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug) + flags, flags);
259
- }
290
+ if (!harness)
291
+ throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug));
260
292
  const route = await readDefaultRoute(ctx);
261
293
  const target = { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status };
262
294
  const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
@@ -268,7 +300,9 @@ export const harnessDefault = {
268
300
  throw new CavelonError(ExitCode.conflict, {
269
301
  code: "solution_not_active",
270
302
  message: `${named(harness)} is ${harness.status}, and only an active solution can be the tenant's default route; nothing was changed.`,
271
- hint: `Activate it through the readiness gate and preview the default route in one step: ${cavelonCommand("activate", "--harness", harness.slug, "--make-default")}. ` +
303
+ hint: (mayActivate(await accessFor(await ctx.client())) === false
304
+ ? `Only an active solution can be the default, and to activate it ${ACTIVATOR}. `
305
+ : `Activate it through the readiness gate and preview the default route in one step: ${cavelonCommand("activate", "--harness", harness.slug, "--make-default")}. `) +
272
306
  `The default route stays ${current ? named(current) : "as it is"} until then.`,
273
307
  details: { harness: target, default_route: current },
274
308
  });
@@ -286,7 +320,7 @@ export const harnessDefault = {
286
320
  },
287
321
  text: [
288
322
  defaultChangeLine(harness, route),
289
- ...(gate.mismatch ? [gate.mismatch] : []),
323
+ gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
290
324
  `Show this to a person; with their yes: ${gate.confirm(commands.confirm)}`,
291
325
  ].join("\n"),
292
326
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
@@ -318,7 +352,7 @@ async function checkHarnessCapacity(ctx, slug) {
318
352
  throw new CavelonError(ExitCode.validation, {
319
353
  code: "tenant_quota_reached",
320
354
  message: `This tenant has used ${formatQuota(quota)} of its solution quota, so nothing was sent.`,
321
- hint: `A platform administrator raises the tenant's quotas; \`cavelon limits\` shows them${quotas.docs ? ` (docs: ${quotas.docs})` : ""}. Archiving an unused solution frees one.`,
355
+ hint: `A platform administrator raises the tenant's quotas; \`${cavelonCommand("limits")}\` shows them${quotas.docs ? ` (docs: ${quotas.docs})` : ""}. Archiving an unused solution frees one.`,
322
356
  docs: quotas.docs ?? undefined,
323
357
  details: { quota: { key: quota.key, current: quota.current, limit: quota.limit, path: quotas.path }, sent: false },
324
358
  });
@@ -347,6 +381,7 @@ export const harnessNew = {
347
381
  summary: "Create an empty draft solution (harness).",
348
382
  readOnly: false,
349
383
  mcpTool: "harness_new",
384
+ operations: ["POST /api/v1/harnesses"],
350
385
  positionals: [{ name: "slug", description: "The new solution's slug.", required: true }],
351
386
  options: {
352
387
  name: { type: "string", value: "<name>", description: "Display name (default: the slug)." },
@@ -375,6 +410,7 @@ export const harnessClone = {
375
410
  summary: "Copy a solution into a new draft solution.",
376
411
  readOnly: false,
377
412
  mcpTool: "harness_clone",
413
+ operations: ["POST /api/v1/harnesses/{harness_id}/clone"],
378
414
  positionals: [{ name: "source", description: "Name, slug or id of the solution to copy.", required: true }],
379
415
  options: {
380
416
  slug: { type: "string", value: "<slug>", description: "The copy's slug." },
@@ -1,4 +1,5 @@
1
1
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption, } from "../command.js";
2
+ import { refuseForAgent } from "../agent-env.js";
2
3
  import { confirmation } from "../confirm-token.js";
3
4
  import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
4
5
  import { clip, keyValues, moreHint, table } from "../format.js";
@@ -6,9 +7,11 @@ import { callStable, workflowOperation } from "../invoke.js";
6
7
  import { readAll } from "../io.js";
7
8
  import { schemaErrors } from "../openapi.js";
8
9
  import { readPrincipal } from "../principal.js";
10
+ import { permissionsNamed, SECRETS_PERMISSIONS, secretsPermissionMissing, variablesPermissionMissing } from "../secret-access.js";
9
11
  import { readHidden } from "../prompt.js";
12
+ import { readPackage } from "../package-files.js";
10
13
  import { requireToken } from "../session.js";
11
- import { shellWord } from "../shell.js";
14
+ import { cavelonCommand, fill, printedCommand } from "../printed.js";
12
15
  export const ENV_OPTION = { type: "string", value: "<name>", description: "Act in the tenant that env/<name>.yaml names." };
13
16
  const CONFIRM_OPTION = {
14
17
  type: "boolean",
@@ -17,21 +20,11 @@ const CONFIRM_OPTION = {
17
20
  };
18
21
  const TOKEN_PREFIXES = ["cbp_", "cvpat_"];
19
22
  const LIST_VALUE_CHARS = 200;
20
- export function targetFlags(session, env = session.envFile?.name) {
21
- let flags = "";
22
- if (session.urlSource === "option" && session.url)
23
- flags += ` --instance ${shellWord(session.url)}`;
24
- if (env)
25
- flags += ` --env ${shellWord(env)}`;
26
- if (session.tenantSource === "option" && session.tenant)
27
- flags += ` --tenant ${shellWord(session.tenant)}`;
28
- return flags;
23
+ export function secretSetCommand(name, env) {
24
+ return printedCommand(["secrets", "set", name], { env });
29
25
  }
30
- export function secretSetCommand(name, flags = "") {
31
- return `cavelon secrets set ${shellWord(name)}${flags}`;
32
- }
33
- export function variableSetCommand(name, flags = "") {
34
- return `cavelon variables set ${shellWord(name)} <value>${flags}`;
26
+ export function variableSetCommand(name, env) {
27
+ return printedCommand(["variables", "set", name, fill("value")], { env });
35
28
  }
36
29
  async function checkName(ctx, method, template, what, name) {
37
30
  const { doc, op } = await workflowOperation(ctx, method, template, what);
@@ -56,12 +49,12 @@ async function readVariable(ctx, name) {
56
49
  throw error;
57
50
  }
58
51
  }
59
- function variableNotSet(name, flags) {
52
+ function variableNotSet(name) {
60
53
  return new CavelonError(ExitCode.failure, {
61
54
  code: "variable_not_set",
62
55
  status: 404,
63
56
  message: `This tenant has no variable "${name}".`,
64
- hint: `\`cavelon variables list\` shows them; \`${variableSetCommand(name, flags)}\` sets it.`,
57
+ hint: `\`${cavelonCommand("variables", "list")}\` shows them; \`${variableSetCommand(name)}\` sets it.`,
65
58
  });
66
59
  }
67
60
  export const variablesList = {
@@ -84,10 +77,9 @@ export const variablesList = {
84
77
  ...(v.value.length > LIST_VALUE_CHARS ? { value_truncated: true } : {}),
85
78
  source: v.source ?? null,
86
79
  }));
87
- const flags = targetFlags(await ctx.session());
88
80
  const text = items.length
89
- ? table(items.map((v) => ({ ...v, source: v.source ?? "" })), ["name", "value", "source"], 60) + moreHint(page.next_cursor, `cavelon variables list${flags}`)
90
- : `No variables in this tenant. Set one with: cavelon variables set <name> <value>${flags}`;
81
+ ? table(items.map((v) => ({ ...v, source: v.source ?? "" })), ["name", "value", "source"], 60) + moreHint(page.next_cursor, cavelonCommand("variables", "list"))
82
+ : `No variables in this tenant. Set one with: ${cavelonCommand("variables", "set", fill("name"), fill("value"))}`;
91
83
  return { data: { items, next_cursor: page.next_cursor, total: page.total }, text };
92
84
  },
93
85
  };
@@ -103,7 +95,7 @@ export const variablesGet = {
103
95
  const name = positional(input, "name");
104
96
  const variable = await readVariable(ctx, name);
105
97
  if (!variable)
106
- throw variableNotSet(name, targetFlags(await ctx.session()));
98
+ throw variableNotSet(name);
107
99
  const data = { name: variable.name, value: variable.value, source: variable.source ?? null };
108
100
  return {
109
101
  data,
@@ -117,12 +109,16 @@ export const variablesGet = {
117
109
  };
118
110
  export const variablesSet = {
119
111
  name: "variables set",
120
- summary: "Create or replace a tenant variable.",
112
+ summary: "Create a tenant variable, or replace one (previews first, --confirm replaces it).",
121
113
  description: "The value is plain text that anyone who may view the tenant's settings reads; never put a credential into a variable,\n" +
122
- "use `cavelon secrets set` (a person runs it). --stdin reads the value from standard input instead of the argument.",
114
+ "use `cavelon secrets set` (a person runs it). --stdin reads the value from standard input instead of the argument.\n" +
115
+ "A new variable is created at once. Replacing another value needs --confirm: without it nothing changes, and the preview\n" +
116
+ "shows the old and the new value. A variable is tenant-wide, so every solution that names it, active ones included, reads\n" +
117
+ "the new value: show the preview to a person and confirm only with their yes.",
123
118
  readOnly: false,
124
119
  idempotent: true,
125
120
  mcpTool: "variables_set",
121
+ operations: ["PUT /api/v1/variables/{name}"],
126
122
  positionals: [
127
123
  { name: "name", description: "The variable's name, as {{var:<name>}} uses it.", required: true },
128
124
  { name: "value", description: "The value (plain text, not a credential)." },
@@ -130,8 +126,14 @@ export const variablesSet = {
130
126
  options: {
131
127
  stdin: { type: "boolean", description: "Read the value from standard input.", cliOnly: true },
132
128
  env: ENV_OPTION,
129
+ confirm: { type: "boolean", mcpToken: true, description: "Replace an existing value (after a person saw the preview); a new variable needs none." },
133
130
  },
134
- examples: ["cavelon variables set crm_base_url https://crm.example.com", "cavelon variables set greeting --stdin < greeting.txt"],
131
+ examples: [
132
+ "cavelon variables set crm_base_url https://crm.example.com",
133
+ "cavelon variables set greeting --stdin < greeting.txt",
134
+ "cavelon variables set crm_base_url https://crm2.example.com --confirm",
135
+ "cavelon variables set crm_base_url https://crm2.example.com --confirm <token>",
136
+ ],
135
137
  async run(ctx, input) {
136
138
  const name = positional(input, "name");
137
139
  const argument = positional(input, "value");
@@ -146,9 +148,27 @@ export const variablesSet = {
146
148
  }
147
149
  await checkName(ctx, "PUT", "/api/v1/variables/{name}", "setting tenant variables", name);
148
150
  const previous = await readVariable(ctx, name);
151
+ if (previous && previous.value !== value) {
152
+ const gate = await confirmation(ctx, input, "variables_set", { name, previous: previous.value, value });
153
+ if (!gate.confirmed) {
154
+ const confirm = gate.confirm(cavelonCommand("variables", "set", name, ...(fromStdin ? ["--stdin"] : [value]), "--confirm"));
155
+ return {
156
+ data: { name, changed: false, created: false, would: "replace", previous: previous.value, value, confirm, ...gate.fields },
157
+ text: [
158
+ `Variable ${name}: ${JSON.stringify(clip(previous.value, LIST_VALUE_CHARS))} → ${JSON.stringify(clip(value, LIST_VALUE_CHARS))}.`,
159
+ "It is tenant-wide: every solution of the tenant that names {{var:" + name + "}}, active ones included, reads the new value.",
160
+ gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
161
+ `Nothing was changed. Show this to a person; with their yes: ${confirm}${fromStdin ? " (with the same value on standard input)" : ""}`,
162
+ ].join("\n"),
163
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
164
+ };
165
+ }
166
+ }
149
167
  const saved = await callStable(ctx, "PUT", "/api/v1/variables/{name}", "setting tenant variables", {
150
168
  params: { name: [name] },
151
169
  body: { value },
170
+ }).catch((error) => {
171
+ throw variablesRefusedForRole(error, "set", name, fromStdin ? undefined : value);
152
172
  });
153
173
  const changed = previous?.value !== saved.value;
154
174
  let text = `Variable ${saved.name} already had this value.`;
@@ -172,16 +192,15 @@ export const variablesDelete = {
172
192
  examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm", "cavelon variables delete old_url --confirm <token>"],
173
193
  async run(ctx, input) {
174
194
  const name = positional(input, "name");
175
- const flags = targetFlags(await ctx.session());
176
195
  const current = await readVariable(ctx, name);
177
196
  if (!current)
178
197
  return { data: { name, deleted: false, existed: false }, text: `This tenant has no variable "${name}"; nothing to delete.` };
179
198
  const gate = await confirmation(ctx, input, "variables_delete", { name, value: current.value });
180
199
  if (!gate.confirmed) {
181
- const confirm = gate.confirm(`cavelon variables delete ${shellWord(name)}${flags} --confirm`);
200
+ const confirm = gate.confirm(cavelonCommand("variables", "delete", name, "--confirm"));
182
201
  return {
183
202
  data: { name, deleted: false, existed: true, value: current.value, confirm, ...gate.fields },
184
- text: `Variable ${name} = ${JSON.stringify(clip(current.value, LIST_VALUE_CHARS))}.\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
203
+ text: `Variable ${name} = ${JSON.stringify(clip(current.value, LIST_VALUE_CHARS))}.\n${gate.where}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
185
204
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
186
205
  };
187
206
  }
@@ -190,7 +209,7 @@ export const variablesDelete = {
190
209
  }
191
210
  catch (error) {
192
211
  if (!notFound(error))
193
- throw error;
212
+ throw variablesRefusedForRole(error, "delete", name);
194
213
  return { data: { name, deleted: false, existed: false }, text: `This tenant has no variable "${name}"; nothing to delete.` };
195
214
  }
196
215
  return { data: { name, deleted: true, existed: true, value: current.value }, text: `Deleted variable ${name}.` };
@@ -208,10 +227,26 @@ async function requirePerson(ctx, verb, name) {
208
227
  throw new CavelonError(ExitCode.unauthorized, {
209
228
  code: "secret_needs_a_person",
210
229
  message: `A tenant API key cannot ${verb} a secret, so nothing was sent: ${verb === "set" ? "setting" : "deleting"} a secret needs a person (a dashboard session or a personal access token).`,
211
- hint: `${fromEnv}A person logs in with a personal access token (\`cavelon login\`) and runs \`cavelon secrets ${verb} ${shellWord(name)}\`, or does it in the Admin.`,
230
+ hint: `${fromEnv}A person logs in with a personal access token (\`${cavelonCommand("login")}\`) and runs \`${cavelonCommand("secrets", verb, name)}\`, or does it in the Admin.`,
212
231
  details: { sent: false, credential: "api_key" },
213
232
  });
214
233
  }
234
+ function refusedForRole(error, verb, name) {
235
+ if (!(error instanceof CavelonError) || error.status !== 403 || error.code === "secret_needs_a_person")
236
+ return error;
237
+ const named = permissionsNamed(error.message);
238
+ if (!named.length && error.code !== "forbidden")
239
+ return error;
240
+ return secretsPermissionMissing(verb, name, named.length ? named : SECRETS_PERMISSIONS);
241
+ }
242
+ function variablesRefusedForRole(error, verb, name, value) {
243
+ if (!(error instanceof CavelonError) || error.status !== 403)
244
+ return error;
245
+ const named = permissionsNamed(error.message);
246
+ if (!named.length && error.code !== "forbidden")
247
+ return error;
248
+ return variablesPermissionMissing(verb, name, named.length ? named : SECRETS_PERMISSIONS, value);
249
+ }
215
250
  function withoutLineEnd(text) {
216
251
  if (text.endsWith("\r\n"))
217
252
  return text.slice(0, -2);
@@ -288,11 +323,26 @@ function secretView(status) {
288
323
  description: status.description ?? null,
289
324
  };
290
325
  }
326
+ const REQUIRED_SECRETS_SECTION = "required_secrets";
327
+ async function locallyDeclaredSecrets(session) {
328
+ const project = session.project;
329
+ if (!project)
330
+ return [];
331
+ const disk = await readPackage(project.root, project.layout).catch(() => undefined);
332
+ const declared = disk?.package[REQUIRED_SECRETS_SECTION];
333
+ if (!Array.isArray(declared))
334
+ return [];
335
+ const source = disk.sources[REQUIRED_SECRETS_SECTION];
336
+ const file = (Array.isArray(source) ? source[0]?.file : source?.file) ?? null;
337
+ const names = declared.map((d) => (d && typeof d === "object" ? d.name : d)).filter((n) => typeof n === "string" && n !== "");
338
+ return [...new Set(names)].map((name) => ({ name, file }));
339
+ }
291
340
  export const secretsList = {
292
341
  name: "secrets list",
293
342
  summary: "List the tenant's secret names ({{secret:…}}) with whether each is set; never a value.",
294
- description: "Lists every secret that has a value or that an imported package declared. A person sets a missing one with\n" +
295
- "`cavelon secrets set <name>`; an agent never sets or reads a secret value.",
343
+ description: "Lists every secret that has a value or that an imported package declared, and in a solution folder the ones its\n" +
344
+ "package declares that the tenant does not know yet. A person sets a missing one with `cavelon secrets set <name>`;\n" +
345
+ "an agent never sets or reads a secret value.",
296
346
  readOnly: true,
297
347
  idempotent: true,
298
348
  mcpTool: "secrets_list",
@@ -305,28 +355,41 @@ export const secretsList = {
305
355
  examples: ["cavelon secrets list", "cavelon secrets list --missing --json"],
306
356
  async run(ctx, input) {
307
357
  const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
308
- const flags = targetFlags(await ctx.session());
358
+ const session = await ctx.session();
309
359
  const all = ((await callStable(ctx, "GET", "/api/v1/secrets", "tenant secrets")).items ?? []).map(secretView);
360
+ const local = (await locallyDeclaredSecrets(session)).filter((d) => !all.some((s) => s.name === d.name));
310
361
  const wanted = boolOption(input, "missing") ? all.filter((s) => s.status !== "set") : all;
311
362
  const page = pageOf(wanted, limit, stringOption(input, "cursor"));
312
- const items = page.items.map((s) => (s.status === "set" ? s : { ...s, set_by_person: secretSetCommand(s.name, flags) }));
363
+ const items = page.items.map((s) => (s.status === "set" ? s : { ...s, set_by_person: secretSetCommand(s.name) }));
313
364
  const missing = all.filter((s) => s.status !== "set").length;
314
365
  const onlyMissing = boolOption(input, "missing");
315
- let text = onlyMissing ? "Every secret this tenant knows is set." : "This tenant has no secrets and no package declared one.";
366
+ let text = onlyMissing ? "Every secret this tenant knows is set." : "This tenant has no secrets, and no package applied to it declared one.";
316
367
  if (items.length) {
317
368
  const rows = items.map((s) => ({ ...s, declared: s.declared ? "yes" : "", changed_at: s.changed_at ?? "", description: s.description ?? "" }));
318
- const next = moreHint(page.next_cursor, `cavelon secrets list${onlyMissing ? " --missing" : ""}${flags}`);
319
- const howTo = missing ? `\n\n${missing} not set. A person sets each with: cavelon secrets set <name>${flags}` : "";
369
+ const next = moreHint(page.next_cursor, cavelonCommand("secrets", "list", ...(onlyMissing ? ["--missing"] : [])));
370
+ const howTo = missing ? `\n\n${missing} not set. A person sets each with: ${cavelonCommand("secrets", "set", fill("name"))}` : "";
320
371
  text = table(rows, ["name", "status", "declared", "changed_at", "description"], 50) + next + howTo;
321
372
  }
322
- return { data: { items, next_cursor: page.next_cursor, total: page.total, not_set: missing }, text };
373
+ if (local.length) {
374
+ const where = local[0].file ?? "this folder's package";
375
+ text +=
376
+ `\n\n${where} declares ${local.map((d) => d.name).join(", ")}, which the tenant does not know yet: it lists ` +
377
+ `${local.length === 1 ? "it" : "them"} once the package is applied (\`${cavelonCommand("apply")}\`). A person may set ${local.length === 1 ? "it" : "each"} before that: ` +
378
+ local.map((d) => secretSetCommand(d.name)).join("; ");
379
+ }
380
+ return {
381
+ data: { items, next_cursor: page.next_cursor, total: page.total, not_set: missing, ...(local.length ? { declared_locally: local } : {}) },
382
+ text,
383
+ };
323
384
  },
324
385
  };
325
386
  export const secretsSet = {
326
387
  name: "secrets set",
327
388
  summary: "Set a secret's value (a person runs this, never the agent).",
328
389
  description: "Asks for the value without echoing it, or reads it from standard input when that is piped (one trailing line break is\n" +
329
- "dropped). The value is never an argument, never printed and never read back. A tenant API key cannot set a secret.",
390
+ "dropped). The value is never an argument, never printed and never read back. A tenant API key cannot set a secret,\n" +
391
+ "nor can a role the instance does not allow to manage secrets (a Builder): its refusal then names who can, a tenant Owner.\n" +
392
+ "Run by a coding agent in its shell, it is refused before it reads a value (operation_for_a_person).",
330
393
  readOnly: false,
331
394
  idempotent: true,
332
395
  mcpTool: false,
@@ -336,6 +399,7 @@ export const secretsSet = {
336
399
  preprocess: refuseValueArgument,
337
400
  async run(ctx, input) {
338
401
  const name = positional(input, "name");
402
+ refuseForAgent(ctx, "Setting a secret's value", secretSetCommand(name));
339
403
  await requirePerson(ctx, "set", name);
340
404
  await checkName(ctx, "PUT", "/api/v1/secrets/{name}", "setting secrets", name);
341
405
  const value = await readSecretValue(ctx, name);
@@ -344,7 +408,7 @@ export const secretsSet = {
344
408
  status = await callStable(ctx, "PUT", "/api/v1/secrets/{name}", "setting secrets", { params: { name: [name] }, body: { value } });
345
409
  }
346
410
  catch (error) {
347
- throw withoutValue(error, value);
411
+ throw withoutValue(refusedForRole(error, "set", name), value);
348
412
  }
349
413
  const data = secretView(status);
350
414
  return { data, text: `Secret ${data.name} is set${changedNote(data.changed_at)}. Its value is never shown.` };
@@ -354,7 +418,8 @@ export const secretsDelete = {
354
418
  name: "secrets delete",
355
419
  summary: "Delete a secret's value (needs --confirm; a person runs this).",
356
420
  description: "Without --confirm, shows the secret's status and deletes nothing. A tool or prompt that names it fails until a person\n" +
357
- "sets it again. A tenant API key cannot delete a secret.",
421
+ "sets it again. A tenant API key cannot delete a secret. Run by a coding agent in its shell, it is refused, with or without\n" +
422
+ "--confirm (operation_for_a_person).",
358
423
  readOnly: false,
359
424
  destructive: true,
360
425
  idempotent: true,
@@ -364,18 +429,18 @@ export const secretsDelete = {
364
429
  examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm", "cavelon secrets delete old_token --confirm <token>"],
365
430
  async run(ctx, input) {
366
431
  const name = positional(input, "name");
432
+ refuseForAgent(ctx, "Deleting a secret's value", cavelonCommand("secrets", "delete", name));
367
433
  await requirePerson(ctx, "delete", name);
368
- const flags = targetFlags(await ctx.session());
369
434
  const current = secretView(await callStable(ctx, "GET", "/api/v1/secrets/{name}", "tenant secrets", { params: { name: [name] } }));
370
435
  const nothing = { data: { ...current, deleted: false }, text: `Secret ${name} has no value; nothing to delete.` };
371
436
  if (current.status !== "set")
372
437
  return nothing;
373
438
  const gate = await confirmation(ctx, input, "secrets_delete", { name, changed_at: current.changed_at ?? null });
374
439
  if (!gate.confirmed) {
375
- const confirm = gate.confirm(`cavelon secrets delete ${shellWord(name)}${flags} --confirm`);
440
+ const confirm = gate.confirm(cavelonCommand("secrets", "delete", name, "--confirm"));
376
441
  return {
377
442
  data: { ...current, deleted: false, confirm, ...gate.fields },
378
- text: `Secret ${name} is set${changedNote(current.changed_at)}.\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
443
+ text: `Secret ${name} is set${changedNote(current.changed_at)}.\n${gate.where}\n${gate.mismatch ? `${gate.mismatch}\n` : ""}Nothing was deleted. Delete it with: ${confirm}`,
379
444
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
380
445
  };
381
446
  }
@@ -385,11 +450,11 @@ export const secretsDelete = {
385
450
  catch (error) {
386
451
  if (notFound(error))
387
452
  return nothing;
388
- throw error;
453
+ throw refusedForRole(error, "delete", name);
389
454
  }
390
455
  return {
391
456
  data: { ...current, status: "not_set", deleted: true },
392
- text: `Deleted the value of secret ${name}. A person sets it again with: ${secretSetCommand(name, flags)}`,
457
+ text: `Deleted the value of secret ${name}. A person sets it again with: ${secretSetCommand(name)}`,
393
458
  };
394
459
  },
395
460
  };