@cavelon/cli 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +34 -15
  2. package/dist/access.js +194 -0
  3. package/dist/acting.js +123 -0
  4. package/dist/agent-env.js +20 -2
  5. package/dist/change-confirmation.js +93 -0
  6. package/dist/commands/api.js +77 -30
  7. package/dist/commands/chat.js +16 -8
  8. package/dist/commands/db.js +474 -0
  9. package/dist/commands/docs.js +83 -7
  10. package/dist/commands/index.js +7 -0
  11. package/dist/commands/limits-set.js +11 -5
  12. package/dist/commands/loops.js +72 -9
  13. package/dist/commands/models.js +12 -6
  14. package/dist/commands/sandboxes.js +7 -2
  15. package/dist/commands/session.js +111 -24
  16. package/dist/commands/setup.js +1 -1
  17. package/dist/commands/solution.js +211 -54
  18. package/dist/commands/tenants.js +55 -12
  19. package/dist/commands/values.js +104 -23
  20. package/dist/commands/work.js +13 -5
  21. package/dist/confirm-token.js +90 -7
  22. package/dist/context.js +5 -1
  23. package/dist/contracts.js +37 -12
  24. package/dist/database-queries.js +301 -0
  25. package/dist/fsutil.js +14 -0
  26. package/dist/http.js +69 -3
  27. package/dist/install.js +30 -0
  28. package/dist/invoke.js +12 -2
  29. package/dist/kit-codes.js +9 -2
  30. package/dist/mcp.js +106 -19
  31. package/dist/openapi.js +7 -0
  32. package/dist/package-check.js +19 -0
  33. package/dist/preview-report.js +2 -2
  34. package/dist/principal.js +24 -2
  35. package/dist/printed.js +5 -0
  36. package/dist/secret-access.js +30 -9
  37. package/dist/session.js +36 -8
  38. package/dist/skills/cavelon-authoring/SKILL.md +93 -10
  39. package/dist/skills/cavelon-long-running/SKILL.md +18 -8
  40. package/dist/skills/cavelon-loop/SKILL.md +126 -41
  41. package/dist/skills/cavelon-testing/SKILL.md +32 -3
  42. package/dist/trace-view.js +10 -0
  43. package/dist/update-check.js +2 -2
  44. package/dist/user-config.js +24 -0
  45. package/package.json +1 -1
package/dist/http.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { accessFor, forbiddenHint } from "./access.js";
1
2
  import { capacityCodeIn, capacityHint } from "./capacity.js";
3
+ import { CONFIRMATION_REQUIRED, confirmationRefused } from "./change-confirmation.js";
2
4
  import { ceilingRefusal, LIMIT_ABOVE_CEILING } from "./limits.js";
3
5
  import { CavelonError, ExitCode } from "./errors.js";
4
6
  import { blockerDetails } from "./preview-report.js";
@@ -28,6 +30,8 @@ export class ApiClient {
28
30
  target;
29
31
  env;
30
32
  tokensOff;
33
+ revalidateTenant;
34
+ confirmer;
31
35
  constructor(target, env = {}) {
32
36
  this.target = target;
33
37
  this.env = env;
@@ -98,10 +102,12 @@ export class ApiClient {
98
102
  }
99
103
  }
100
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;
101
107
  const timeoutMs = options.timeoutMs ?? (Number(this.env.CAVELON_HTTP_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS);
102
108
  const timeout = AbortSignal.timeout(timeoutMs);
103
109
  const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
104
- const response = await this.fetchRaw(method, path, { ...options, signal });
110
+ const response = await this.fetchRaw(method, path, { ...options, headers: sentHeaders, signal });
105
111
  let text;
106
112
  try {
107
113
  text = await response.text();
@@ -118,17 +124,55 @@ export class ApiClient {
118
124
  });
119
125
  }
120
126
  if (!response.ok && !options.allow?.includes(response.status)) {
127
+ if (await this.tenantMoved(method, path, response.status, options))
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 });
121
132
  const tenantless = options.sendTenant !== false && !this.headers(options)["X-Tenant-Id"] && Boolean(this.target.token?.startsWith("cvpat_"));
122
133
  const pathname = new URL(response.url || this.resolve(path)).pathname;
123
134
  const platform = options.sendTenant === false || isPlatformRoute(pathname);
124
- throw await this.refusal(response.status, data, `${method} ${pathname}`, response.headers, { tenantless, platform });
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);
125
137
  }
126
138
  return { status: response.status, headers: response.headers, data: data, text };
