@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.
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 } 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,65 @@ 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
+ function firewallSentence(offer) {
134
+ const { egress_ips: ips, connections_per_process: perProcess } = offer.network;
135
+ const pool = `Each process of the instance that runs agents opens at most ${perProcess} connection${perProcess === 1 ? "" : "s"} per database connection.`;
136
+ if (!ips.length) {
137
+ return ("The instance's operator has named no addresses it connects from, so it does not say what to allowlist: " +
138
+ `ask the operator before opening the database's firewall. ${pool}`);
139
+ }
140
+ const these = ips.length === 1 ? "this address" : "these addresses";
141
+ 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}`;
142
+ }
143
+ export const dbInstance = {
144
+ name: "db instance",
145
+ summary: "What this instance offers for database connections: the dialects it runs, and the addresses a database's firewall lets in.",
146
+ 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" +
147
+ "its test and queries answer unavailable, and the customer's database must let the instance's egress addresses in. An\n" +
148
+ "instance older than this route says only its dialects, in its capabilities.",
149
+ readOnly: true,
150
+ idempotent: true,
151
+ mcpTool: "db_instance",
152
+ examples: ["cavelon db instance", "cavelon db instance --json"],
153
+ async run(ctx) {
154
+ let offer;
155
+ try {
156
+ offer = await read(ctx, "/api/v1/database-connectors/instance", "the database connector's dialects and network");
157
+ }
158
+ catch (error) {
159
+ const unpublished = error instanceof CavelonError && (error.code === "operation_unavailable" || error.status === 404);
160
+ if (!unpublished)
161
+ throw error;
162
+ const dialects = connectorOffer(await (await ctx.contracts()).capabilities()).dialects;
163
+ return {
164
+ data: { published: false, runnable_dialects: dialects ?? null, network: null },
165
+ text: "This instance does not publish which addresses it connects to databases from (it is older than that); its operator knows them." +
166
+ (dialects ? `\nDialects it runs: ${dialects.join(", ") || "none"}` : ""),
167
+ };
168
+ }
169
+ const firewall = firewallSentence(offer);
170
+ return {
171
+ data: { published: true, ...offer, firewall },
172
+ text: [
173
+ keyValues([
174
+ ["dialects", offer.runnable_dialects.join(", ") || "none"],
175
+ ["egress_ips", offer.network.egress_ips.join(", ") || "none named"],
176
+ ["connections_per_process", offer.network.connections_per_process],
177
+ ]),
178
+ "",
179
+ firewall,
180
+ ...(offer.runnable_dialects.length ? [] : ["", "This instance runs no database dialect: a connection can be saved, but its test and queries answer unavailable."]),
181
+ ].join("\n"),
182
+ };
183
+ },
184
+ };
92
185
  export const dbConnections = {
93
186
  name: "db connections",
94
- summary: "The tenant's database connections: dialect, target, TLS mode, last test and query count; never a password.",
187
+ summary: "The tenant's database connections: dialect, target, TLS mode, CA certificates, last test and query count; never a password.",
95
188
  description: "A superadmin creates and changes connections in the Admin; a token reads them. A package names a query's connection by\n" +
96
189
  "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>`.",
190
+ "its connection is enabled and its last test passed; the tenant Owner runs the test with `cavelon db test <connection>`.\n" +
191
+ `It warns of a CA certificate that has expired or expires within ${EXPIRY_WARNING_DAYS} days.`,
98
192
  readOnly: true,
99
193
  idempotent: true,
100
194
  mcpTool: "db_connections",
