@cavelon/cli 0.1.11 → 0.1.13

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.
package/README.md CHANGED
@@ -17,8 +17,9 @@ npm i -g @cavelon/cli
17
17
  Without Node.js, one line installs a standalone `cavelon` into your user
18
18
  folder: `curl -fsSL https://github.com/goodguys-gmbh/cavelon-dev-kit/releases/latest/download/install.sh | sh`
19
19
  on macOS and Linux, `irm https://github.com/goodguys-gmbh/cavelon-dev-kit/releases/latest/download/install.ps1 | iex`
20
- in Windows PowerShell. Then `cavelon setup` sets up your coding agents and logs
21
- you in.
20
+ in Windows PowerShell. With Python, `uvx cavelon` runs the same executable from
21
+ PyPI, and `uv tool install cavelon` or `pipx install cavelon` installs it. Then
22
+ `cavelon setup` sets up your coding agents and logs you in.
22
23
 
23
24
  The full documentation is in the repository's
24
25
  [`docs/`](https://github.com/goodguys-gmbh/cavelon-dev-kit/tree/main/docs):
@@ -150,7 +151,8 @@ Every command takes `--json` (one JSON document on stdout, errors included),
150
151
  | `kb upload <dir> --kb <kb> [-r] [--ext pdf] [--replace] [--dry-run] [--wait]` | changing | Upload documents; returns operation ids. Names files that match an active document; `--replace` replaces those. `--dry-run` also names files identical to an active document. |
151
152
  | `test run [--suite <s>] [--harness <h>] [--wait]` | changing | Start test-suite runs; returns operation ids. |
152
153
  | `trace <run> [--trace <id>] [--span <id>]` | read-only | Summarise a run's traces (or a test run's results, with why a case did not pass), then one trace's spans, then one span. A database query call that failed shows its code. |
153
- | `db connections` / `db queries [<query>] [--connection]` / `db runs <query>` | read-only | The tenant's database connections, saved queries (one in full with its SQL and parameters) and a query's runs (no values, no rows). |
154
+ | `db instance` | read-only | The dialects the instance runs and the addresses it connects to databases from, which a database's firewall lets in. |
155
+ | `db connections` / `db queries [<query>] [--connection]` / `db runs <query>` | read-only | The tenant's database connections (with their CA certificates' expiry), saved queries (one in full with its SQL and parameters) and a query's runs (no values, no rows). |
154
156
  | `db test <connection>` | changing | The tenant Owner tests a connection step by step; exit 3 when a step fails. |
155
157
  | `db test-run <query> [--value name=value…]` | changing | The tenant Owner runs a saved query once, identity parameters included, and sees what the model would; exit 3 when it fails. |
156
158
  | `loop start <trigger> [--input <json>] [--wait] [--confirm]` | changing | Start a loop through its trigger, as you; without `--confirm`, shows the trigger, its solution and the payload; with it, returns the run and operation ids. |
@@ -398,9 +400,13 @@ op read op://dev/crm/token | cavelon secrets set crm_api_token
398
400
  dropped), and refuses a value given as an argument without repeating it.
399
401
  Setting or deleting one needs a person (a session or a personal access
400
402
  token): with a tenant API key, `cavelon` refuses before it asks for the value
401
- or sends anything (exit 7, `secret_needs_a_person`, as the instance would
402
- answer). MCP offers only `secrets_list`; an agent tells the person the exact
403
- `cavelon secrets set <name>` command instead.
403
+ or sends anything (`secret_needs_a_person`, as the instance would answer).
404
+ Where the instance lets only a person signed in to the Admin set or delete
405
+ one (`/meta/principal` lists them in `needs_a_person`), every token is
406
+ refused that way (exit 5; a key on an older instance exits 7), and the hints name the Admin's
407
+ Settings › Secrets page. MCP offers only `secrets_list`; an agent tells the
408
+ person the exact `cavelon secrets set <name>` command, or the Admin page,
409
+ instead.
404
410
  - `--env <name>` acts in the tenant `env/<name>.yaml` names, like `apply`. A
405
411
  name without its env file is refused (exit 2) before anything is sent.
406
412
 