127
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
+ }
150
+ async tenantMoved(method, path, status, options = {}) {
151
+ const sentTenant = this.headers(options)["X-Tenant-Id"];
152
+ if ((status !== 403 && status !== 404) || !sentTenant || !this.revalidateTenant)
153
+ return false;
154
+ const revalidate = this.revalidateTenant;
155
+ this.revalidateTenant = undefined;
156
+ if (!(await revalidate()))
157
+ return false;
158
+ if (method === "GET" || method === "HEAD")
159
+ return true;
160
+ throw new CavelonError(ExitCode.conflict, {
161
+ code: "tenant_moved",
162
+ status,
163
+ message: `${method} ${path} was refused in tenant ${sentTenant}, which a cached slug named; the slug now names tenant ${this.target.tenantId}. Nothing was changed.`,
164
+ hint: "Run the command again: it now acts in the tenant the slug names, and a change previews there first.",
165
+ });
166
+ }
128
167
  async refusal(status, body, what, headers, sent = {}) {
129
168
  if (status === 401 && this.target.token?.startsWith("cvpat_") && (await this.personalAccessTokensOff())) {
130
169
  return tokensDisabledError(this.url);
131
170
  }
171
+ if (status === 403 && sent.method && sent.path && this.target.token && !sent.platform && !sent.tenantless) {
172
+ const kind = this.target.token.startsWith("cbp_") ? "api_key" : this.target.token.startsWith("cvpat_") ? "personal_access_token" : undefined;
173
+ const access = await accessFor(this).catch(() => undefined);
174
+ sent = { ...sent, credential: { kind, access, method: sent.method, path: sent.path } };
175
+ }
132
176
  return errorFromResponse(status, body, what, headers, sent);
133
177
  }
134
178
  personalAccessTokensOff() {
@@ -152,6 +196,13 @@ export class ApiClient {
152
196
  return this.request("GET", path, options);
153
197
  }
154
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
+ }
155
206
  function parseBody(text, contentType) {
156
207
  if (!text)
157
208
  return null;
@@ -283,6 +334,9 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
283
334
  }
284
335
  if (changed)
285
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 };
286
340
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
287
341
  hint = `Choose a tenant with \`${cavelonCommand("use")}\` (it lists your tenants), --tenant or CAVELON_TENANT.`;
288
342
  }
@@ -294,7 +348,15 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
294
348
  ? PLATFORM_ROUTE_HINT
295
349
  : sent.tenantless
296
350
  ? `No tenant was named. ${TENANT_ID_HINT} Otherwise check the token's permission ceiling.`
297
- : `The token does not reach this. Check the tenant (\`${cavelonCommand("whoami")}\`) and the token's permission ceiling.`;
351
+ : sent.credential
352
+ ? undefined
353
+ : `The token does not reach this. Check the tenant (\`${cavelonCommand("whoami")}\`) and the token's permission ceiling.`;
354
+ if (!hint && sent.credential) {
355
+ const forbidden = forbiddenHint(message ?? "", sent.credential);
356
+ hint = forbidden.hint;
357
+ if (details === undefined)
358
+ details = forbidden.details;
359
+ }
298
360
  }
299
361
  return new CavelonError(exitCode, {
300
362
  code: code ?? defaultCode(status),
@@ -314,6 +376,8 @@ export function exitCodeForStatus(status) {
314
376
  return ExitCode.validation;
315
377
  if (status === 409 || status === 412)
316
378
  return ExitCode.conflict;
379
+ if (status === 428)
380
+ return ExitCode.needsAction;
317
381
  if (status === 408 || status === 429 || status >= 500)
318
382
  return ExitCode.server;
319
383
  return ExitCode.failure;
@@ -332,6 +396,8 @@ function defaultCode(status) {
332
396
  return "conflict";
333
397
  case 412:
334
398
  return "precondition_failed";
399
+ case 428:
400
+ return "precondition_required";
335
401
  case 422:
336
402
  return "validation_failed";
337
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;
@@ -108,10 +110,18 @@ export async function callOperation(ctx, client, doc, op, args) {
108
110
  }
109
111
  }
110
112
  if (!response.ok) {
113
+ if (await client.tenantMoved(op.method, target, response.status, { sendTenant: args.sendTenant }))
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 });
111
118
  const pathname = new URL(client.resolve(target)).pathname;
112
- 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, {
113
120
  platform: args.sendTenant === false || isPlatformRoute(pathname),
121
+ method: op.method,
122
+ path: pathname,
114
123
  });
124
+ throw confirmationRefused(error, Boolean(confirmed) || args.confirmation === false);
115
125
  }
