@cavelon/cli 0.1.11 → 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.
@@ -1,13 +1,14 @@
1
1
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, pageOf, positional, stringOption, } from "../command.js";
2
2
  import { refuseForAgent } from "../agent-env.js";
3
- import { confirmation } from "../confirm-token.js";
3
+ import { confirmation, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
4
4
  import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
5
5
  import { clip, keyValues, moreHint, table } from "../format.js";
6
6
  import { callStable, workflowOperation } from "../invoke.js";
7
7
  import { readAll } from "../io.js";
8
8
  import { schemaErrors } from "../openapi.js";
9
9
  import { readPrincipal } from "../principal.js";
10
- import { permissionsNamed, SECRETS_PERMISSIONS, secretsPermissionMissing, variablesPermissionMissing } from "../secret-access.js";
10
+ import { principalOf } from "../access.js";
11
+ import { permissionsNamed, SECRETS_IN_ADMIN, SECRETS_PERMISSIONS, secretsInAdminOnly, secretsPermissionMissing, variablesPermissionMissing, } from "../secret-access.js";
11
12
  import { readHidden } from "../prompt.js";
12
13
  import { readPackage } from "../package-files.js";
13
14
  import { requireToken } from "../session.js";
@@ -23,6 +24,12 @@ const LIST_VALUE_CHARS = 200;
23
24
  export function secretSetCommand(name, env) {
24
25
  return printedCommand(["secrets", "set", name], { env });
25
26
  }
27
+ export function secretStep(name, inAdmin, env) {
28
+ return inAdmin ? `${SECRETS_IN_ADMIN} (${name})` : secretSetCommand(name, env);
29
+ }
30
+ export async function secretsSetInAdmin(ctx) {
31
+ return secretsInAdminOnly(await ctx.client().then(principalOf, () => undefined)) === true;
32
+ }
26
33
  export function variableSetCommand(name, env) {
27
34
  return printedCommand(["variables", "set", name, fill("value")], { env });
28
35
  }
@@ -114,7 +121,8 @@ export const variablesSet = {
114
121
  "use `cavelon secrets set` (a person runs it). --stdin reads the value from standard input instead of the argument.\n" +
115
122
  "A new variable is created at once. Replacing another value needs --confirm: without it nothing changes, and the preview\n" +
116
123
  "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.",
124
+ "the new value: show the preview to a person and confirm only with their yes.\n" +
125
+ PERSON_CONFIRMS_HELP,
118
126
  readOnly: false,
119
127
  idempotent: true,
120
128
  mcpTool: "variables_set",
@@ -144,14 +152,20 @@ export const variablesSet = {
144
152
  throw usageError("Missing <value>.", "Usage: cavelon variables set <name> <value> (or --stdin)");
145
153
  const value = argument ?? withoutLineEnd(await readAll(ctx.io.stdin));
146
154
  if (TOKEN_PREFIXES.some((prefix) => value.startsWith(prefix))) {
147
- throw usageError("That value looks like a key or token. A variable is plain text anyone with settings access reads; nothing was sent.", `Keep credentials in a secret, which a person sets: ${secretSetCommand(name)}. If this was a real token, revoke it.`);
155
+ throw usageError("That value looks like a key or token. A variable is plain text anyone with settings access reads; nothing was sent.", `Keep credentials in a secret, which a person sets: ${secretStep(name, await secretsSetInAdmin(ctx))}. If this was a real token, revoke it.`);
148
156
  }
149
157
  await checkName(ctx, "PUT", "/api/v1/variables/{name}", "setting tenant variables", name);
150
158
  const previous = await readVariable(ctx, name);
151
159
  if (previous && previous.value !== value) {
152
- const gate = await confirmation(ctx, input, "variables_set", { name, previous: previous.value, value });
160
+ const words = ["variables", "set", name, ...(fromStdin ? ["--stdin"] : [value]), "--confirm"];
161
+ const gate = await confirmation(ctx, input, "variables_set", { name, previous: previous.value, value }, {
162
+ person: {
163
+ what: `Replace the tenant variable ${name}, which every solution of the tenant reads: ${JSON.stringify(clip(previous.value, LIST_VALUE_CHARS))} → ${JSON.stringify(clip(value, LIST_VALUE_CHARS))}.`,
164
+ words,
165
+ },
166
+ });
153
167
  if (!gate.confirmed) {
154
- const confirm = gate.confirm(cavelonCommand("variables", "set", name, ...(fromStdin ? ["--stdin"] : [value]), "--confirm"));
168
+ const confirm = gate.confirm(cavelonCommand(...words));
155
169
  return {
156
170
  data: { name, changed: false, created: false, would: "replace", previous: previous.value, value, confirm, ...gate.fields },
157
171
  text: [
@@ -189,15 +203,18 @@ export const variablesDelete = {
189
203
  mcpTool: false,
190
204
  positionals: [{ name: "name", description: "The variable's name.", required: true }],
191
205
  options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
192
- examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm", "cavelon variables delete old_url --confirm <token>"],
206
+ examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm"],
193
207
  async run(ctx, input) {
194
208
  const name = positional(input, "name");
195
209
  const current = await readVariable(ctx, name);
196
210
  if (!current)
197
211
  return { data: { name, deleted: false, existed: false }, text: `This tenant has no variable "${name}"; nothing to delete.` };
198
- const gate = await confirmation(ctx, input, "variables_delete", { name, value: current.value });
212
+ const words = ["variables", "delete", name, "--confirm"];
213
+ const gate = await confirmation(ctx, input, "variables_delete", { name, value: current.value }, {
214
+ person: { what: `Delete the tenant variable ${name}; a prompt or tool that names it gets no value afterwards.`, words },
215
+ });
199
216
  if (!gate.confirmed) {
200
- const confirm = gate.confirm(cavelonCommand("variables", "delete", name, "--confirm"));
217
+ const confirm = gate.confirm(cavelonCommand(...words));
201
218
  return {
202
219
  data: { name, deleted: false, existed: true, value: current.value, confirm, ...gate.fields },
203
220
  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}`,
@@ -215,6 +232,19 @@ export const variablesDelete = {
215
232
  return { data: { name, deleted: true, existed: true, value: current.value }, text: `Deleted variable ${name}.` };
216
233
  },
217
234
  };
235
+ async function refuseWhereAdminOnly(ctx, verb, name) {
236
+ const principal = await ctx.client().then(principalOf, () => undefined);
237
+ const inAdmin = Array.isArray(principal?.needs_a_person);
238
+ if (secretsInAdminOnly(principal, verb === "set" ? "PUT" : "DELETE") !== true)
239
+ return { inAdmin };
240
+ const credential = principal.kind === "api_key" ? "A tenant API key" : "A personal access token";
241
+ throw new CavelonError(ExitCode.needsAction, {
242
+ code: "secret_needs_a_person",
243
+ message: `${credential} cannot ${verb} a secret on this instance, so nothing was sent: only a person signed in to the Admin ${verb === "set" ? "sets" : "deletes"} a secret's value.`,
244
+ hint: `A person ${verb === "set" ? "sets" : "deletes"} ${name} ${SECRETS_IN_ADMIN}.`,
245
+ details: { sent: false, credential: principal.kind },
246
+ });
247
+ }
218
248
  async function requirePerson(ctx, verb, name) {
219
249
  const session = await ctx.session();
220
250
  requireToken(session);
@@ -231,13 +261,13 @@ async function requirePerson(ctx, verb, name) {
231
261
  details: { sent: false, credential: "api_key" },
232
262
  });
233
263
  }
234
- function refusedForRole(error, verb, name) {
264
+ function refusedForRole(error, verb, name, inAdmin) {
235
265
  if (!(error instanceof CavelonError) || error.status !== 403 || error.code === "secret_needs_a_person")
236
266
  return error;
237
267
  const named = permissionsNamed(error.message);
238
268
  if (!named.length && error.code !== "forbidden")
239
269
  return error;
240
- return secretsPermissionMissing(verb, name, named.length ? named : SECRETS_PERMISSIONS);
270
+ return secretsPermissionMissing(verb, name, named.length ? named : SECRETS_PERMISSIONS, inAdmin);
241
271
  }
242
272
  function variablesRefusedForRole(error, verb, name, value) {
243
273
  if (!(error instanceof CavelonError) || error.status !== 403)
@@ -341,8 +371,8 @@ export const secretsList = {
341
371
  name: "secrets list",
342
372
  summary: "List the tenant's secret names ({{secret:…}}) with whether each is set; never a value.",
343
373
  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.",
374
+ "package declares that the tenant does not know yet. A person sets a missing one with `cavelon secrets set <name>`, or\n" +
375
+ "in the Admin under Settings › Secrets where the instance lets no token set one; an agent never sets or reads a secret value.",
346
376
  readOnly: true,
347
377
  idempotent: true,
348
378
  mcpTool: "secrets_list",
@@ -360,14 +390,19 @@ export const secretsList = {
360
390
  const local = (await locallyDeclaredSecrets(session)).filter((d) => !all.some((s) => s.name === d.name));
361
391
  const wanted = boolOption(input, "missing") ? all.filter((s) => s.status !== "set") : all;
362
392
  const page = pageOf(wanted, limit, stringOption(input, "cursor"));
363
- const items = page.items.map((s) => (s.status === "set" ? s : { ...s, set_by_person: secretSetCommand(s.name) }));
393
+ const inAdmin = await secretsSetInAdmin(ctx);
394
+ const items = page.items.map((s) => (s.status === "set" ? s : { ...s, set_by_person: secretStep(s.name, inAdmin) }));
364
395
  const missing = all.filter((s) => s.status !== "set").length;
365
396
  const onlyMissing = boolOption(input, "missing");
366
397
  let text = onlyMissing ? "Every secret this tenant knows is set." : "This tenant has no secrets, and no package applied to it declared one.";
367
398
  if (items.length) {
368
399
  const rows = items.map((s) => ({ ...s, declared: s.declared ? "yes" : "", changed_at: s.changed_at ?? "", description: s.description ?? "" }));
369
400
  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"))}` : "";
401
+ const howTo = !missing
402
+ ? ""
403
+ : inAdmin
404
+ ? `\n\n${missing} not set. A person sets each, signed in to the Admin under Settings › Secrets.`
405
+ : `\n\n${missing} not set. A person sets each with: ${cavelonCommand("secrets", "set", fill("name"))}`;
371
406
  text = table(rows, ["name", "status", "declared", "changed_at", "description"], 50) + next + howTo;
372
407
  }
373
408
  if (local.length) {
@@ -375,7 +410,7 @@ export const secretsList = {
375
410
  text +=
376
411
  `\n\n${where} declares ${local.map((d) => d.name).join(", ")}, which the tenant does not know yet: it lists ` +
377
412
  `${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("; ");
413
+ local.map((d) => secretStep(d.name, inAdmin)).join("; ");
379
414
  }
380
415
  return {
381
416
  data: { items, next_cursor: page.next_cursor, total: page.total, not_set: missing, ...(local.length ? { declared_locally: local } : {}) },
@@ -389,6 +424,8 @@ export const secretsSet = {
389
424
  description: "Asks for the value without echoing it, or reads it from standard input when that is piped (one trailing line break is\n" +
390
425
  "dropped). The value is never an argument, never printed and never read back. A tenant API key cannot set a secret,\n" +
391
426
  "nor can a role the instance does not allow to manage secrets (a Builder): its refusal then names who can, a tenant Owner.\n" +
427
+ "An instance that lets only a person signed in to the Admin set a secret (its /meta/principal lists the operation in\n" +
428
+ "needs_a_person) refuses every token; there it is refused before it reads a value, naming the Admin page.\n" +
392
429
  "Run by a coding agent in its shell, it is refused before it reads a value (operation_for_a_person).",
393
430
  readOnly: false,
394
431
  idempotent: true,
@@ -399,6 +436,7 @@ export const secretsSet = {
399
436
  preprocess: refuseValueArgument,
400
437
  async run(ctx, input) {
401
438
  const name = positional(input, "name");
439
+ const { inAdmin } = await refuseWhereAdminOnly(ctx, "set", name);
402
440
  refuseForAgent(ctx, "Setting a secret's value", secretSetCommand(name));
403
441
  await requirePerson(ctx, "set", name);
404
442
  await checkName(ctx, "PUT", "/api/v1/secrets/{name}", "setting secrets", name);
@@ -408,7 +446,7 @@ export const secretsSet = {
408
446
  status = await callStable(ctx, "PUT", "/api/v1/secrets/{name}", "setting secrets", { params: { name: [name] }, body: { value } });
409
447
  }
410
448
  catch (error) {
411
- throw withoutValue(refusedForRole(error, "set", name), value);
449
+ throw withoutValue(refusedForRole(error, "set", name, inAdmin), value);
412
450
  }
413
451
  const data = secretView(status);
414
452
  return { data, text: `Secret ${data.name} is set${changedNote(data.changed_at)}. Its value is never shown.` };
@@ -418,7 +456,8 @@ export const secretsDelete = {
418
456
  name: "secrets delete",
419
457
  summary: "Delete a secret's value (needs --confirm; a person runs this).",
420
458
  description: "Without --confirm, shows the secret's status and deletes nothing. A tool or prompt that names it fails until a person\n" +
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" +
459
+ "sets it again. A tenant API key cannot delete a secret, nor can any token on an instance that lets only a person signed\n" +
460
+ "in to the Admin do it (secret_needs_a_person). Run by a coding agent in its shell, it is refused, with or without\n" +
422
461
  "--confirm (operation_for_a_person).",
423
462
  readOnly: false,
424
463
  destructive: true,
@@ -429,6 +468,7 @@ export const secretsDelete = {
429
468
  examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm", "cavelon secrets delete old_token --confirm <token>"],
430
469
  async run(ctx, input) {
431
470
  const name = positional(input, "name");
471
+ const { inAdmin } = await refuseWhereAdminOnly(ctx, "delete", name);
432
472
  refuseForAgent(ctx, "Deleting a secret's value", cavelonCommand("secrets", "delete", name));
433
473
  await requirePerson(ctx, "delete", name);
434
474
  const current = secretView(await callStable(ctx, "GET", "/api/v1/secrets/{name}", "tenant secrets", { params: { name: [name] } }));
@@ -450,7 +490,7 @@ export const secretsDelete = {
450
490
  catch (error) {
451
491
  if (notFound(error))
452
492
  return nothing;
453
- throw refusedForRole(error, "delete", name);
493
+ throw refusedForRole(error, "delete", name, inAdmin);
454
494
  }
455
495
  return {
456
496
  data: { ...current, status: "not_set", deleted: true },
@@ -3,7 +3,7 @@ import { actingTarget, targetLine } from "./acting.js";
3
3
  import { drivenByAgent } from "./agent-env.js";
4
4
  import { CavelonError, ExitCode } from "./errors.js";
5
5
  import { canonical } from "./package-files.js";
6
- import { PREVIEW_TOKEN } from "./printed.js";
6
+ import { personCommand, PREVIEW_TOKEN } from "./printed.js";
7
7
  export const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
8
8
  export function confirmToken(target, tool, change) {
9
9
  return createHash("sha256")
@@ -24,23 +24,60 @@ export function withToken(printed, token) {
24
24
  return `${command.slice(0, at)} --confirm ${token}${command.slice(at + " --confirm".length)}`;
25
25
  return `${command} --confirm ${token}`;
26
26
  }
27
+ export const PERSON_CONFIRMS_HELP = "A coding agent cannot confirm it: over MCP the client asks the person, and from an agent's shell the person runs the\n" +
28
+ "confirm in their own terminal.";
27
29
  export async function confirmation(ctx, input, tool, change, options = {}) {
28
- const gate = await gateOf(ctx, input, tool, change);
30
+ const gate = await gateOf(ctx, input, tool, change, options);
29
31
  if (gate.confirmed)
30
32
  return { ...gate, where: "" };
31
33
  const target = await actingTarget(ctx, options);
32
34
  return { ...gate, fields: { target, ...gate.fields }, where: targetLine(target) };
33
35
  }
34
- async function gateOf(ctx, input, tool, change) {
36
+ async function gateOf(ctx, input, tool, change, options) {
35
37
  const given = input.options.confirm;
36
38
  const driven = drivenByAgent(ctx);
37
39
  const tokenGiven = typeof given === "string" && given !== "";
38
- if (!driven && !tokenGiven)
40
+ const approve = () => {
41
+ if (!driven)
42
+ ctx.approved = { guarded: Boolean(options.person) };
43
+ };
44
+ if (!driven && !tokenGiven) {
45
+ if (given === true)
46
+ approve();
39
47
  return { confirmed: given === true, fields: {}, confirm: (command) => command };
48
+ }
40
49
  if (driven?.by === "mcp" && given === true)
41
50
  throw confirmTokenRequired(tool);
42
51
  const session = await ctx.session();
43
52
  const token = confirmToken({ url: session.url, tenant: session.tenant }, tool, change);
53
+ const person = driven && options.person ? { ...options.person, route: personRoute(ctx, driven) } : undefined;
54
+ if (person) {
55
+ const command = personCommand(...person.words);
56
+ const confirm = () => (person.route === "client" ? confirmThroughClient(tool, token) : confirmInTerminal(command));
57
+ const fields = { ...(person.route === "client" ? { confirm_token: token } : {}), needs_person: person.route };
58
+ if (given === true || given === "") {
59
+ return {
60
+ confirmed: false,
61
+ fields,
62
+ confirm,
63
+ mismatch: "A coding agent cannot confirm this change; nothing was changed: the person confirms it in their own terminal.",
64
+ exitCode: ExitCode.needsAction,
65
+ };
66
+ }
67
+ if (!tokenGiven)
68
+ return { confirmed: false, fields, confirm };
69
+ if (given === token) {
70
+ await personApproves(ctx, driven, { tool, what: person.what, command }, options);
71
+ return { confirmed: true, fields: {}, confirm };
72
+ }
73
+ return {
74
+ confirmed: false,
75
+ fields: { ...fields, token_mismatch: true },
76
+ confirm,
77
+ mismatch: "The confirm token is not this change's: the change differs from its preview, or the token is another one's. Nothing was changed.",
78
+ exitCode: ExitCode.conflict,
79
+ };
80
+ }
44
81
  const confirm = (command) => (driven?.by === "mcp" ? confirmWith(tool, token) : driven ? withToken(command, token) : command);
45
82
  if (given === true && driven?.by === "agent") {
46
83
  return {
@@ -53,8 +90,10 @@ async function gateOf(ctx, input, tool, change) {
53
90
  }
54
91
  if (!tokenGiven)
55
92
  return { confirmed: false, fields: { confirm_token: token }, confirm };
56
- if (given === token)
93
+ if (given === token) {
94
+ approve();
57
95
  return { confirmed: true, fields: {}, confirm };
96
+ }
58
97
  return {
59
98
  confirmed: false,
60
99
  fields: { confirm_token: token, token_mismatch: true },
@@ -63,6 +102,42 @@ async function gateOf(ctx, input, tool, change) {
63
102
  exitCode: ExitCode.conflict,
64
103
  };
65
104
  }
105
+ export function personRoute(ctx, driven) {
106
+ return driven.by === "mcp" && ctx.askPerson ? "client" : "terminal";
107
+ }
108
+ export const PERSON_WAIT_MS = 10 * 60_000;
109
+ export async function personApproves(ctx, driven, change, target = {}) {
110
+ if (personRoute(ctx, driven) === "terminal")
111
+ throw needsPerson(change.command);
112
+ const where = targetLine(await actingTarget(ctx, target));
113
+ const answer = await ctx.askPerson([change.what, where, `A coding agent asks to make this change through cavelon (${change.tool}). Approve only this exact change.`].filter(Boolean).join("\n"));
114
+ if (answer === "approved") {
115
+ ctx.approved = { guarded: change.guarded ?? true };
116
+ return;
117
+ }
118
+ throw new CavelonError(ExitCode.needsAction, {
119
+ code: "confirm_declined",
120
+ message: answer === "declined"
121
+ ? "The person did not approve the change; nothing was changed."
122
+ : `The person did not answer within ${PERSON_WAIT_MS / 60_000} minutes, or the client could not ask; nothing was changed.`,
123
+ hint: `Ask the person whether they want it. With their yes, call ${change.tool} again with the same confirm token, or they run ${change.command} in their own terminal.`,
124
+ details: { answer, person_command: change.command },
125
+ });
126
+ }
127
+ export function needsPerson(command) {
128
+ return new CavelonError(ExitCode.needsAction, {
129
+ code: "confirm_needs_person",
130
+ message: `A coding agent cannot confirm this change; nothing was changed. The person confirms it in their own terminal: ${command}`,
131
+ hint: "Show the person the preview and the command; they run it themselves, outside the agent.",
132
+ details: { person_command: command },
133
+ });
134
+ }
135
+ export function confirmThroughClient(tool, token) {
136
+ return `Show the person this, then call ${tool} again with the same arguments and confirm: "${token}": the client then asks the person to approve exactly this change, and nothing changes without their yes.`;
137
+ }
138
+ export function confirmInTerminal(command) {
139
+ return `${command} (the person runs it in their own terminal: a coding agent cannot confirm this change)`;
140
+ }
66
141
  export function shellTokenRequired(command) {
67
142
  return new CavelonError(ExitCode.needsAction, {
68
143
  code: "confirm_token_required",
package/dist/context.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { checkKeyTenant } from "./acting.js";
2
2
  import { Contracts } from "./contracts.js";
3
+ import { changeConfirmer } from "./change-confirmation.js";
3
4
  import { ApiClient } from "./http.js";
4
5
  import { colorEnabled, styleFor } from "./io.js";
5
6
  import { requireInstance, requireToken, resolveSession, resolveTenantId } from "./session.js";
@@ -33,6 +34,7 @@ export function createContext(io, globals, mode = "cli") {
33
34
  clientPromise ??= (async () => {
34
35
  const session = await ctx.session();
35
36
  const client = new ApiClient({ url: requireInstance(session), token: requireToken(session) }, io.env);
37
+ client.confirmer = changeConfirmer(ctx, client);
36
38
  client.target.tenantId =
37
39
  session.tokenKind === "api_key" ? await checkKeyTenant(client, session, (m) => ctx.warn(m)) : await resolveTenantId(io.env, session, client, io.now());
38
40
  return client;
package/dist/http.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { accessFor, forbiddenHint } from "./access.js";
2
2
  import { capacityCodeIn, capacityHint } from "./capacity.js";
3
+ import { CONFIRMATION_REQUIRED, confirmationRefused } from "./change-confirmation.js";
3
4
  import { ceilingRefusal, LIMIT_ABOVE_CEILING } from "./limits.js";
4
5
  import { CavelonError, ExitCode } from "./errors.js";
5
6
  import { blockerDetails } from "./preview-report.js";
@@ -30,6 +31,7 @@ export class ApiClient {
30
31
  env;
31
32
  tokensOff;
32
33
  revalidateTenant;
34
+ confirmer;
33
35
  constructor(target, env = {}) {
34
36
  this.target = target;
35
37
  this.env = env;
@@ -100,10 +102,12 @@ export class ApiClient {
100
102
  }
101
103
  }
102
104
  async request(method, path, options = {}) {
105
+ const { change, confirmed } = await this.confirmationBefore(method, path, options);
106
+ const sentHeaders = confirmed ? { ...options.headers, ...confirmed } : options.headers;
103
107
  const timeoutMs = options.timeoutMs ?? (Number(this.env.CAVELON_HTTP_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS);
104
108
  const timeout = AbortSignal.timeout(timeoutMs);
105
109
  const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
106
- const response = await this.fetchRaw(method, path, { ...options, signal });
110
+ const response = await this.fetchRaw(method, path, { ...options, headers: sentHeaders, signal });
107
111
  let text;
108
112
  try {
109
113
  text = await response.text();
@@ -122,13 +126,27 @@ export class ApiClient {
122
126
  if (!response.ok && !options.allow?.includes(response.status)) {
123
127
  if (await this.tenantMoved(method, path, response.status, options))
124
128
  return this.request(method, path, options);
129
+ const late = await this.confirmationAsked(response.status, data, change, confirmed);
130
+ if (late)
131
+ return this.request(method, path, { ...options, headers: { ...options.headers, ...late }, confirmation: false });
125
132
  const tenantless = options.sendTenant !== false && !this.headers(options)["X-Tenant-Id"] && Boolean(this.target.token?.startsWith("cvpat_"));
126
133
  const pathname = new URL(response.url || this.resolve(path)).pathname;
127
134
  const platform = options.sendTenant === false || isPlatformRoute(pathname);
128
- throw await this.refusal(response.status, data, `${method} ${pathname}`, response.headers, { tenantless, platform, method, path: pathname });
135
+ const error = await this.refusal(response.status, data, `${method} ${pathname}`, response.headers, { tenantless, platform, method, path: pathname });
136
+ throw confirmationRefused(error, Boolean(confirmed) || options.confirmation === false);
129
137
  }
130
138
  return { status: response.status, headers: response.headers, data: data, text };
131
139
  }
140
+ async confirmationBefore(method, path, options) {
141
+ if (!this.confirmer || options.confirmation === false || method === "GET" || method === "HEAD" || options.form || options.bytes)
142
+ return {};
143
+ const change = { method, path, query: options.query, body: options.json };
144
+ return { change, confirmed: await this.confirmer(change) };
145
+ }
146
+ async confirmationAsked(status, data, change, confirmed) {
147
+ const asked = status === 428 && change && !confirmed ? askedFor(data) : undefined;
148
+ return asked ? this.confirmer(change, asked) : undefined;
149
+ }
132
150
  async tenantMoved(method, path, status, options = {}) {
133
151
  const sentTenant = this.headers(options)["X-Tenant-Id"];
134
152
  if ((status !== 403 && status !== 404) || !sentTenant || !this.revalidateTenant)
@@ -178,6 +196,13 @@ export class ApiClient {
178
196
  return this.request("GET", path, options);
179
197
  }
180
198
  }
199
+ function askedFor(data) {
200
+ if (!data || typeof data !== "object" || Array.isArray(data))
201
+ return undefined;
202
+ const body = data;
203
+ const inner = body.detail && typeof body.detail === "object" && !Array.isArray(body.detail) ? body.detail : {};
204
+ return body.code === CONFIRMATION_REQUIRED || inner.code === CONFIRMATION_REQUIRED ? { ...inner, ...body } : undefined;
205
+ }
181
206
  function parseBody(text, contentType) {
182
207
  if (!text)
183
208
  return null;
@@ -309,6 +334,9 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
309
334
  }
310
335
  if (changed)
311
336
  details = details && typeof details === "object" && !Array.isArray(details) ? { ...details, changed } : { changed };
337
+ const reason = status === 428 && body && typeof body === "object" ? body.reason : undefined;
338
+ if (typeof reason === "string")
339
+ details = details && typeof details === "object" && !Array.isArray(details) ? { ...details, reason } : { reason };
312
340
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
313
341
  hint = `Choose a tenant with \`${cavelonCommand("use")}\` (it lists your tenants), --tenant or CAVELON_TENANT.`;
314
342
  }
@@ -348,6 +376,8 @@ export function exitCodeForStatus(status) {
348
376
  return ExitCode.validation;
349
377
  if (status === 409 || status === 412)
350
378
  return ExitCode.conflict;
379
+ if (status === 428)
380
+ return ExitCode.needsAction;
351
381
  if (status === 408 || status === 429 || status >= 500)
352
382
  return ExitCode.server;
353
383
  return ExitCode.failure;
@@ -366,6 +396,8 @@ function defaultCode(status) {
366
396
  return "conflict";
367
397
  case 412:
368
398
  return "precondition_failed";
399
+ case 428:
400
+ return "precondition_required";
369
401
  case 422:
370
402
  return "validation_failed";
371
403
  case 429:
package/dist/install.js CHANGED
@@ -6,11 +6,16 @@ export const REPOSITORY = "goodguys-gmbh/cavelon-dev-kit";
6
6
  export const NPM_PACKAGE = "@cavelon/cli";
7
7
  const WINGET_ID = "goodguys.Cavelon";
8
8
  const RELEASES = `https://github.com/${REPOSITORY}/releases/latest`;
9
+ export const PYPI_MARKER = ["share", "cavelon", "pypi"];
9
10
  const LABELS = {
10
11
  script: "the install script",
11
12
  executable: "a downloaded executable",
12
13
  homebrew: "Homebrew",
13
14
  winget: "winget",
15
+ "uv-tool": "uv tool install",
16
+ pipx: "pipx",
17
+ uvx: "uvx",
18
+ pip: "pip",
14
19
  npm: "npm i -g",
15
20
  npx: "npx",
16
21
  package: "a package manager",
@@ -32,6 +37,9 @@ export function detectInstall(facts) {
32
37
  if (platform === "win32" && packages > 0 && lower[packages - 1] === "winget" && lower[packages + 1]?.startsWith(`${WINGET_ID.toLowerCase()}_`)) {
33
38
  return { method: "winget", path: file, update: `winget upgrade ${WINGET_ID}`, source: "github" };
34
39
  }
40
+ const pypi = pypiInstall(facts, p, lower);
41
+ if (pypi)
42
+ return pypi;
35
43
  const name = p.basename(file).toLowerCase();
36
44
  if (name !== (platform === "win32" ? "cavelon.exe" : "cavelon")) {
37
45
  return { method: "executable", path: file, advice: `Download the new one from ${RELEASES}.`, source: "github" };
@@ -54,6 +62,28 @@ export function detectInstall(facts) {
54
62
  return { method: "npm", path: file, update: `npm i -g ${NPM_PACKAGE}`, source: "npm" };
55
63
  return { method: "package", path: file, advice: `Update ${NPM_PACKAGE} with the package manager that installed it.`, source: "npm" };
56
64
  }
65
+ function pypiInstall(facts, p, lower) {
66
+ const prefix = p.dirname(p.dirname(facts.file));
67
+ const roots = facts.platform === "win32" ? [prefix, p.dirname(prefix)] : [prefix];
68
+ if (!roots.some((root) => facts.exists(p.join(root, ...PYPI_MARKER))))
69
+ return undefined;
70
+ const file = facts.file;
71
+ const follows = (a, b) => lower.some((s, i) => s === a && lower[i + 1] === b);
72
+ const under = (dir) => {
73
+ if (!dir)
74
+ return false;
75
+ const fold = (v) => (facts.platform === "win32" ? v.toLowerCase() : v);
76
+ return fold(file).startsWith(fold(p.join(dir, p.sep)));
77
+ };
78
+ if (follows("uv", "tools") || under(facts.env.UV_TOOL_DIR))
79
+ return { method: "uv-tool", path: file, update: "uv tool upgrade cavelon", source: "github" };
80
+ if (follows("pipx", "venvs") || under(facts.env.PIPX_HOME))
81
+ return { method: "pipx", path: file, update: "pipx upgrade cavelon", source: "github" };
82
+ if (lower.includes("uv") && lower.some((s) => s.startsWith("archive-v"))) {
83
+ return { method: "uvx", path: file, advice: "uvx reuses the release it cached; `uvx cavelon@latest` runs the newest.", source: "github" };
84
+ }
85
+ return { method: "pip", path: file, update: "pip install --upgrade cavelon", source: "github" };
86
+ }
57
87
  function scriptUpdate(facts, dir) {
58
88
  const { env } = facts;
59
89
  if (facts.platform === "win32") {
package/dist/invoke.js CHANGED
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { CavelonError, ExitCode, validationError } from "./errors.js";
4
4
  import { bodyBytes, isPlatformRoute } from "./http.js";
5
5
  import { coerceParameter, isArrayParameter, operationAt, validateBody } from "./openapi.js";
6
+ import { confirmationRefused } from "./change-confirmation.js";
6
7
  import { cavelonCommand } from "./printed.js";
7
8
  export async function openapiOrWarn(ctx) {
8
9
  try {
@@ -92,8 +93,9 @@ export async function callOperation(ctx, client, doc, op, args) {
92
93
  validateBody(doc, op, args.body);
93
94
  json = args.body;
94
95
  }
96
+ const { change, confirmed } = await client.confirmationBefore(op.method, target, { query, json, form, confirmation: args.confirmation });
95
97
  const signal = AbortSignal.timeout(args.timeoutMs ?? (Number(ctx.io.env.CAVELON_HTTP_TIMEOUT_MS) || 30_000));
96
- const response = await client.fetchRaw(op.method, target, { query, headers, json, form, sendTenant: args.sendTenant, signal });
98
+ const response = await client.fetchRaw(op.method, target, { query, headers: { ...headers, ...confirmed }, json, form, sendTenant: args.sendTenant, signal });
97
99
  const contentType = response.headers.get("content-type") ?? "";
98
100
  const bytes = await bodyBytes(response, client.resolve(target), signal);
99
101
  const isText = /json|text|xml|yaml|markdown|event-stream/.test(contentType) || bytes.length === 0;
@@ -110,12 +112,16 @@ export async function callOperation(ctx, client, doc, op, args) {
110
112
  if (!response.ok) {
111
113
  if (await client.tenantMoved(op.method, target, response.status, { sendTenant: args.sendTenant }))
112
114
  return callOperation(ctx, client, doc, op, args);
115
+ const late = await client.confirmationAsked(response.status, data, change, confirmed);
116
+ if (late)
117
+ return callOperation(ctx, client, doc, op, { ...args, headers: { ...args.headers, ...late }, confirmation: false });
113
118
  const pathname = new URL(client.resolve(target)).pathname;
114
- throw await client.refusal(response.status, data, `${op.method} ${pathname}`, response.headers, {
119
+ const error = await client.refusal(response.status, data, `${op.method} ${pathname}`, response.headers, {
115
120
  platform: args.sendTenant === false || isPlatformRoute(pathname),
116
121
  method: op.method,
117
122
  path: pathname,
118
123
  });
124
+ throw confirmationRefused(error, Boolean(confirmed) || args.confirmation === false);
119
125
  }
120
126
  return { status: response.status, contentType, data: isText ? (text ? data : null) : undefined, bytes: isText ? undefined : bytes };
121
127
  }
package/dist/kit-codes.js CHANGED
@@ -15,7 +15,7 @@ export const KIT_ERROR_CODES = [
15
15
  { code: "platform_role_required", area: "cli", message: "The change is an operator's: it needs a personal access token in Platform mode of a platform role; nothing was sent.", hint: "Ask the instance's operator, or run it with an operator's token." },
16
16
  { code: "forbidden", area: "cli", message: "The credential may not make this change; nothing was sent.", hint: "The message names the permission; a person with it makes the change, or in the Admin." },
17
17
  { code: "token_activation_refused", area: "cli", message: "The personal access token was not created with \"may activate\", so it cannot activate solutions.", hint: "A person activates the solution in the Admin, or creates a token with \"may activate\"." },
18
- { code: "secret_needs_a_person", area: "cli", message: "A tenant API key cannot set or delete a secret; nothing was sent.", hint: "A person logs in with a personal access token and runs `cavelon secrets set <name>`, or uses the Admin." },
18
+ { code: "secret_needs_a_person", area: "cli", message: "This credential cannot set or delete a secret here; nothing was sent. A tenant API key never can, and an instance that lets only a person signed in to the Admin do it refuses every token.", hint: "A person sets it in the Admin under Settings › Secrets; on an instance that still takes a personal access token there, also with `cavelon secrets set <name>` in their own terminal." },
19
19
  { code: "foreign_url", area: "cli", message: "cavelon refused to send the token to a URL outside the instance.", hint: "Check the instance URL; the token goes only to the instance it was stored for." },
20
20
  { code: "network_error", area: "cli", message: "The instance could not be reached.", hint: "Check the instance URL and the network (VPN, proxy, allowlist)." },
21
21
  { code: "request_timeout", area: "cli", message: "The instance did not answer in time.", hint: "Retry; CAVELON_HTTP_TIMEOUT_MS raises the limit per request." },
@@ -31,7 +31,7 @@ export const KIT_ERROR_CODES = [
31
31
  { code: "operation_ambiguous", area: "cli", message: "The short name matches several operations.", hint: "Use the full operationId the message lists." },
32
32
  { code: "operation_for_a_person", area: "cli", message: "The operation stays with a person (the instance marks it, or it changes a secret, a credential or an approval), so an agent does not send it.", hint: "A person runs it in their own terminal, or in the Admin." },
33
33
  { code: "secret_field_for_a_person", area: "cli", message: "The request sets a field the instance marks as a secret value, so an agent does not send it.", hint: "Leave the field out; a person enters the value with `cavelon secrets set <name>` or in the Admin." },
34
- { code: "confirmation_required", area: "cli", message: "The command changes something and there is no terminal to ask.", hint: "Read the plan it printed, then run it again with --yes." },
34
+ { code: "yes_required", area: "cli", message: "setup changes something and there is no terminal to ask.", hint: "Read the plan it printed, then run it again with --yes." },
35
35
  { code: "operations_unavailable", area: "cli", message: "The instance does not offer the operations API.", hint: "Its operator turns it on with OPERATIONS_API_ENABLED." },
36
36
  { code: "not_an_operation_id", area: "cli", message: "That is not an operation id; they start with op_.", hint: "Commands that start work print the operation id; `cavelon status` lists running ones." },
37
37
  { code: "operation_gone", area: "cli", message: "The operation no longer exists on the instance.", hint: "Start the work again; `cavelon status` lists the running operations." },
@@ -62,6 +62,8 @@ export const KIT_ERROR_CODES = [
62
62
  { code: "preview_discarded", area: "cli", message: "The preview was discarded (apply --discard); nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
63
63
  { code: "preview_expired", area: "cli", message: "The preview is older than the kit keeps previews; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
64
64
  { code: "confirm_token_required", area: "cli", message: "Over MCP, or run by a coding agent in its shell, a changing command confirms only with the token its preview returned, never with true or a bare --confirm.", hint: "Call the tool (or run the command) without confirm, show the person the preview, then call it again with the same arguments and confirm set to its confirm_token (--confirm <token> in a shell)." },
65
+ { code: "confirm_needs_person", area: "cli", message: "A coding agent cannot confirm this change, even with its preview's token: it reaches live traffic or the whole tenant, or cannot be taken back, and the agent's MCP client cannot ask the person (or the agent runs cavelon in its shell). Nothing was changed.", hint: "Show the person the preview; they run the command the refusal names in their own terminal, outside the agent." },
66
+ { code: "confirm_declined", area: "cli", message: "The MCP client asked the person to approve the change, and they declined or did not answer in time. Nothing was changed.", hint: "Ask the person whether they want the change; with their yes, confirm again with the same token, or they run the command in their own terminal." },
65
67
  { code: "token_mismatch", area: "cli", message: "The confirm token is not the one for this change: it belongs to another preview, or the change differs from what its preview showed; nothing was changed (exit code 4).", hint: "Show the person the new preview this answer carries, and confirm only with its confirm_token after their yes; a token confirms exactly the change its preview showed." },
66
68
  { code: "unknown_argument", area: "cli", message: "An MCP tool was called with an argument its schema does not list; nothing was done.", hint: "Call it again with the argument the error names (the tool's schema lists them all), spelled in snake_case." },
67
69
  { code: "solution_not_active", area: "cli", message: "Only an active solution can be the tenant's default route; this one is not (a draft, or inactive after a deactivate), so nothing was changed.", hint: "Activate it through the readiness gate and preview the default route in one step: `cavelon activate --harness <slug> --make-default`." },