@@ -0,0 +1,93 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
2
+ import { operationForPath } from "./openapi.js";
3
+ import { cavelonCommand } from "./printed.js";
4
+ const DOCUMENTED = { path: "/api/v1/confirmations", header: "X-Cavelon-Confirmation" };
5
+ const HEADER_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;
6
+ export async function enforcedOffer(ctx) {
7
+ const caps = await (await ctx.contracts()).capabilities().catch(() => null);
8
+ const offer = caps?.confirmations;
9
+ if (!offer || typeof offer !== "object" || offer.enforced !== true)
10
+ return undefined;
11
+ return offerFrom(offer.path, offer.header);
12
+ }
13
+ function offerFrom(path, header) {
14
+ return {
15
+ path: typeof path === "string" && path.startsWith("/") ? path : DOCUMENTED.path,
16
+ header: typeof header === "string" && HEADER_NAME.test(header) ? header : DOCUMENTED.header,
17
+ };
18
+ }
19
+ async function marked(ctx, method, path) {
20
+ const doc = await (await ctx.contracts()).openapi().catch(() => undefined);
21
+ const found = doc ? operationForPath(doc, method, path) : undefined;
22
+ return found?.op.confirmation === true;
23
+ }
24
+ function ownPath(client, path, query) {
25
+ const url = client.resolve(path, query);
26
+ const base = new URL(client.url.endsWith("/") ? client.url : `${client.url}/`).pathname;
27
+ return { pathname: base.length > 1 && url.pathname.startsWith(base) ? url.pathname.slice(base.length - 1) : url.pathname, search: url.search };
28
+ }
29
+ export function confirmedPath(client, path, query) {
30
+ const own = ownPath(client, path, query);
31
+ return `${decodeURIComponent(own.pathname)}${own.search}`;
32
+ }
33
+ async function issue(client, offer, method, path, body) {
34
+ const response = await client.request("POST", offer.path, {
35
+ json: { method, path, body: body ?? null },
36
+ confirmation: false,
37
+ allow: [400, 404, 405, 422],
38
+ });
39
+ const id = response.status === 201 || response.status === 200 ? response.data?.confirmation_id : undefined;
40
+ return typeof id === "string" && id.trim() ? id.trim() : undefined;
41
+ }
42
+ export function changeConfirmer(ctx, client) {
43
+ return async (request, asked) => {
44
+ const approved = ctx.approved;
45
+ if (!approved || !client.target.token?.startsWith("cvpat_"))
46
+ return undefined;
47
+ let offer;
48
+ if (asked)
49
+ offer = offerFrom(asked.confirmations, asked.header);
50
+ else {
51
+ if (!approved.guarded)
52
+ return undefined;
53
+ offer = await enforcedOffer(ctx);
54
+ if (!offer || !(await marked(ctx, request.method, ownPath(client, request.path).pathname)))
55
+ return undefined;
56
+ }
57
+ const path = confirmedPath(client, request.path, request.query);
58
+ const id = await issue(client, offer, request.method, path, request.body);
59
+ return id ? { [offer.header]: id } : undefined;
60
+ };
61
+ }
62
+ export const CONFIRMATION_REQUIRED = "confirmation_required";
63
+ export const CONFIRMATION_INVALID = "confirmation_invalid";
64
+ export function confirmationRefused(error, sentId) {
65
+ if (error.status !== 428 || (error.code !== CONFIRMATION_REQUIRED && error.code !== CONFIRMATION_INVALID))
66
+ return error;
67
+ const details = error.details && typeof error.details === "object" && !Array.isArray(error.details) ? error.details : {};
68
+ const hint = error.code === CONFIRMATION_INVALID
69
+ ? "Run the command again: it previews the change, and once the person approves it cavelon asks the instance for a new confirmation. " +
70
+ `A confirmation lasts minutes and confirms one change once. \`${cavelonCommand("explain", CONFIRMATION_INVALID)}\` says more.`
71
+ : sentId
72
+ ? `The instance asked again for a confirmation cavelon sent. \`${cavelonCommand("explain", CONFIRMATION_REQUIRED)}\` says more.`
73
+ : "The instance wants the person's own yes for this change. The person runs the command in their own terminal with --confirm " +
74
+ "(or approves it in the MCP client's dialog), where cavelon asks the instance for the confirmation; or makes the change in the Admin. " +
75
+ `\`${cavelonCommand("explain", CONFIRMATION_REQUIRED)}\` says more.`;
76
+ return new CavelonError(ExitCode.needsAction, {
77
+ code: error.code,
78
+ message: error.message.includes("Nothing was changed") ? error.message : `${error.message} Nothing was changed.`,
79
+ hint,
80
+ docs: error.docs,
81
+ status: error.status,
82
+ details: { ...details, confirmation_sent: sentId },
83
+ });
84
+ }
85
+ export function confirmationPointer(code) {
86
+ if (code !== CONFIRMATION_REQUIRED && code !== CONFIRMATION_INVALID)
87
+ return undefined;
88
+ return ("Only after the person approved the change does cavelon ask the instance for this confirmation: in their own terminal with " +
89
+ "--confirm, or in the MCP client's dialog when an agent confirms with the preview's token. An agent's token alone never gets one. " +
90
+ (code === CONFIRMATION_INVALID
91
+ ? "An expired, used or other change's confirmation needs a new preview and the person's yes again."
92
+ : "An older cavelon sends none: update it, or make the change in the Admin."));
93
+ }
@@ -9,10 +9,10 @@ import { callOperation, previewRequest } from "../invoke.js";
9
9
  import { confinedPath } from "../paths.js";
10
10
  import { describeSchema, findOperation, jsonBodySchema, matchedLoosely, operations, schemaTypes, secretFields, secretPaths } from "../openapi.js";
11
11
  import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
12
- import { CONFIRM_TOKEN, confirmToken, confirmTokenRequired, confirmWith } from "../confirm-token.js";
12
+ import { CONFIRM_TOKEN, confirmInTerminal, confirmThroughClient, confirmToken, confirmTokenRequired, personApproves, personRoute } from "../confirm-token.js";
13
13
  import { actingTarget, targetLine } from "../acting.js";
14
14
  import { accessFor, operationAccess } from "../access.js";