116
126
  return { status: response.status, contentType, data: isText ? (text ? data : null) : undefined, bytes: isText ? undefined : bytes };
117
127
  }
package/dist/kit-codes.js CHANGED
@@ -5,6 +5,8 @@ export const KIT_ERROR_CODES = [
5
5
  { code: "unauthorized", area: "cli", message: "The instance refused the token: expired, revoked, or for another instance.", hint: "A person creates a new token on /account/access-tokens and runs `cavelon login`." },
6
6
  { code: "tenant_required", area: "cli", message: "The command acts in a tenant, and none is chosen.", hint: "Choose one with `cavelon use` (it lists your tenants), or pass --tenant <name or slug>." },
7
7
  { code: "tenant_not_found", area: "cli", message: "No tenant by that name, slug or id that this token reaches.", hint: "`cavelon tenant list` shows the tenants; `cavelon whoami` which ones the token reaches." },
8
+ { code: "tenant_mismatch", area: "cli", message: "The tenant API key acts only in its own tenant, and the command names another; nothing was sent there.", hint: "Use a key of the tenant you name (CAVELON_TOKEN), or name the key's tenant, or leave the tenant out where the key is meant." },
9
+ { code: "tenant_moved", area: "cli", message: "A change was refused in the tenant a cached slug named, and the slug now names another tenant; nothing was changed.", hint: "Run the command again: it acts in the tenant the slug names now, and a change previews there first." },
8
10
  { code: "no_tenant_reached", area: "cli", message: "The token reaches no tenant on this instance.", hint: "A person adds the token's owner to a tenant, or creates a token for one; `cavelon whoami` shows what it reaches." },
9
11
  { code: "api_key_inactive", area: "cli", message: "The tenant API key is revoked or inactive.", hint: "A person creates a new key in the Admin." },
10
12
  { code: "api_key_cannot_create_tenants", area: "cli", message: "A tenant API key can never create a tenant.", hint: "Use a personal access token that allows Platform mode, owned by someone with tenants.manage." },
@@ -13,7 +15,7 @@ export const KIT_ERROR_CODES = [
13
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." },
14
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." },
15
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\"." },
16
- { 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." },
17
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." },
18
20
  { code: "network_error", area: "cli", message: "The instance could not be reached.", hint: "Check the instance URL and the network (VPN, proxy, allowlist)." },
19
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." },
@@ -29,7 +31,7 @@ export const KIT_ERROR_CODES = [
29
31
  { code: "operation_ambiguous", area: "cli", message: "The short name matches several operations.", hint: "Use the full operationId the message lists." },
30
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." },
31
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." },
32
- { 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." },
33
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." },
34
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." },
35
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." },
@@ -60,6 +62,8 @@ export const KIT_ERROR_CODES = [
60
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." },
61
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." },
62
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." },
63
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." },
64
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." },
65
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`." },
@@ -88,6 +92,9 @@ export const KIT_ERROR_CODES = [
88
92
  { code: "sandbox_transfer_size_limit", area: "cli", message: "The archive is larger than a Sandbox imports at once.", hint: "Seed fewer or smaller files; a seed replaces the whole workspace." },
89
93
  { code: "sandbox_artifact_digest_mismatch", area: "cli", message: "The export arrived with another digest than the instance declared; nothing was written.", hint: "Download it again." },
90
94
  { code: "invalid_job_id", area: "cli", message: "The instance returned an unexpected job id.", hint: "Retry; if it repeats, report it with the command." },
95
+ { code: "database_connector_disabled", area: "cli", message: "This instance has the database connector switched off.", hint: "Its operator switches it on (DATABASE_CONNECTOR_ENABLED); until then no agent gets a database tool." },
96
+ { code: "database_connection_not_found", area: "cli", message: "No database connection by that name or id in this tenant.", hint: "`cavelon db connections` lists them; a superadmin creates one in the Admin." },
97
+ { code: "database_query_not_found", area: "cli", message: "No saved database query by that tool slug or id in this tenant.", hint: "`cavelon db queries` lists them; a superadmin writes one in the Admin, and `cavelon pull` brings it into the package." },
91
98
  { code: "usage", area: "cli", message: "The command was called the wrong way (a missing or invalid argument or option).", hint: "`cavelon <command> --help` shows its arguments." },
92
99
  { code: "validation_failed", area: "cli", message: "A value did not pass the check before it was sent, or the instance refused it as invalid.", hint: "The message names the field; `cavelon api describe <operation>` shows the shape." },
93
100
  { code: "cancelled", area: "cli", message: "Nothing was chosen or confirmed, so nothing changed.", hint: "Run the command again, or name the choice with an option." },
package/dist/mcp.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
2
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
+ import { accessFor, allOf, credentialWords, operationAccess, whoInstead } from "./access.js";
3
4
  import { formerlyWarning, ownsTenant, propertyName } from "./command.js";
4
5
  import { MCP_MAX_WAIT_MS } from "./commands/async.js";
6
+ import { PERSON_WAIT_MS } from "./confirm-token.js";
5
7
  import { createContext, withWarnings } from "./context.js";
6
8
  import { asCavelonError, CavelonError, ExitCode, usageError } from "./errors.js";
7
9
  import { closest } from "./package-references.js";
@@ -13,15 +15,24 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
13
15
  "loop_start, sandbox_seed, artifacts_export) return operation ids at once; read them with operation_status, which returns " +
14
16
  `the state at once, or waits up to its timeout (at most ${MCP_MAX_WAIT_MS / 1000} s) when given one, and reports waited_ms, ` +
15
17
  "and follow a loop with loop_iterations. What needs confirmation: apply imports only with confirm set to a preview's id; " +
16
- "limits_set, models_set_limit, loop_cancel, sandbox_seed, trigger_identity, harness_default, activate with make_default, deactivate, " +
18
+ "tenant_create, variables_set where it replaces another value, loop_start, limits_set, models_set_limit, loop_cancel, sandbox_seed, " +
19
+ "trigger_identity, harness_default, activate of a solution a channel or trigger reaches or with make_default, deactivate, " +
17
20
  "and api for an operation that is not read-only, " +
18
21
  "return what they would do and a confirm_token, and change nothing until called again with the same arguments and " +
19
22
  "confirm set to that token: show the person the preview first. The token confirms exactly the change the preview showed; " +
20
- "a different change needs a new preview, and confirm: true is refused. The default route " +
21
- "(harness_default, activate's make_default) decides which solution the tenant's chat and widget answer with: live traffic, " +
22
- "so ask the person, and confirm only with their yes; the same goes for deactivate, which takes a solution out of live traffic " +
23
- "(its status becomes inactive), and for apply with include_tenant_wide, which imports the tenant-wide sections (tenant_settings, " +
24
- "model_registry, …) for every solution of the tenant. " +
23
+ "a different change needs a new preview, and confirm: true is refused. A change that reaches live traffic or the whole tenant, " +
24
+ "or that cannot be taken back, is the person's to confirm, and the token alone does not make it: its preview says " +
25
+ "needs_person. With needs_person \"client\", call again with the token and the client asks the person to approve exactly that " +
26
+ "change; their no, or no answer, changes nothing (confirm_declined). Only after their yes does cavelon ask the instance for " +
27
+ "the confirmation it checks itself; confirmation_required or confirmation_invalid changed nothing: preview again, never retry " +
28
+ "on your own. With needs_person \"terminal\" this client cannot ask " +
29
+ "them: give the person the preview's confirm command, which they run in their own terminal, never in yours. These are " +
30
+ "harness_default and activate (the default route and a solution something reaches: live traffic), deactivate, tenant_create, " +
31
+ "variables_set replacing a value (every solution of the tenant reads it), limits_set, models_set_limit, trigger_identity, " +
32
+ "api for an operation that is not read-only, loop_start unless the trigger's solution is a draft (a run acts as the person " +
33
+ "and spends budget), and apply where its preview says show_to_person (tenant-wide sections, an active solution, deletions, " +
34
+ "env/prod). A draft's apply, a draft's loop_start, loop_cancel, sandbox_seed and kb_upload's replace you confirm with the " +
35
+ "token once the person saw the preview. " +
25
36
  "chat sends one message to a solution and returns its answer: the way to try one that is not the default route. " +
26
37
  "kb_upload names files that match an active document of the knowledge base; with replace it replaces them, and where the " +
27
38
  "instance's upload cannot, it returns what it would deactivate and uploads nothing without its confirm_token. " +
@@ -31,6 +42,9 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
31
42
  "(x-cavelon-person-only; its reason is in the error), or on an instance that marks none, one that changes a secret, " +
32
43
  "creates or revokes a credential (tokens, API keys, sign-in) or decides an approval; it also refuses a body that sets a field " +
33
44
  "the instance marks as a secret value (x-cavelon-secret): leave the field out and let a person enter the value. " +
45
+ "A tool whose description starts with \"Not for this credential\" is one the instance says this token or key may not use " +
46
+ "in this tenant (whoami lists its permissions, an API key's scopes and the operations a person runs): do not call it to " +
47
+ "find out; tell the person who does it. api_list marks such operations (may_send false) and leaves them out with usable. " +
34
48
  "Run from your shell, cavelon's api command applies the same guards, and sends a changing operation only with --confirm and the token " +
35
49
  "its preview printed. Tools read and write files only " +
36
50
  "inside the solution folder (the folder of cavelon.yaml, or the one the server started in), never in cavelon's own " +
@@ -38,16 +52,26 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
38
52
  "instance allows this tenant (upload sizes and types, run and tool limits, timeouts, quotas) and who changes each. " +
39
53
  "Never change a limit on your own: propose the old and new value (limits_set for a limit a tenant admin changes, " +
40
54
  "models_set_limit for an endpoint's max_concurrent_requests) and let the person decide; an operator's limit goes to the operator. " +
41
- "variables_list/variables_get/variables_set handle plain-text {{var:…}} values. secrets_list shows which {{secret:…}} " +
42
- "values are set, never a value: a person sets a secret, so tell them the exact `cavelon secrets set <name>` command " +
43
- "to run in their terminal, and never ask for, read or pass a secret value. Never approve or decide an approval; " +
55
+ "db_connections, db_queries and db_runs read the database connections, saved queries and their runs behind database query " +
56
+ "tools; only a superadmin in the Admin creates or changes a connection or a query, so an apply that changes a query is " +
57
+ "blocked for any token: tell the person, and apply the rest with the query left as the instance holds it. " +
58
+ "variables_list/variables_get/variables_set handle plain-text {{var:…}} values; setting one needs a role that may manage " +
59
+ "the tenant's settings, as a secret does (a Builder's may not): where whoami says the credential may not, tell the person " +
60
+ "who sets it instead of calling variables_set. secrets_list shows which {{secret:…}} " +
61
+ "values are set, never a value: a person sets a secret, so tell them how, as the answers name it: the exact " +
62
+ "`cavelon secrets set <name>` command to run in their terminal, or, where the instance lets no token set one, the Admin " +
63
+ "under Settings › Secrets. Never ask for, read or pass a secret value. Never approve or decide an approval; " +
44
64
  "that stays with a person. Use docs_search before guessing, " +
45
65
  "and api_list/api_describe/api for anything without its own tool. " +
66
+ "use_tenant chooses the tenant for this MCP session only and never changes the tenant stored for the person; every preview " +
67
+ "names the instance, the tenant and the mode it acts on (its target): show that to the person with the change. " +
46
68
  "The first result of a session may carry a warning that cavelon, the Cavelon plugin or this folder's skills are behind " +
47
69
  "the latest release, with the commands that update them: pass it on to the person, who runs them; do not run them yourself.";
48
70
  export function mcpInstructions(commands) {
49
71
  return printingFor({ mode: "mcp", commands }, () => spoken(INSTRUCTIONS));
50
72
  }
73
+ const TOOL_LIST_ACCESS_MS = 5_000;
74
+ const TENANT_CHOOSERS = new Set(["use_tenant", "tenant_create"]);
51
75
  const TOKEN_DESCRIPTION = "Over MCP: the confirm_token this tool's preview returned, which confirms exactly the change it showed; true is refused.";
52
76
  export function toolName(spec) {
53
77
  return spec.mcpTool || undefined;
@@ -88,15 +112,31 @@ export function inputSchema(spec, commands = []) {
88
112
  : { type: ["string", "number"], description };
89
113
  }
90
114
  if (!ownsTenant(spec)) {
91
- properties.tenant = { type: "string", description: "Tenant slug or id, when not the one chosen for this directory." };
115
+ properties.tenant = {
116
+ type: "string",
117
+ description: "Tenant slug or id, when not the one chosen for this directory or with use_tenant in this session. A preview names the tenant it acts on.",
118
+ };
92
119
  }
93
120
  return { type: "object", properties, ...(required.length ? { required } : {}), additionalProperties: false };
94
121
  }
95
- export function toolFor(spec, commands = []) {
122
+ export function notForThisCredential(spec, access) {
123
+ if (!access)
124
+ return undefined;
125
+ for (const operation of spec.operations ?? []) {
126
+ const refused = operationAccess(access, operation);
127
+ if (refused.allowed !== false)
128
+ continue;
129
+ const why = refused.person ? "a person runs it" : `it needs ${allOf(refused.missing)}, which it does not hold`;
130
+ return `Not for this credential: ${credentialWords(access)} may not send ${operation} (${why}). ${whoInstead(access, refused)} Do not call it to find out; tell the person.`;
131
+ }
132
+ return undefined;
133
+ }
134
+ export function toolFor(spec, commands = [], access) {
96
135
  const marked = spec.mcpEffect ?? (spec.readOnly ? "Read-only." : spec.destructive ? "Changes the instance; may delete or overwrite." : "Changes the instance.");
136
+ const refused = notForThisCredential(spec, access);
97
137
  return {
98
138
  name: toolName(spec),
99
- description: mcpSpelling([spec.summary, spec.description, marked].filter(Boolean).join("\n"), spec, commands),
139
+ description: mcpSpelling([refused, spec.summary, spec.description, marked].filter(Boolean).join("\n"), spec, commands),
100
140
  inputSchema: inputSchema(spec, commands),
101
141
  annotations: {
102
142
  title: spec.summary,
@@ -167,16 +207,58 @@ function missingRequired(spec, args) {
167
207
  .filter((p) => p.required && (args[p.name] === undefined || args[p.name] === ""))
168
208
  .map((p) => p.name);
169
209
  }
210
+ const APPROVAL_SCHEMA = {
211
+ type: "object",
212
+ properties: { approve: { type: "boolean", title: "Make this change", description: "Yes makes exactly the change shown; no changes nothing." } },
213
+ required: ["approve"],
214
+ };
215
+ function clientAsks(server) {
216
+ const elicitation = server.getClientCapabilities()?.elicitation;
217
+ return Boolean(elicitation && (elicitation.form || Object.keys(elicitation).length === 0));
218
+ }
219
+ async function askThroughClient(server, message, relatedRequestId) {
220
+ try {
221
+ const result = await server.elicitInput({ mode: "form", message, requestedSchema: APPROVAL_SCHEMA }, { timeout: PERSON_WAIT_MS, relatedRequestId });
222
+ return result.action === "accept" && result.content?.approve === true ? "approved" : "declined";
223
+ }
224
+ catch {
225
+ return "unanswered";
226
+ }
227
+ }
170
228
  function mcpIo(io) {
171
229
  return { ...io, stdout: { write: () => true, isTTY: false } };
172
230
  }
173
231
  export function createMcpServer(io, commands, updates = {}) {
174
232
  const tools = commands.filter((c) => c.mcpTool);
175
233
  const byName = new Map(tools.map((c) => [toolName(c), c]));
176
- const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: {} }, instructions: mcpInstructions(commands) });
234
+ const server = new Server({ name: "cavelon", version: KIT_VERSION }, { capabilities: { tools: { listChanged: true } }, instructions: mcpInstructions(commands) });
177
235
  const notice = startSessionUpdateCheck(io, updates);
178
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools.map((t) => toolFor(t, commands)) }));
179
- async function call(name, given) {
236
+ const sessionTenants = new Map();
237
+ async function credentialAccess() {
238
+ const read = (async () => {
239
+ const ctx = createContext(mcpIo(io), { json: true, sessionTenants }, "mcp");
240
+ const session = await ctx.session();
241
+ if (!session.url || !session.token)
242
+ return undefined;
243
+ return accessFor(await ctx.client());
244
+ })().catch(() => undefined);
245
+ let timer;
246
+ const late = new Promise((resolve) => {
247
+ timer = setTimeout(() => resolve(undefined), TOOL_LIST_ACCESS_MS);
248
+ timer.unref?.();
249
+ });
250
+ try {
251
+ return await Promise.race([read, late]);
252
+ }
253
+ finally {
254
+ clearTimeout(timer);
255
+ }
256
+ }
257
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
258
+ const access = await credentialAccess();
259
+ return { tools: tools.map((t) => toolFor(t, commands, access)) };
260
+ });
261
+ async function call(name, given, requestId) {
180
262
  const spec = byName.get(name);
181
263
  const fail = (error) => ({ isError: true, body: { error: asCavelonError(error).toJSON() } });
182
264
  if (!spec)
@@ -195,11 +277,14 @@ export function createMcpServer(io, commands, updates = {}) {
195
277
  }
196
278
  const tenant = !ownsTenant(spec) && typeof args.tenant === "string" ? args.tenant : undefined;
197
279
  const solutionEnv = spec.options?.env && typeof args.env === "string" ? args.env : undefined;
198
- const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv }, "mcp");
280
+ const ctx = createContext(mcpIo(io), { json: true, tenant, solutionEnv, sessionTenants }, "mcp");
281
+ if (clientAsks(server))
282
+ ctx.askPerson = (message) => askThroughClient(server, message, requestId);
199
283
  for (const message of renamed)
200
284
  ctx.warn(message);
201
285
  try {
202
- const { result, warnings } = await printingFor({ mode: "mcp", commands, ...(spec.storesTarget ? {} : { tenant, env: solutionEnv }) }, async () => {
286
+ const chosen = tenant ?? (await ctx.session().then((s) => (s.tenantSource === "session" ? s.tenant : undefined), () => undefined));
287
+ const { result, warnings } = await printingFor({ mode: "mcp", commands, ...(spec.storesTarget ? {} : { tenant: chosen, env: solutionEnv }) }, async () => {
203
288
  try {
204
289
  const done = await spec.run(ctx, inputFrom(spec, args));
205
290
  return { result: { ...done, data: spokenHints(done.data) }, warnings: ctx.warnings.map(spoken) };
@@ -220,9 +305,11 @@ export function createMcpServer(io, commands, updates = {}) {
220
305
  return fail(error);
221
306
  }
222
307
  }
223
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
308
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
224
309
  const warning = notice.forCall(() => server.getClientVersion()?.name);
225
- const { body, isError } = await call(request.params.name, (request.params.arguments ?? {}));
310
+ const { body, isError } = await call(request.params.name, (request.params.arguments ?? {}), extra.requestId);
311
+ if (!isError && TENANT_CHOOSERS.has(request.params.name))
312
+ void server.sendToolListChanged().catch(() => undefined);
226
313
  let out = body;
227
314
  const text = await warning;
228
315
  if (text) {
package/dist/openapi.js CHANGED
@@ -40,6 +40,7 @@ export function operations(doc) {
40
40
  responses: raw.responses ?? {},
41
41
  readOnly: method === "get" || method === "head" || method === "options",
42
42
  personOnly: personOnlyOf(raw),
43
+ ...confirmationOf(raw),
43
44
  });
44
45
  }
45
46
  }
@@ -55,6 +56,12 @@ function personOnlyOf(raw) {
55
56
  ...(typeof reason === "string" && reason.trim() ? { reason: reason.trim() } : {}),
56
57
  };
57
58
  }
59
+ function confirmationOf(raw) {
60
+ if (raw["x-cavelon-confirmation"] !== "required")
61
+ return {};
62
+ const when = raw["x-cavelon-confirmation-when"];
63
+ return { confirmation: true, ...(typeof when === "string" && when.trim() ? { confirmationWhen: when.trim() } : {}) };
64
+ }
58
65
  export function deref(doc, value) {
59
66
  let current = value;
60
67
  for (let i = 0; i < 10 && current && typeof current === "object" && typeof current.$ref === "string"; i++) {
@@ -1,5 +1,6 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import { BRANCH_WIDTH_KEY, branchConcurrency, offText } from "./branches.js";
3
+ import { checkQueryTools, QUERY_CHANGED_CODE, QUERY_FIELDS_IGNORED_CODE } from "./database-queries.js";
3
4
  import { locate, schemaSections, tenantWideSections } from "./package-files.js";
4
5
  import { MANIFEST_SECTION, PERSONA_SECTION, sectionFields } from "./package-format.js";
5
6
  import { kitErrorEntry } from "./kit-codes.js";
@@ -29,6 +30,7 @@ const SOLUTION_MISMATCH_CODE = "solution_slug_mismatch";
29
30
  const TENANT_WIDE_CODE = "tenant_wide_section";
30
31
  const ASSERTION_UNCHECKED_CODE = "test_assertion_unchecked";
31
32
  const TESTING_DOCS = "/docs/concepts/regression-testing";
33
+ const DATABASE_DOCS = "/docs/administration/database-connectors";
32
34
  export const KIT_CODES = [
33
35
  {
34
36
  code: SCHEMA_CODE,
@@ -158,6 +160,22 @@ export const KIT_CODES = [
158
160
  "Remove the file unless that is meant. An instance that does not publish include_tenant_wide imports it with every apply.",
159
161
  docs: PACKAGE_DOCS,
160
162
  },
163
+ {
164
+ code: QUERY_CHANGED_CODE,
165
+ area: "package",
166
+ message: "A database query tool's query (database_query), name or description differs from the last pull or apply, or the tool is new. Only a superadmin in the Admin creates or changes a query; a personal access token's import preview blocks it.",
167
+ hint: "Hand the change to a superadmin, who imports the package in the Admin (`cavelon explain database_query_needs_superadmin` names the step); then apply passes while the queries match. " +
168
+ "To apply the rest first, leave the query as the instance holds it: restore the tool's entry as the last pull wrote it, or remove its database_query block (a query tool without one keeps the instance's query, name and description). " +
169
+ "Rename the tool for one agent with the assignment's config_overrides instead: an override of name, description or max_calls is no query change.",
170
+ docs: DATABASE_DOCS,
171
+ },
172
+ {
173
+ code: QUERY_FIELDS_IGNORED_CODE,
174
+ area: "package",
175
+ message: "A database query tool's params_json_schema or default_config differs from the last pull or apply; the instance derives both from the query and ignores the package's.",
176
+ hint: "Change the query's parameters instead (database_query.parameters), or put the field back as pulled.",
177
+ docs: DATABASE_DOCS,
178
+ },
161
179
  {
162
180
  code: "package_file_duplicate",
163
181
  area: "package",
@@ -320,6 +338,7 @@ export function checkPackage(disk, options) {
320
338
  findings.push(...checkUncheckedAssertions(disk, options.schema));
321
339
  findings.push(...checkSolutionSlug(disk, options.solution));
322
340
  findings.push(...checkTenantWide(disk, options.schema, options.solution));
341
+ findings.push(...checkQueryTools(disk, options.schema, options.queryBaseline));
323
342
  noteTenantWide(findings, options.schema, options.solution);
324
343
  for (const finding of findings) {
325
344
  const entry = findingEntry(options.catalog, finding.code);
@@ -143,7 +143,7 @@ function harnessSlugAt(path, pkg, fallback) {
143
143
  const entry = index !== undefined ? list[Number(index)] : undefined;
144
144
  return (isObject(entry) && text(entry.slug)) || fallback;
145
145
  }
146
- export function notApplied(raw, pkg, harness) {
146
+ export function notApplied(raw, pkg, harness, mayActivate = null) {
147
147
  if (!Array.isArray(raw))
148
148
  return [];
149
149
  return raw
@@ -164,7 +164,7 @@ export function notApplied(raw, pkg, harness) {
164
164
  if (field === "is_default")
165
165
  return { ...n, command: cavelonCommand("harness", "default", slug ?? "<solution>") };
166
166
  if (field === "status")
167
- return { ...n, command: slug ? cavelonCommand("activate", "--harness", slug) : cavelonCommand("activate") };
167
+ return mayActivate === false ? n : { ...n, command: slug ? cavelonCommand("activate", "--harness", slug) : cavelonCommand("activate") };
168
168
  return n;
169
169
  });
170
170
  }
package/dist/principal.js CHANGED
@@ -2,8 +2,30 @@ export async function readPrincipal(client, options = {}) {
2
2
  const response = await client.get("/api/v1/meta/principal", { allow: [400, 403, 404, 405], sendTenant: options.sendTenant });
3
3
  if (response.status !== 200 || !response.data?.kind)
4
4
  return undefined;
5
- const { permissions, ...rest } = response.data;
6
- return Array.isArray(permissions) ? { ...rest, permissions: permissions.filter((p) => typeof p === "string") } : rest;
5
+ const { permissions, needs_a_person: needsAPerson, tenant, ...rest } = response.data;
6
+ const principal = rest;
7
+ if (Array.isArray(permissions))
8
+ principal.permissions = permissions.filter((p) => typeof p === "string");
9
+ if (Array.isArray(needsAPerson))
10
+ principal.needs_a_person = operationsNeedingAPerson(needsAPerson);
11
+ if (tenant === null)
12
+ principal.tenant = null;
13
+ else if (tenant && typeof tenant === "object" && typeof tenant.id === "string") {
14
+ const text = (v) => (typeof v === "string" && v ? v : null);
15
+ principal.tenant = { id: tenant.id, name: text(tenant.name), slug: text(tenant.slug) };
16
+ }
17
+ return principal;
18
+ }
19
+ function operationsNeedingAPerson(value) {
20
+ return value
21
+ .filter((o) => Boolean(o) && typeof o === "object")
22
+ .filter((o) => typeof o.method === "string" && typeof o.path === "string")
23
+ .map((o) => ({
24
+ operation: typeof o.operation === "string" && o.operation ? o.operation : null,
25
+ method: o.method.toUpperCase(),
26
+ path: o.path,
27
+ reason: typeof o.reason === "string" ? o.reason : "",
28
+ }));
7
29
  }
8
30
  const TENANT_PAGE = 200;
9
31
  const MAX_TENANT_PAGES = 5;