@@ -102,7 +196,10 @@ export const dbConnections = {
102
196
  examples: ["cavelon db connections", "cavelon db connections --json"],
103
197
  async run(ctx, input) {
104
198
  const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
105
- const page = pageOf((await listConnections(ctx)).map(connectionView), limit, stringOption(input, "cursor"));
199
+ const all = await listConnections(ctx);
200
+ for (const warning of expiryWarnings(all, ctx.io.now()))
201
+ ctx.warn(warning);
202
+ const page = pageOf(all.map(connectionView), limit, stringOption(input, "cursor"));
106
203
  const rows = page.items.map((c) => {
107
204
  const conn = c;
108
205
  return {
@@ -117,12 +214,18 @@ export const dbConnections = {
117
214
  };
118
215
  });
119
216
  const untested = page.items.filter((c) => c.last_test_outcome !== "ok").map((c) => String(c.name));
217
+ const refused = page.items.filter((c) => c.query_enable_refusal?.code);
120
218
  return {
121
219
  data: page,
122
220
  text: (table(rows, ["name", "dialect", "target", "tls", "enabled", "last_test", "queries", "id"]) ||
123
221
  `No database connections. A superadmin creates one in the Admin (\`${cavelonCommand("docs", "get", DOCS_PAGE)}\` says who does what).`) +
222
+ caLines(page.items).join("\n") +
124
223
  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"))}` : ""),
224
+ (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"))}` : "") +
225
+ (refused.length
226
+ ? `\n\nQueries cannot be enabled on: ${refused.map((c) => `${c.name} (${c.query_enable_refusal.code}${c.query_enable_refusal.message ? `: ${clip(c.query_enable_refusal.message, 200)}` : ""})`).join("; ")}` +
227
+ explainLine(refused.map((c) => c.query_enable_refusal.code))
228
+ : ""),
126
229
  };
127
230
  },
128
231
  };
@@ -214,6 +317,8 @@ export const dbRuns = {
214
317
  const page = await callStable(ctx, "GET", "/api/v1/database-connectors/queries/{query_id}/runs", "database query runs", {
215
318
  params: { query_id: [q.id] },
216
319
  query: { limit, offset },
320
+ }).catch((error) => {
321
+ throw viewerOnly(error);
217
322
  });
218
323
  const items = page.items ?? [];
219
324
  const next = typeof page.next_offset === "number" ? String(page.next_offset) : null;
@@ -241,7 +346,9 @@ export const dbTest = {
241
346
  description: "Needs the tenant Owner's permission (database_connectors.test). The result becomes the connection's last test: a query tool\n" +
242
347
  "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
348
  "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.",
349
+ "can write: ask the database administrator for a read-only user. On SQL Server, which has no read-only transaction, the\n" +
350
+ "connection's queries then do not run (write_privileges_unacknowledged) until its login may only read or a superadmin\n" +
351
+ "acknowledges the write privileges in the Admin.",
245
352
  readOnly: false,
246
353
  idempotent: true,
247
354
  mcpEffect: "Runs the connection test on the instance and stores its outcome as the connection's last test; changes no setting.",
@@ -14,7 +14,7 @@ import { activate, apply, explain, pull, validate } from "./solution.js";
14
14
  import { schema } from "./schema.js";
15
15
  import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
16
16
  import { kbUpload, testRun, trace } from "./work.js";
17
- import { dbConnections, dbQueries, dbRuns, dbTest, dbTestRun } from "./db.js";
17
+ import { dbConnections, dbInstance, dbQueries, dbRuns, dbTest, dbTestRun } from "./db.js";
18
18
  import { secretsDelete, secretsList, secretsSet, variablesDelete, variablesGet, variablesList, variablesSet } from "./values.js";
19
19
  import { loopCancel, loopIterations, loopPause, loopResume, loopStart, loopWatch, triggerIdentity } from "./loops.js";
20
20
  import { artifactsExport, sandboxActivity, sandboxCat, sandboxFiles, sandboxList, sandboxLogs, sandboxReceipt, sandboxRefresh, sandboxSeed, sandboxValidate, } from "./sandboxes.js";
@@ -103,6 +103,7 @@ export const COMMANDS = [
103
103
  kbUpload,
104
104
  testRun,
105
105
  trace,
106
+ dbInstance,
106
107
  dbConnections,
107
108
  dbQueries,
108
109
  dbRuns,
@@ -1,7 +1,7 @@
1
1
  import { originText } from "../capacity.js";
2
2
  import { positional } from "../command.js";
3
3
  import { CavelonError, ExitCode, usageError } from "../errors.js";
4
- import { confirmation } from "../confirm-token.js";
4
+ import { confirmation, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
5
5
  import { callOperation, openapiOrWarn, workflowOperation } from "../invoke.js";
6
6
  import { changedBy, docsPage, formatValue, isOperatorChange, LIMIT_ABOVE_CEILING, limitRef, quotaSetting, readLimits, } from "../limits.js";
7
7
  import { deref, jsonBodySchema, operationForPath, validateBody } from "../openapi.js";
@@ -471,7 +471,8 @@ export const limitsSet = {
471
471
  "An operator's change (a run cap) is sent only with a personal access token in Platform mode of a role it names, without\n" +
472
472
  "X-Tenant-Id; --tenant <id|slug> then sets one tenant's own run cap. An environment or licence limit, a value out of bounds,\n" +
473
473
  "an instance that does not publish how to change the limit, and a credential without the permission or the role are refused\n" +
474
- "before anything is sent. Propose the change to the person; never raise a limit on your own.",
474
+ "before anything is sent. Propose the change to the person; never raise a limit on your own.\n" +
475
+ PERSON_CONFIRMS_HELP,
475
476
  readOnly: false,
476
477
  destructive: true,
477
478
  idempotent: true,
@@ -491,7 +492,6 @@ export const limitsSet = {
491
492
  examples: [
492
493
  "cavelon limits set kb_upload_max_file_size_mb 50",
493
494
  "cavelon limits set kb_upload_max_file_size_mb 50 --confirm",
494
- "cavelon limits set kb_upload_max_file_size_mb 50 --confirm <token>",
495
495
  "cavelon limits set rate_limit_chat_rpm none --confirm",
496
496
  "cavelon limits set monthly_inference_token_budget 2000000",
497
497
  "cavelon limits set monthly_processing_step_cap none --confirm",
@@ -576,6 +576,10 @@ export const limitsSet = {
576
576
  : `a credential with ${anyOf(change.permissions)} (a session, a personal access token, or an admin API key of the tenant)`;
577
577
  const gate = await confirmation(ctx, input, "limits_set", { key, value, previous: previous ?? null, operation }, {
578
578
  platform: operator ? (target.scope === "one_tenant" ? "tenant" : "outside") : undefined,
579
+ person: {
580
+ what: `${key}: ${from} → ${to}${target.scope === "platform" ? ", the platform's cap for every tenant without its own" : ""}.`,
581
+ words: ["limits", "set", key, argText(value), "--confirm"],
582
+ },
579
583
  });
580
584
  if (!gate.confirmed) {
581
585
  const confirm = gate.confirm(cavelonCommand("limits", "set", key, argText(value), "--confirm"));