15
- import { cavelonCommand, fill } from "../printed.js";
15
+ import { cavelonCommand, fill, personCommand } from "../printed.js";
16
16
  export const JSON_BODY_DEPRECATED = "`--json <body>` as the request body is deprecated and will be removed in a later release; pass the body with --body. " +
17
17
  "--json alone prints JSON, as on every command.";
18
18
  export function splitJsonBody(args, warn) {
@@ -98,7 +98,8 @@ function parseParams(input) {
98
98
  const FOR_A_PERSON = [
99
99
  {
100
100
  does: "changes a secret",
101
- hint: "A person sets a secret in their own terminal with `cavelon secrets set <name>` (or deletes it with `cavelon secrets delete <name>`).",
101
+ hint: "A person sets a secret in the Admin under Settings › Secrets, or, on an instance that still takes a token there, in their own " +
102
+ "terminal with `cavelon secrets set <name>` (or deletes it with `cavelon secrets delete <name>`).",
102
103
  match: (word) => word.includes("secret"),
103
104
  },
104
105
  {
@@ -201,8 +202,9 @@ export const api = {
201
202
  "As an MCP tool, or run by a coding agent (" +
202
203
  AGENT_VARIABLES.filter((v) => v.variable !== "CAVELON_AGENT").map((v) => (v.value ? `${v.variable}=${v.value}` : v.variable)).join(", ") +
203
204
  "\nor CAVELON_AGENT=1 is set), an operation that changes something returns what it would send and a confirm token,\n" +
204
- "and sends it only with that token: --confirm <token>, or confirm: \"<token>\" as an MCP tool. A changed request\n" +
205
- "needs a new preview; confirm: true is refused.\n" +
205
+ "and sends it only with that token and the person's yes: as an MCP tool, confirm: \"<token>\", after which the client\n" +
206
+ "asks the person; from an agent's shell, the person sends it from their own terminal. A changed request needs a new\n" +
207
+ "preview; confirm: true is refused.\n" +
206
208
  "Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
207
209
  "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
208
210
  "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
@@ -273,10 +275,20 @@ export const api = {
273
275
  throw secretRefusal(op, secrets, driven);
274
276
  }
275
277
  if (driven && !op.readOnly) {
276
- const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven);
278
+ const words = [
279
+ "api",
280
+ name,
281
+ ...(input.positionals.params ?? []),
282
+ ...listOption(input, "param").flatMap((p) => ["-p", p]),
283
+ ...(rawBody !== undefined ? ["--body", rawBody] : []),
284
+ ...listOption(input, "file").flatMap((f) => ["--file", f]),
285
+ ];
286
+ const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven, personCommand(...words));
277
287
  if (preview)
278
288
  return preview;
279
289
  }
290
+ if (!driven && !op.readOnly)
291
+ ctx.approved = { guarded: false };
280
292
  const client = await ctx.client();
281
293
  const result = await callOperation(ctx, client, doc, op, args);
282
294
  if (output) {
@@ -296,7 +308,7 @@ export const api = {
296
308
  return { data, text };
297
309
  },
298
310
  };
299
- async function previewUnlessConfirmed(ctx, input, doc, op, args, driven) {
311
+ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, command) {
300
312
  const given = input.options.confirm;
301
313
  if (given === true)
302
314
  throw confirmTokenRequired("api");
@@ -304,20 +316,23 @@ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven) {
304
316
  const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
305
317
  const session = await ctx.session();
306
318
  const token = confirmToken({ url: session.url, tenant: session.tenant }, "api", { request, files });
307
- if (typeof given === "string" && given === token)
319
+ const route = personRoute(ctx, driven);
320
+ if (typeof given === "string" && given === token) {
321
+ await personApproves(ctx, driven, { tool: "api", what: `Send ${request.method} ${request.path} (${op.alias}).`, command });
308
322
  return undefined;
323
+ }
309
324
  const stale = typeof given === "string" && given !== "";
310
325
  const bare = given === "" && driven.by === "agent";
311
- const confirm = driven.by === "mcp"
312
- ? confirmWith("api", token)
313
- : `Show the person this request, then run the same command again with --confirm ${token} to send exactly it.`;
326
+ const confirm = route === "client" ? confirmThroughClient("api", token) : confirmInTerminal(command);
314
327
  const target = await actingTarget(ctx);
315
328
  const shown = { operation: op.alias, ...request, ...(files.length ? { files } : {}), target, sent: false };
316
329
  const lines = [`Would send ${request.method} ${request.path}. Nothing was sent.`, targetLine(target)];
317
330
  if (stale)
318
331
  lines.push("The confirm token is not this request's: the request changed since its preview, or the token is another one's.");
319
332
  if (bare && driven.by === "agent")
320
- lines.push("--confirm alone does not send it when a coding agent runs cavelon.");
333
+ lines.push("A coding agent cannot send it: the person sends it from their own terminal.");
334
+ if (op.confirmation)
335
+ lines.push(`The instance asks for the person's confirmation of it (x-cavelon-confirmation)${op.confirmationWhen ? `: ${op.confirmationWhen}` : ""}`);
321
336
  if (Object.keys(request.query).length)
322
337
  lines.push(`Query: ${JSON.stringify(request.query)}`);
323
338
  if (Object.keys(request.headers).length)
@@ -328,7 +343,15 @@ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven) {
328
343
  lines.push(`File: ${f.field} = ${f.file}`);
329
344
  lines.push(confirm);
330
345
  return {
331
- data: { ...shown, confirm_token: token, confirm, ...(stale ? { token_mismatch: true } : {}), ...(bare ? { token_required: true } : {}) },
346
+ data: {
347
+ ...shown,
348
+ ...(route === "client" ? { confirm_token: token } : {}),
349
+ confirm,
350
+ needs_person: route,
351
+ ...(op.confirmation ? { instance_confirmation: op.confirmationWhen ?? true } : {}),
352
+ ...(stale ? { token_mismatch: true } : {}),
353
+ ...(bare ? { token_required: true } : {}),
354
+ },
332
355
  text: lines.join("\n"),
333
356
  ...(stale ? { exitCode: ExitCode.conflict } : bare ? { exitCode: ExitCode.needsAction } : {}),
334
357
  };
@@ -440,6 +463,7 @@ export const apiDescribe = {
440
463
  read_only: op.readOnly,
441
464
  person_only: kept ? { source: kept.source, reason: kept.reason ?? null, hint: kept.hint } : null,
442
465
  secret_fields: secrets,
466
+ confirmation: op.confirmation ? { required: true, when: op.confirmationWhen ?? null } : null,
443
467
  tags: op.tags,
444
468
  summary: op.summary ?? null,
445
469
  description: op.description ? clip(op.description, 1500) : null,
@@ -463,6 +487,10 @@ export const apiDescribe = {
463
487
  }
464
488
  if (secrets.length)
465
489
  lines.push(`Secret values (x-cavelon-secret): ${secrets.join(", ")}. A person enters them; an agent leaves them out.`);
490
+ if (op.confirmation) {
491
+ lines.push(`A person confirms it (x-cavelon-confirmation)${op.confirmationWhen ? `: ${op.confirmationWhen}` : "."} cavelon asks the instance for the ` +
492
+ "confirmation once the person approved the call: in their own terminal, or in the MCP client's dialog.");
493
+ }
466
494
  if (data.description && data.description !== op.summary)
467
495
  lines.push("", data.description);
468
496
  if (data.parameters.length) {
@@ -1,5 +1,5 @@
1
1
  import { parseDuration, positional, stringOption } from "../command.js";
2
- import { confirmation, confirmTokenRequired } from "../confirm-token.js";
2
+ import { confirmation, confirmTokenRequired, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
3
3
  import { named, readDefaultRoute } from "../default-route.js";
4
4
  import { CavelonError, ExitCode, usageError } from "../errors.js";
5
5
  import { clip } from "../format.js";
@@ -114,7 +114,8 @@ export const deactivate = {
114
114
  "through its readiness gate). Without --confirm nothing changes: the preview says what would stop. Show it to a person\n" +
115
115
  "and confirm only with their yes. The tenant's default route is refused before anything is sent: make another solution\n" +
116
116
  "the default first (`cavelon harness default <solution>`). An instance that publishes no deactivate route is said so; a\n" +
117
- "person deactivates in the Admin there.",
117
+ "person deactivates in the Admin there.\n" +
118
+ PERSON_CONFIRMS_HELP,
118
119
  readOnly: false,
119
120
  destructive: true,
120
121
  idempotent: true,
@@ -160,7 +161,9 @@ export const deactivate = {
160
161
  });
161
162
  }
162
163
  const confirmCommand = cavelonCommand("deactivate", "--harness", harness.slug, "--confirm");
163
- const gate = await confirmation(ctx, input, "deactivate", { harness: harness.id, status: harness.status });
164
+ const gate = await confirmation(ctx, input, "deactivate", { harness: harness.id, status: harness.status }, {
165
+ person: { what: `Deactivate ${named(harness)}: it goes inactive and out of live traffic.`, words: ["deactivate", "--harness", harness.slug, "--confirm"] },
166
+ });
164
167
  if (!gate.confirmed) {
165
168
  const known = route?.known ? "" : " (this instance does not say which solution is the default route)";
166
169
  return {
@@ -1,5 +1,6 @@
1
1
  import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption } from "../command.js";
2
2
  import { CavelonError, ExitCode, usageError } from "../errors.js";
3
+ import { connectorOffer, isProcedureCall } from "../database-queries.js";
3
4
  import { requireFeature } from "../features.js";
4
5
  import { clip, keyValues, moreHint, table } from "../format.js";
5
6
  import { callStable } from "../invoke.js";
@@ -8,26 +9,30 @@ import { isUuid } from "../session.js";
8
9
  const FEATURE = "database_connector_enabled";
9
10
  const DOCS_PAGE = "administration/database-connectors";
10
11
  const connectorOn = (ctx) => requireFeature(ctx, FEATURE, "database_connector_disabled", "the database connector");
11
- function ownerOnly(error, what) {
12
+ function withPermissionHint(error, hint) {
12
13
  if (!(error instanceof CavelonError) || error.status !== 403)
13
14
  return error;
14
15
  return new CavelonError(error.exitCode, {
15
16
  code: error.code,
16
17
  status: error.status,
17
18
  message: error.message,
18
- hint: `${what} needs the tenant Owner's permission (database_connectors.test), or a superadmin in the Admin; the roles that read the connections do not hold it. ` +
19
- `\`${cavelonCommand("whoami")}\` shows the token's role.`,
19
+ hint: `${hint} \`${cavelonCommand("whoami")}\` shows the token's role.`,
20
20
  docs: error.docs,
21
21
  });
22
22
  }
23
- async function listConnections(ctx) {
23
+ const ownerOnly = (error, what) => withPermissionHint(error, `${what} needs the tenant Owner's permission (database_connectors.test), or a superadmin in the Admin; the roles that read the connections do not hold it.`);
24
+ const viewerOnly = (error) => withPermissionHint(error, "Reading the database connector needs database_connectors.view, which the tenant roles that see tools hold, and a superadmin in Tenant mode.");
25
+ async function read(ctx, path, what, query) {
24
26
  await connectorOn(ctx);
25
- return callStable(ctx, "GET", "/api/v1/database-connectors/connections", "database connections");
26
- }
27
- async function listQueries(ctx, connectionId) {
28
- await connectorOn(ctx);
29
- return callStable(ctx, "GET", "/api/v1/database-connectors/queries", "database queries", { query: { connection_id: connectionId } });
27
+ try {
28
+ return await callStable(ctx, "GET", path, what, { query });
29
+ }
30
+ catch (error) {
31
+ throw viewerOnly(error);
32
+ }
30
33
  }
34
+ const listConnections = (ctx) => read(ctx, "/api/v1/database-connectors/connections", "database connections");
35
+ const listQueries = (ctx, connectionId) => read(ctx, "/api/v1/database-connectors/queries", "database queries", { connection_id: connectionId });
31
36
  async function resolveConnection(ctx, ref) {
32
37
  const all = await listConnections(ctx);
33
38
  const hit = all.find((c) => c.id === ref.toLowerCase()) ?? all.find((c) => c.name === ref) ?? all.find((c) => c.name.toLowerCase() === ref.toLowerCase());
@@ -47,7 +52,7 @@ async function resolveQuery(ctx, ref) {
47
52
  }
48
53
  catch (error) {
49
54
  if (!(error instanceof CavelonError && error.status === 404))
50
- throw error;
55
+ throw viewerOnly(error);
51
56
  }
52
57
  }
53
58
  const all = await listQueries(ctx);
@@ -64,6 +69,42 @@ function connectionView(c) {
64
69
  const { ca_certificate_pem: pem, ...rest } = c;
65
70
  return { ...rest, ca_certificate_set: Boolean(pem) };
66
71
  }
72
+ const DAY_MS = 86_400_000;
73
+ const EXPIRY_WARNING_DAYS = 30;
74
+ const day = (iso) => iso.slice(0, 10);
75
+ function expiryWarnings(connections, now) {
76
+ const warnings = [];
77
+ for (const c of connections) {
78
+ for (const cert of c.ca_certificates ?? []) {
79
+ const until = Date.parse(cert.not_after);
80
+ if (Number.isNaN(until))
81
+ continue;
82
+ const days = Math.floor((until - now.getTime()) / DAY_MS);
83
+ if (days >= EXPIRY_WARNING_DAYS)
84
+ continue;
85
+ const when = until <= now.getTime()
86
+ ? `expired on ${day(cert.not_after)}`
87
+ : `expires on ${day(cert.not_after)} (in ${days === 0 ? "less than a day" : `${days} day${days === 1 ? "" : "s"}`})`;
88
+ warnings.push(`The CA certificate "${cert.subject}" of the database connection "${c.name}" ${when}: from then its TLS check fails, and with it the connection's queries. ` +
89
+ `A superadmin uploads the renewed CA in the Admin; then the tenant Owner tests the connection again: ${cavelonCommand("db", "test", c.name)}`);
90
+ }
91
+ }
92
+ return warnings;
93
+ }
94
+ function caLines(connections) {
95
+ const lines = [];
96
+ for (const c of connections) {
97
+ if (c.ca_certificates?.length) {
98
+ for (const cert of c.ca_certificates)
99
+ lines.push(`${c.name}: ${cert.subject}, valid until ${day(cert.not_after)}`);
100
+ }
101
+ else if (!c.ca_certificates && c.ca_certificate_sha256?.length) {
102
+ const n = c.ca_certificate_sha256.length;
103
+ lines.push(`${c.name}: a CA is set (${n} certificate${n === 1 ? "" : "s"}); this instance does not publish their subject or expiry`);
104
+ }
105
+ }
106
+ return lines.length ? ["", "", "CA certificates:", ...lines] : [];
107
+ }
67
108
  function lastTest(c) {
68
109
  if (!c.last_test_at)
69
110
  return "never";
@@ -89,12 +130,66 @@ function explainLine(codes) {
89
130
  return "";
90
131
  return `\n\nWhat a code means: ${cavelonCommand("explain", fill("code"))} (${distinct.slice(0, 8).join(", ")})`;
91
132
  }
133
+ const refusalOf = (name, refusal) => `${name} (${refusal.code}${refusal.message ? `: ${clip(refusal.message, 200)}` : ""})`;
134
+ function firewallSentence(offer) {
135
+ const { egress_ips: ips, connections_per_process: perProcess } = offer.network;
136
+ const pool = `Each process of the instance that runs agents opens at most ${perProcess} connection${perProcess === 1 ? "" : "s"} per database connection.`;
137
+ if (!ips.length) {
138
+ return ("The instance's operator has named no addresses it connects from, so it does not say what to allowlist: " +
139
+ `ask the operator before opening the database's firewall. ${pool}`);
140
+ }
141
+ const these = ips.length === 1 ? "this address" : "these addresses";
142
+ return `Allow ${ips.join(", ")} through the database's firewall, on the database's port: the instance connects to a customer's database only from ${these}. ${pool}`;
143
+ }
144
+ export const dbInstance = {
145
+ name: "db instance",
146
+ summary: "What this instance offers for database connections: the dialects it runs, and the addresses a database's firewall lets in.",
147
+ description: "Read it before a database connection is set up: a connection of a dialect the instance does not run can be saved, but\n" +
148
+ "its test and queries answer unavailable, and the customer's database must let the instance's egress addresses in. An\n" +
149
+ "instance older than this route says only its dialects, in its capabilities.",
150
+ readOnly: true,
151
+ idempotent: true,
152
+ mcpTool: "db_instance",
153
+ examples: ["cavelon db instance", "cavelon db instance --json"],
154
+ async run(ctx) {
155
+ let offer;
156
+ try {
157
+ offer = await read(ctx, "/api/v1/database-connectors/instance", "the database connector's dialects and network");
158
+ }
159
+ catch (error) {
160
+ const unpublished = error instanceof CavelonError && (error.code === "operation_unavailable" || error.status === 404);
161
+ if (!unpublished)
162
+ throw error;
163
+ const dialects = connectorOffer(await (await ctx.contracts()).capabilities()).dialects;
164
+ return {
165
+ data: { published: false, runnable_dialects: dialects ?? null, network: null },
166
+ text: "This instance does not publish which addresses it connects to databases from (it is older than that); its operator knows them." +
167
+ (dialects ? `\nDialects it runs: ${dialects.join(", ") || "none"}` : ""),
168
+ };
169
+ }
170
+ const firewall = firewallSentence(offer);
171
+ return {
172
+ data: { published: true, ...offer, firewall },
173
+ text: [
174
+ keyValues([
175
+ ["dialects", offer.runnable_dialects.join(", ") || "none"],
176
+ ["egress_ips", offer.network.egress_ips.join(", ") || "none named"],
177
+ ["connections_per_process", offer.network.connections_per_process],
178
+ ]),
179
+ "",
180
+ firewall,
181
+ ...(offer.runnable_dialects.length ? [] : ["", "This instance runs no database dialect: a connection can be saved, but its test and queries answer unavailable."]),
182
+ ].join("\n"),
183
+ };
184
+ },
185
+ };
92
186
  export const dbConnections = {
93
187
  name: "db connections",
94
- summary: "The tenant's database connections: dialect, target, TLS mode, last test and query count; never a password.",
188
+ summary: "The tenant's database connections: dialect, target, TLS mode, CA certificates, last test and query count; never a password.",
95
189
  description: "A superadmin creates and changes connections in the Admin; a token reads them. A package names a query's connection by\n" +
96
190
  "name and dialect, so the same name serves in every tenant and environment. A query tool is ready for agents only while\n" +
97
- "its connection is enabled and its last test passed; the tenant Owner runs the test with `cavelon db test <connection>`.",
191
+ "its connection is enabled and its last test passed; the tenant Owner runs the test with `cavelon db test <connection>`.\n" +
192
+ `It warns of a CA certificate that has expired or expires within ${EXPIRY_WARNING_DAYS} days.`,
98
193
  readOnly: true,
99
194
  idempotent: true,
100
195
  mcpTool: "db_connections",
@@ -102,7 +197,10 @@ export const dbConnections = {
102
197
  examples: ["cavelon db connections", "cavelon db connections --json"],
103
198
  async run(ctx, input) {
104
199
  const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
105
- const page = pageOf((await listConnections(ctx)).map(connectionView), limit, stringOption(input, "cursor"));
200
+ const all = await listConnections(ctx);
201
+ for (const warning of expiryWarnings(all, ctx.io.now()))
202
+ ctx.warn(warning);
203
+ const page = pageOf(all.map(connectionView), limit, stringOption(input, "cursor"));
106
204
  const rows = page.items.map((c) => {
107
205
  const conn = c;
108
206
  return {
@@ -117,12 +215,21 @@ export const dbConnections = {
117
215
  };
118
216
  });
119
217
  const untested = page.items.filter((c) => c.last_test_outcome !== "ok").map((c) => String(c.name));
218
+ const connections = page.items;
219
+ const refused = connections.filter((c) => c.query_enable_refusal?.code);
220
+ const procedureRefused = connections.filter((c) => c.procedure_call_refusal?.code);
120
221
  return {
121
222
  data: page,
122
223
  text: (table(rows, ["name", "dialect", "target", "tls", "enabled", "last_test", "queries", "id"]) ||
123
224
  `No database connections. A superadmin creates one in the Admin (\`${cavelonCommand("docs", "get", DOCS_PAGE)}\` says who does what).`) +
225
+ caLines(connections).join("\n") +
124
226
  moreHint(page.next_cursor, cavelonCommand("db", "connections")) +
125
- (untested.length ? `\n\nNot tested successfully: ${untested.join(", ")}; its queries are not ready for agents. The Owner tests one with: ${cavelonCommand("db", "test", fill("connection"))}` : ""),
227
+ (untested.length ? `\n\nNot tested successfully: ${untested.join(", ")}; its queries are not ready for agents. The Owner tests one with: ${cavelonCommand("db", "test", fill("connection"))}` : "") +
228
+ (refused.length ? `\n\nQueries cannot be enabled on: ${refused.map((c) => refusalOf(c.name, c.query_enable_refusal)).join("; ")}` : "") +
229
+ (procedureRefused.length
230
+ ? `\n\nStored-procedure queries (EXEC) cannot be saved or run on: ${procedureRefused.map((c) => refusalOf(c.name, c.procedure_call_refusal)).join("; ")}`
231
+ : "") +
232
+ explainLine([...refused.map((c) => c.query_enable_refusal.code), ...procedureRefused.map((c) => c.procedure_call_refusal.code)]),
126
233
  };
127
234
  },
128
235
  };
@@ -146,6 +253,9 @@ export const dbQueries = {
146
253
  const ref = positional(input, "query");
147
254
  if (ref) {
148
255
  const q = await resolveQuery(ctx, ref);
256
+ const connection = (await listConnections(ctx)).find((c) => c.id === q.connection_id);
257
+ const procedure = isProcedureCall(q.sql_text, connection?.dialect);
258
+ const refusal = procedure ? connection?.procedure_call_refusal : undefined;
149
259
  const text = [
150
260
  keyValues([
151
261
  ["query", `${q.slug} (${q.name})`],
@@ -161,11 +271,19 @@ export const dbQueries = {
161
271
  "SQL:",
162
272
  q.sql_text,
163
273
  "",
274
+ ...(procedure
275
+ ? [
276
+ "It calls a stored procedure: the model gets its first result set. It runs only while the connection's last test found no write privileges,",
277
+ "and the instance reads the procedure's definition at every save, enable and test run and refuses one that writes.",
278
+ ...(refusal?.code ? [`Not now on ${connection.name}: ${refusal.code}${refusal.message ? ` (${clip(refusal.message, 200)})` : ""}`] : []),
279
+ "",
280
+ ]
281
+ : []),
164
282
  q.parameters.length ? table(parameterRows(q.parameters), ["name", "filled_by", "type", "required", "constraints", "description"]) : "No parameters.",
165
283
  "",
166
284
  `Its runs (no values, no rows): ${cavelonCommand("db", "runs", q.slug)}`,
167
285
  ].join("\n");
168
- return { data: q, text };
286
+ return { data: q, text: text + explainLine([refusal?.code]) };
169
287
  }
170
288
  const connectionRef = stringOption(input, "connection");
171
289
  const connection = connectionRef ? await resolveConnection(ctx, connectionRef) : undefined;
@@ -214,6 +332,8 @@ export const dbRuns = {
214
332
  const page = await callStable(ctx, "GET", "/api/v1/database-connectors/queries/{query_id}/runs", "database query runs", {
215
333
  params: { query_id: [q.id] },
216
334
  query: { limit, offset },
335
+ }).catch((error) => {
336
+ throw viewerOnly(error);
217
337
  });
218
338
  const items = page.items ?? [];
219
339
  const next = typeof page.next_offset === "number" ? String(page.next_offset) : null;
@@ -241,7 +361,12 @@ export const dbTest = {
241
361
  description: "Needs the tenant Owner's permission (database_connectors.test). The result becomes the connection's last test: a query tool\n" +
242
362
  "is ready for agents only while it passed, and a package's query needs a tested connection of its name to import. A failed\n" +
243
363
  "step names its code; `cavelon explain <code>` says how to fix it. A finding under write_privileges means the database user\n" +
244
- "can write: ask the database administrator for a read-only user.",
364
+ "can write: ask the database administrator for a read-only user. On SQL Server, which has no read-only transaction, the\n" +
365
+ "connection's queries then do not run (write_privileges_unacknowledged) until its login may only read or a superadmin\n" +
366
+ "acknowledges the write privileges in the Admin; a stored-procedure query (EXEC) runs only on a login the test found\n" +
367
+ "without write privileges, acknowledged or not. A passing test on SQL Server also reads again the procedure each\n" +
368
+ "stored-procedure query calls, and lists those that no longer pass the instance's check (procedure_findings); they stay\n" +
369
+ "as they are, and their next save or enable is refused until the procedure only reads again.",
245
370
  readOnly: false,
246
371
  idempotent: true,
247
372
  mcpEffect: "Runs the connection test on the instance and stores its outcome as the connection's last test; changes no setting.",
@@ -263,19 +388,51 @@ export const dbTest = {
263
388
  }
264
389
  const ok = result.outcome === "ok";
265
390
  const steps = (result.steps ?? []).map((s) => ({ step: s.name, status: s.status, code: s.code ?? null, message: s.driver_message ? clip(s.driver_message, 160) : null }));
391
+ const findings = (Array.isArray(result.procedure_findings) ? result.procedure_findings : []).map((f) => ({
392
+ query: f.slug ?? f.query_id ?? "?",
393
+ code: f.code ?? null,
394
+ message: f.message ? clip(f.message, 200) : null,
395
+ }));
396
+ if (findings.length) {
397
+ ctx.warn(`The test passed, but the procedure of ${findings.length === 1 ? "one stored-procedure query" : `${findings.length} stored-procedure queries`} ` +
398
+ `(${findings.map((f) => f.query).join(", ")}) no longer passes the instance's check: ${findings.length === 1 ? "it stays" : "they stay"} as ${findings.length === 1 ? "it is" : "they are"}, ` +
399
+ "and a save or enable is refused until the procedure only reads again.");
400
+ }
266
401
  const text = [
267
402
  `Connection "${connection.name}" (${connection.dialect}): ${ok ? "test passed" : `test failed (${result.outcome})`}, ${result.duration_ms} ms.`,
268
403
  table(steps, ["step", "status", "code", ...(steps.some((s) => s.message) ? ["message"] : [])], 80),
269
404
  ...(result.server_version ? [`server: ${result.server_version}`] : []),
270
405
  ...(result.write_privileges ? [`write privileges: ${clip(JSON.stringify(result.write_privileges), 300)}`] : []),
406
+ ...(findings.length
407
+ ? ["", "Stored-procedure queries whose procedure no longer passes (they stay as they are; a save or enable is refused):", table(findings, ["query", "code", "message"], 80)]
408
+ : []),
271
409
  ].join("\n");
272
410
  return {
273
411
  data: { connection: { id: connection.id, name: connection.name, dialect: connection.dialect }, ...result },
274
- text: text + explainLine(steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code)),
412
+ text: text + explainLine([...steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code), ...findings.map((f) => f.code)]),
275
413
  exitCode: ok ? ExitCode.ok : ExitCode.validation,
276
414
  };
277
415
  },
278
416
  };
417
+ const RUN_REFUSAL_STEPS = {
418
+ database_connection_untested: (q) => `The tenant Owner tests the connection first: ${cavelonCommand("db", "test", q.connection_name)}`,
419
+ write_privileges_block_procedure: (q) => `The connection's login needs to lose its write privileges (a database administrator's change), then the tenant Owner tests it again: ${cavelonCommand("db", "test", q.connection_name)}`,
420
+ procedure_definition_unreadable: () => "The connection's login needs VIEW DEFINITION on the procedure, and the procedure must not be created WITH ENCRYPTION.",
421
+ procedure_definition_writes: () => "The procedure must only read (temporary tables and table variables are fine), or a superadmin writes the query as a SELECT.",
422
+ };
423
+ function refusedRun(error, query) {
424
+ if (!(error instanceof CavelonError) || error.status !== 409)
425
+ return error;
426
+ const step = RUN_REFUSAL_STEPS[error.code];
427
+ return new CavelonError(error.exitCode, {
428
+ code: error.code,
429
+ status: error.status,
430
+ message: error.message,
431
+ hint: [error.hint, step?.(query), `\`${cavelonCommand("explain", error.code)}\` says more.`].filter(Boolean).join(" "),
432
+ docs: error.docs,
433
+ details: error.details,
434
+ });
435
+ }
279
436
  function typed(parameter, raw) {
280
437
  const type = parameter?.type ?? "string";
281
438
  if (type === "integer" || type === "number") {
@@ -314,7 +471,11 @@ export const dbTestRun = {
314
471
  description: "Needs the tenant Owner's permission (database_connectors.test); it reads the customer's own data. Give each parameter\n" +
315
472
  "with --value name=value, those the platform fills from the signed-in visitor (end_user.*) too: that is how an\n" +
316
473
  "identity-scoped query is checked for one customer. The instance records the run (counts only) and audits it with your\n" +
317
- "name; the rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.",
474
+ "name; the rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.\n" +
475
+ "A stored-procedure query (SQL Server) shows the procedure's first result set; the instance refuses its run (exit 4)\n" +
476
+ "while the connection's last test found write privileges or the procedure's definition writes or cannot be read, and\n" +
477
+ "a run whose procedure ended the connector's transaction comes back with a notice saying so and whether the query was\n" +
478
+ "switched off.",
318
479
  readOnly: false,
319
480
  idempotent: true,
320
481
  mcpEffect: "Runs the saved query once on the instance; it leaves a run record (counts only) and an audit entry, and changes no setting.",
@@ -339,7 +500,7 @@ export const dbTestRun = {
339
500
  });
340
501
  }
341
502
  catch (error) {
342
- throw ownerOnly(error, "A test run");
503
+ throw refusedRun(ownerOnly(error, "A test run"), query);
343
504
  }
344
505
  const ok = result.outcome === "ok" && !result.error_code;
345
506
  const columns = result.columns ?? [];
@@ -351,6 +512,7 @@ export const dbTestRun = {
351
512
  ["outcome", result.error_code ? `${result.outcome} (${result.error_code}${result.sqlstate ? `, SQLSTATE ${result.sqlstate}` : ""})` : result.outcome],
352
513
  ["rows", ok ? `${result.returned_rows ?? rows.length} returned of ${result.row_count ?? "?"}${result.truncated ? ", truncated for the model" : ""}` : undefined],
353
514
  ["duration_ms", result.duration_ms],
515
+ ["notice", result.notice || undefined],
354
516
  ]),
355
517
  "",
356
518
  "What the model sees:",