@cavelon/cli 0.1.13 → 0.1.14

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/dist/access.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
1
2
  import { readPrincipal } from "./principal.js";
2
3
  import { cavelonCommand } from "./printed.js";
3
4
  export const ACTIVATE_PERMISSION = "harnesses.activate";
@@ -22,7 +23,16 @@ export const OPERATION_PERMISSIONS = {
22
23
  "POST /api/v1/sandboxes/{sandbox_id}/refresh-workspace": ["sandboxes.manage"],
23
24
  "POST /api/v1/sandboxes/{sandbox_id}/validate": ["sandboxes.manage"],
24
25
  "POST /api/v1/database-connectors/connections/{connection_id}/test": [["database_connectors.test", "database_connectors.manage"]],
26
+ "POST /api/v1/database-connectors/connections": ["database_connectors.manage"],
27
+ "PATCH /api/v1/database-connectors/connections/{connection_id}": ["database_connectors.manage"],
28
+ "DELETE /api/v1/database-connectors/connections/{connection_id}": ["database_connectors.manage"],
29
+ "POST /api/v1/database-connectors/connections/{connection_id}/schema": ["database_connectors.manage"],
30
+ "GET /api/v1/database-connectors/login-script": ["database_connectors.view"],
31
+ "GET /api/v1/database-connectors/connections/{connection_id}/login-script": ["database_connectors.view"],
25
32
  "POST /api/v1/database-connectors/queries/{query_id}/test-run": [["database_connectors.test", "database_connectors.manage"]],
33
+ "POST /api/v1/database-connectors/queries": ["database_connectors.manage"],
34
+ "PATCH /api/v1/database-connectors/queries/{query_id}": ["database_connectors.manage"],
35
+ "DELETE /api/v1/database-connectors/queries/{query_id}": ["database_connectors.manage"],
26
36
  "PUT /api/v1/variables/{name}": [SETTINGS_VALUES],
27
37
  "DELETE /api/v1/variables/{name}": [SETTINGS_VALUES],
28
38
  "PUT /api/v1/secrets/{name}": [SETTINGS_VALUES],
@@ -49,6 +59,7 @@ export function accessOf(principal) {
49
59
  complete,
50
60
  scopes: principal.api_key ? [...principal.api_key.scopes] : null,
51
61
  needsAPerson: principal.needs_a_person ?? [],
62
+ needsAPersonWhen: principal.needs_a_person_when ?? null,
52
63
  principal,
53
64
  };
54
65
  }
@@ -81,6 +92,10 @@ export function knownOperation(method, path) {
81
92
  export function operationAccess(access, operation) {
82
93
  if (!access)
83
94
  return { allowed: null };
95
+ const conditional = conditionalPersonOperation(access, operation);
96
+ return { ...unconditionalOperationAccess(access, operation), ...(conditional ? { personWhen: conditional.reason } : {}) };
97
+ }
98
+ function unconditionalOperationAccess(access, operation) {
84
99
  const [method, template] = operation.split(" ");
85
100
  const person = access.needsAPerson.find((o) => o.method === method && (o.path === template || pathMatches(o.path, template)));
86
101
  if (person)
@@ -92,6 +107,23 @@ export function operationAccess(access, operation) {
92
107
  const missing = needs.filter((need) => !held(need));
93
108
  return missing.length ? { allowed: false, missing: missing.map(needWords) } : { allowed: true };
94
109
  }
110
+ function conditionalPersonOperation(access, operation) {
111
+ const [method, path] = operation.split(" ");
112
+ return access?.needsAPersonWhen?.find(o => o.method === method && (o.path === path || (!path.includes("{") && pathMatches(o.path, path))));
113
+ }
114
+ export function requirePersonForIdentityChoice(access, operation, choice) {
115
+ if (access?.kind !== "api_key")
116
+ return;
117
+ const restriction = conditionalPersonOperation(access, operation);
118
+ if (!restriction)
119
+ return;
120
+ throw new CavelonError(ExitCode.needsAction, {
121
+ code: "key_needs_a_person",
122
+ message: `A tenant API key cannot ${choice}. Nothing was sent.`,
123
+ hint: `A person makes this identity choice in the Admin or with their own personal access token. The instance's condition: ${restriction.reason || "this request binds a person's identity"}. Ordinary query tests and runs using a suite's saved reader remain available.`,
124
+ details: { credential: "api_key", needs_a_person_when: true, reason: restriction.reason, method: restriction.method, path: restriction.path, sent: false },
125
+ });
126
+ }
95
127
  export function mayActivate(access) {
96
128
  if (!access)
97
129
  return null;
@@ -0,0 +1,68 @@
1
+ import { accessFor, requirePersonForIdentityChoice } from "./access.js";
2
+ import { stringOption } from "./command.js";
3
+ import { CavelonError, ExitCode, usageError, validationError } from "./errors.js";
4
+ import { workflowOperation } from "./invoke.js";
5
+ import { deref, jsonBodySchema, schemaErrors } from "./openapi.js";
6
+ import { cavelonCommand } from "./printed.js";
7
+ const READER_PERMISSIONS = ["knowledge_bases.view", "end_users.read"];
8
+ export const AS_CHAT_USER_OPTION = {
9
+ type: "string",
10
+ value: "<id>",
11
+ description: "Read knowledge and identity-bound queries as this tenant's Chat User; needs knowledge_bases.view and end_users.read.",
12
+ };
13
+ const chooseReader = "Choose a current Chat User of the acting tenant with `cavelon api list_chat_users -p tenant_id=<tenant_id>`; `cavelon whoami` shows the acting tenant and credential's permissions. Check email_verified for an email-bound query.";
14
+ export async function chatUserReader(ctx, input, path) {
15
+ const id = stringOption(input, "as-chat-user");
16
+ if (id === undefined)
17
+ return undefined;
18
+ if (!id.trim())
19
+ throw usageError("The Chat User id is empty.", chooseReader);
20
+ const { doc, op } = await workflowOperation(ctx, "POST", path, "Chat User reader selection");
21
+ const body = doc ? deref(doc, jsonBodySchema(op)) : undefined;
22
+ const mode = body?.properties?.reader_mode;
23
+ const user = body?.properties?.reader_chat_user_id;
24
+ if (!doc || !mode || !user || schemaErrors(doc, mode, "as_chat_user").length) {
25
+ throw new CavelonError(ExitCode.failure, {
26
+ code: "operation_unavailable",
27
+ message: "This instance does not publish Chat User reader selection for this request. Nothing was sent.",
28
+ hint: `The instance may be older than this feature${doc ? "" : ", or its OpenAPI is unavailable"}; ask its operator for reader support. Omit --as-chat-user to keep the usual reader; \`${cavelonCommand("status")}\` shows the instance version.`,
29
+ details: { sent: false },
30
+ });
31
+ }
32
+ if (schemaErrors(doc, user, id).length) {
33
+ throw validationError("The Chat User id does not match the instance's reader_chat_user_id schema.", { sent: false }, chooseReader);
34
+ }
35
+ const access = await accessFor(await ctx.client());
36
+ if (path === "/api/v1/test-suites/{suite_id}/runs") {
37
+ requirePersonForIdentityChoice(access, `POST ${path}`, "choose an as_chat_user reader for a test run");
38
+ }
39
+ if (path === "/api/v1/chat" && (access?.kind === "api_key" || (await ctx.session()).tokenKind === "api_key")) {
40
+ throw new CavelonError(ExitCode.unauthorized, {
41
+ code: "chat_user_reader_forbidden",
42
+ message: "A tenant API key cannot choose a Chat User reader for chat. Nothing was sent.",
43
+ hint: `Use a personal access token whose role holds ${READER_PERMISSIONS.join(" and ")}, or omit --as-chat-user for the usual reader. ${chooseReader}`,
44
+ details: { sent: false, credential: "api_key" },
45
+ });
46
+ }
47
+ const missing = access?.permissions ? READER_PERMISSIONS.filter((p) => !access.permissions.includes(p)) : [];
48
+ if (missing.length) {
49
+ throw new CavelonError(ExitCode.unauthorized, {
50
+ code: "chat_user_reader_forbidden",
51
+ message: `Reading as a Chat User needs ${missing.join(" and ")}, which this credential does not hold. Nothing was sent.`,
52
+ hint: `A person whose role holds ${READER_PERMISSIONS.join(" and ")} uses a credential with those permissions; a personal access token acts at most as its ceiling role. ${chooseReader}`,
53
+ details: { sent: false, missing_permissions: missing },
54
+ });
55
+ }
56
+ return { reader_mode: "as_chat_user", reader_chat_user_id: id };
57
+ }
58
+ export function chatUserReaderError(error, reader) {
59
+ if (!reader || !(error instanceof CavelonError))
60
+ return error;
61
+ if (error.status !== 403 && !(error.status === 422 && /reader|chat.?user/i.test(error.message)))
62
+ return error;
63
+ return new CavelonError(error.exitCode, {
64
+ code: error.code, status: error.status, message: error.message,
65
+ hint: [error.hint, error.status === 403 ? `Chat reader selection needs a personal access token; chat and test runs need ${READER_PERMISSIONS.join(" and ")}. An older instance may refuse a token even when it publishes reader fields.` : undefined, chooseReader].filter(Boolean).join(" "),
66
+ docs: error.docs, details: error.details,
67
+ });
68
+ }
@@ -359,6 +359,7 @@ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, command
359
359
  export const apiList = {
360
360
  name: "api list",
361
361
  summary: "List the operations the instance publishes.",
362
+ description: "Shows needs_a_person_when separately from unconditional access restrictions; --usable keeps operations with conditional identity cases available for ordinary requests.",
362
363
  readOnly: true,
363
364
  idempotent: true,
364
365
  mcpTool: "api_list",
@@ -414,9 +415,11 @@ export const apiList = {
414
415
  })), limit, stringOption(input, "cursor"));
415
416
  const flags = [tag ? ["--tag", tag] : [], method ? ["--method", method] : [], search ? ["--search", search] : [], usableOnly ? ["--usable"] : []].flat();
416
417
  const marked = page.items.some((i) => i.may_send === false);
418
+ const conditional = page.items.some(i => i.needs_a_person_when !== null);
417
419
  return {
418
420
  data: { ...page, credential_published: Boolean(access) },
419
421
  text: table(page.items.map((i) => ({ ...i, access: i.needs_a_person ? "a person" : i.needs?.length ? `needs ${i.needs.join(" and ")}` : "" })), marked ? ["operation", "method", "path", "access", "summary"] : ["operation", "method", "path", "summary"]) +
422
+ (conditional ? `\nNeeds a person only when (ordinary requests remain usable):${page.items.filter(i => i.needs_a_person_when !== null).map(i => `\n ${i.method} ${i.path}: ${clip(i.needs_a_person_when, 240)}`).join("")}` : "") +
420
423
  `\n${page.items.length} of ${page.total}` +
421
424
  (marked ? `\nOperations with an access entry are ones this credential may not send, as the instance says; --usable leaves them out.` : "") +
422
425
  moreHint(page.next_cursor, cavelonCommand("api", "list", ...flags)),
@@ -433,11 +436,12 @@ async function listAccess(ctx) {
433
436
  }
434
437
  }
435
438
  function accessFields(mark) {
436
- return { may_send: mark.allowed, needs_a_person: mark.person ?? null, needs: mark.missing ?? null };
439
+ return { may_send: mark.allowed, needs_a_person: mark.person ?? null, needs_a_person_when: mark.personWhen ?? null, needs: mark.missing ?? null };
437
440
  }
438
441
  export const apiDescribe = {
439
442
  name: "api describe",
440
443
  summary: "Show one operation's parameters, body and responses.",
444
+ description: "Shows the credential's published needs_a_person_when as advisory guidance. Its reason describes the condition; it does not refuse an ordinary request.",
441
445
  readOnly: true,
442
446
  idempotent: true,
443
447
  mcpTool: "api_describe",
@@ -461,6 +465,7 @@ export const apiDescribe = {
461
465
  method: op.method,
462
466
  path: op.path,
463
467
  read_only: op.readOnly,
468
+ ...accessFields(operationAccess(await listAccess(ctx), `${op.method} ${op.path}`)),
464
469
  person_only: kept ? { source: kept.source, reason: kept.reason ?? null, hint: kept.hint } : null,
465
470
  secret_fields: secrets,
466
471
  confirmation: op.confirmation ? { required: true, when: op.confirmationWhen ?? null } : null,
@@ -480,6 +485,8 @@ export const apiDescribe = {
480
485
  responses,
481
486
  };
482
487
  const lines = [`${op.method} ${op.path} (${op.readOnly ? "read-only" : "changing"})`, op.summary ?? ""];
488
+ if (data.needs_a_person_when !== null)
489
+ lines.push(`Needs a person only when: ${data.needs_a_person_when}. Ordinary requests remain usable; the instance decides every request.`);
483
490
  if (kept) {
484
491
  lines.push(kept.source === "instance"
485
492
  ? `For a person only (x-cavelon-person-only${kept.reason ? `: ${kept.reason}` : ""}): an agent does not send it. ${kept.hint}`
@@ -8,6 +8,7 @@ import { callStable, workflowOperation } from "../invoke.js";
8
8
  import { cavelonCommand, fill } from "../printed.js";
9
9
  import { MCP_MAX_WAIT_MS } from "./async.js";
10
10
  import { accessFor, activationStep, mayActivate } from "../access.js";
11
+ import { AS_CHAT_USER_OPTION, chatUserReader, chatUserReaderError } from "../chat-reader.js";
11
12
  function harnessRef(session, input) {
12
13
  const option = stringOption(input, "harness");
13
14
  if (option)
@@ -48,7 +49,10 @@ export const chat = {
48
49
  "not the default, or a draft, can be tried before it answers anyone. A draft answers a person's token as a Playground run\n" +
49
50
  "(counted as testing), never a tenant API key. Without --harness: the env file's or cavelon.yaml's solution, else the\n" +
50
51
  "tenant's default route. Each call is one turn; --session continues a conversation. Not streamed: waits for the whole\n" +
51
- `answer, at most --timeout (default ${DEFAULT_CHAT_TIMEOUT}; ${MCP_MAX_WAIT_MS / 1000} s as an MCP tool).`,
52
+ `answer, at most --timeout (default ${DEFAULT_CHAT_TIMEOUT}; ${MCP_MAX_WAIT_MS / 1000} s as an MCP tool).\n` +
53
+ "--as-chat-user reads knowledge and binds database query identity as that Chat User, with a personal access token.\n" +
54
+ "Choose an id with `cavelon api list_chat_users -p tenant_id=<tenant_id>`; email_verified says whether an email-bound\n" +
55
+ "query can bind that address. Without the option, keeps the usual reader.",
52
56
  readOnly: false,
53
57
  mcpEffect: "Starts or continues a conversation with the solution and runs its agents (model usage, its tools' actions); changes no configuration.",
54
58
  mcpTool: "chat",
@@ -58,6 +62,7 @@ export const chat = {
58
62
  harness: HARNESS_OPTION,
59
63
  env: ENV_OPTION,
60
64
  session: { type: "string", value: "<session_id>", description: "Continue this conversation (the session_id a previous chat printed)." },
65
+ "as-chat-user": AS_CHAT_USER_OPTION,
61
66
  timeout: { type: "string", value: "<duration>", description: `Wait at most this long for the answer (90s, 5m; default ${DEFAULT_CHAT_TIMEOUT}).` },
62
67
  },
63
68
  examples: ['cavelon chat "When are you open?" --harness support-faq', 'cavelon chat "And on Saturdays?" --session <session_id>', 'cavelon chat "Hello" --json'],
@@ -68,9 +73,10 @@ export const chat = {
68
73
  const raw = stringOption(input, "timeout");
69
74
  const timeout = Math.min(parseDuration(raw ?? DEFAULT_CHAT_TIMEOUT), ctx.mode === "mcp" ? MCP_MAX_WAIT_MS : Number.MAX_SAFE_INTEGER);
70
75
  const session = await ctx.session();
76
+ const reader = await chatUserReader(ctx, input, "/api/v1/chat");
71
77
  const { ref, source } = harnessRef(session, input);
72
78
  const harness = ref ? await findHarness(ctx, ref, source, (slug) => cavelonCommand("chat", fill("message"), "--harness", slug)) : undefined;
73
- const body = { message, stream: false };
79
+ const body = { message, stream: false, ...reader };
74
80
  if (harness)
75
81
  body.harness_id = harness.id;
76
82
  const sessionId = stringOption(input, "session");
@@ -81,21 +87,22 @@ export const chat = {
81
87
  answer = await callStable(ctx, "POST", "/api/v1/chat", "chatting with a solution", { body, timeoutMs: timeout });
82
88
  }
83
89
  catch (error) {
84
- throw chatError(error, harness, error instanceof CavelonError && error.status === 409 ? mayActivate(await accessFor(await ctx.client())) : null);
90
+ throw chatUserReaderError(chatError(error, harness, error instanceof CavelonError && error.status === 409 ? mayActivate(await accessFor(await ctx.client())) : null), reader);
85
91
  }
86
92
  const target = harness ? { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } : null;
87
93
  if (answer.retrieval_warning)
88
94
  ctx.warn(answer.retrieval_warning);
89
95
  const next = {
90
- continue: cavelonCommand("chat", fill("message"), "--session", answer.session_id),
96
+ continue: cavelonCommand("chat", fill("message"), "--session", answer.session_id, ...(reader ? ["--as-chat-user", reader.reader_chat_user_id, ...(harness ? ["--harness", harness.slug] : [])] : [])),
91
97
  trace: cavelonCommand("trace", answer.conversation_id, "--kind", "conversation"),
92
98
  };
93
99
  const who = harness ? named(harness) : "The default route";
94
100
  const directives = answer.ui_directives?.length ? `\n(${answer.ui_directives.length} UI directive${answer.ui_directives.length === 1 ? "" : "s"}, such as a form; --json shows them)` : "";
95
101
  const limit = answer.limit_error ? `\nlimit: ${clip(JSON.stringify(answer.limit_error), 300)}` : "";
96
102
  return {
97
- data: { harness: target, ...answer, next },
103
+ data: { harness: target, ...answer, ...reader, next },
98
104
  text: [
105
+ ...(reader ? [`Reading as Chat User ${reader.reader_chat_user_id}.`] : []),
99
106
  `${who} answered:`,
100
107
  `${answer.response || "(no text)"}${directives}${limit}`,
101
108
  "",
@@ -0,0 +1,284 @@
1
+ import { X509Certificate } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption } from "../command.js";
4
+ import { accessFor, allOf, operationAccess, principalOf } from "../access.js";
5
+ import { confirmation } from "../confirm-token.js";
6
+ import { CavelonError, ExitCode, usageError, validationError } from "../errors.js";
7
+ import { keyValues, moreHint, table } from "../format.js";
8
+ import { callStable, workflowOperation } from "../invoke.js";
9
+ import { deref } from "../openapi.js";
10
+ import { confinedPath } from "../paths.js";
11
+ import { cavelonCommand } from "../printed.js";
12
+ import { connectionView, connectorOn, read, resolveConnection, viewerOnly, withPermissionHint } from "./db.js";
13
+ const CONNECTIONS = "/api/v1/database-connectors/connections";
14
+ const CONNECTION = `${CONNECTIONS}/{connection_id}`;
15
+ const manageHint = "This needs database_connectors.manage in Tenant mode: the tenant Owner (legacy Admin) or a superadmin, using a personal access token or the dashboard. A tenant API key cannot manage connections.";
16
+ async function managementPreflight(ctx, method, route) {
17
+ await connectorOn(ctx);
18
+ const { op } = await workflowOperation(ctx, method, route, "database connection management");
19
+ const access = operationAccess(await accessFor(await ctx.client()), `${method} ${route}`);
20
+ if (op.personOnly?.marked || access.person) {
21
+ const reason = op.personOnly?.marked ? op.personOnly.reason : access.person;
22
+ throw new CavelonError(ExitCode.needsAction, {
23
+ code: "operation_for_a_person", message: `This instance keeps ${method} ${route} for a person${reason ? ` (${reason})` : ""}.`,
24
+ hint: "A person manages the connection in the Admin under Settings › Security & access › Databases. This instance may be older than connection management with a personal access token.",
25
+ });
26
+ }
27
+ if (access.allowed === false)
28
+ throw new CavelonError(ExitCode.unauthorized, {
29
+ code: "permission_missing", status: 403, message: `This credential lacks ${allOf(access.missing)} for ${method} ${route}.`,
30
+ hint: manageHint, details: { permissions: access.missing, sent: false },
31
+ });
32
+ }
33
+ async function manage(ctx, method, route, body, id) {
34
+ try {
35
+ await managementPreflight(ctx, method, route);
36
+ return await callStable(ctx, method, route, "database connection management", { body, params: id ? { connection_id: [id] } : undefined });
37
+ }
38
+ catch (error) {
39
+ if (error instanceof CavelonError && error.code === "credential_required_for_target_change") {
40
+ throw new CavelonError(error.exitCode, { code: error.code, status: error.status, message: error.message, details: error.details,
41
+ hint: "A person changes host, port or dialect of a password-bearing connection in the Admin under Settings › Security & access › Databases, with the new server's password. The kit never takes a password." });
42
+ }
43
+ throw withPermissionHint(error, manageHint);
44
+ }
45
+ }
46
+ const textOption = (description, value = "<value>") => ({ type: "string", value, description });
47
+ const connectionOptions = {
48
+ dialect: textOption("Database type, checked against this instance's published create/update schema.", "<dialect>"),
49
+ host: textOption("One DNS name or IP address, without port, path or user.", "<host>"),
50
+ port: textOption("Database port; required on create (the instance validates its bounds).", "<port>"),
51
+ "database-name": textOption("Database name on this server.", "<name>"),
52
+ username: textOption("Database login name; its password is set only in the Admin.", "<name>"),
53
+ "tls-mode": textOption("TLS mode, checked against the published schema; omitted on create uses the instance's default.", "<mode>"),
54
+ "statement-timeout-ms": textOption("Statement timeout in milliseconds, within the instance's bounds.", "<ms>"),
55
+ enabled: textOption("Enable or disable the connection (true or false); omitted leaves the instance's default or current value.", "<true|false>"),
56
+ };
57
+ function booleanText(input, name) {
58
+ const value = stringOption(input, name);
59
+ if (value === undefined)
60
+ return undefined;
61
+ if (value !== "true" && value !== "false")
62
+ throw usageError(`--${name} takes true or false.`);
63
+ return value === "true";
64
+ }
65
+ function connectionBody(input, name) {
66
+ const body = {};
67
+ if (name !== undefined)
68
+ body.name = name;
69
+ for (const [option, field] of Object.entries({ name: "name", dialect: "dialect", host: "host", "database-name": "database_name", username: "username", "tls-mode": "tls_mode" })) {
70
+ const value = stringOption(input, option);
71
+ if (value !== undefined)
72
+ body[field] = value;
73
+ }
74
+ for (const [option, field] of Object.entries({ port: "port", "statement-timeout-ms": "statement_timeout_ms" })) {
75
+ const value = intOption(input, option);
76
+ if (value !== undefined)
77
+ body[field] = value;
78
+ }
79
+ const enabled = booleanText(input, "enabled");
80
+ if (enabled !== undefined)
81
+ body.is_enabled = enabled;
82
+ return body;
83
+ }
84
+ async function savedResult(ctx, connection, verb) {
85
+ const principal = await principalOf(await ctx.client());
86
+ const person = principal?.needs_a_person?.find(o => o.method === "PUT" && o.path === `${CONNECTION}/password`) ?? null;
87
+ const next = connection.password_set ? `Test the connection: ${cavelonCommand("db", "test", connection.name)}` :
88
+ `${person?.reason ? `${person.reason}: ` : ""}a person sets the password in the Admin under Settings › Security & access › Databases, then runs ${cavelonCommand("db", "test", connection.name)}. The password never goes through the kit.`;
89
+ return { data: { connection: connectionView(connection), needs_a_person: person, next_step: next }, text: `${verb} connection ${connection.name} (${connection.id}).\n${keyValues([
90
+ ["dialect", connection.dialect], ["target", `${connection.host}:${connection.port}/${connection.database_name}`], ["username", connection.username],
91
+ ["tls_mode", connection.tls_mode], ["password_set", connection.password_set], ["allows_writes", connection.allows_writes],
92
+ ["ca_certificates", connection.ca_certificates], ["ca_certificate_sha256", connection.ca_certificate_sha256],
93
+ ])}\n${next}` };
94
+ }
95
+ export const dbConnectionCreate = {
96
+ name: "db connections create", summary: "Create a connection without a password (database_connectors.manage); print the Admin password step.",
97
+ description: "The tenant Owner (legacy Admin), or a superadmin in Tenant mode, creates it with a personal access token.\n" +
98
+ "Fields and defaults come from this instance's OpenAPI. No password argument, environment value, stdin or file is read.\n" +
99
+ "A person sets the password in Settings › Security & access › Databases before testing. Connections stay outside packages.",
100
+ readOnly: false, mcpTool: "db_connection_create", operations: [`POST ${CONNECTIONS}`],
101
+ positionals: [{ name: "name", required: true, description: "Connection name, the same in every environment that uses the package." }],
102
+ options: connectionOptions,
103
+ examples: ["cavelon db connections create shop-db --dialect postgresql --host db.example.com --port 5432 --database-name shop --username cavelon_reader"],
104
+ async run(ctx, input) {
105
+ const body = connectionBody(input, positional(input, "name"));
106
+ for (const field of ["dialect", "host", "port", "database_name", "username"])
107
+ if (body[field] === undefined)
108
+ throw usageError(`Create needs --${field.replaceAll("_", "-")}.`);
109
+ return savedResult(ctx, await manage(ctx, "POST", CONNECTIONS, body), "Created");
110
+ },
111
+ };
112
+ export const dbConnectionUpdate = {
113
+ name: "db connections update", summary: "Change only given public connection fields (database_connectors.manage); never a password or allows_writes.",
114
+ description: "A person must move a password-bearing connection to another host, port or dialect in the Admin with its password.\n" +
115
+ "The instance refuses that change from the kit; an uncredentialed connection moves freely. Test again after changing it.\n" +
116
+ "Enabling writes and acknowledging write privileges remain dashboard actions and never enter a package.",
117
+ readOnly: false, idempotent: true, mcpTool: "db_connection_update", operations: [`PATCH ${CONNECTION}`],
118
+ positionals: [{ name: "connection", required: true, description: "Connection name or id." }],
119
+ options: { name: textOption("New connection name.", "<name>"), ...connectionOptions },
120
+ examples: ["cavelon db connections update shop-db --statement-timeout-ms 3000", "cavelon db connections update shop-db --enabled false"],
121
+ async run(ctx, input) {
122
+ const body = connectionBody(input);
123
+ if (!Object.keys(body).length)
124
+ throw usageError("Give at least one connection field to change.");
125
+ const connection = await resolveConnection(ctx, positional(input, "connection"));
126
+ return savedResult(ctx, await manage(ctx, "PATCH", CONNECTION, body, connection.id), "Updated");
127
+ },
128
+ };
129
+ export const dbConnectionDelete = {
130
+ name: "db connections delete", summary: "Delete an unused connection (database_connectors.manage); previews first, --confirm deletes it.",
131
+ description: "Without --confirm nothing is deleted. The instance refuses deletion while queries still use the connection.",
132
+ readOnly: false, destructive: true, mcpTool: "db_connection_delete", operations: [`DELETE ${CONNECTION}`],
133
+ positionals: [{ name: "connection", required: true, description: "Connection name or id." }],
134
+ options: { confirm: { type: "boolean", mcpToken: true, description: "Delete the previewed connection." } },
135
+ examples: ["cavelon db connections delete unused-db", "cavelon db connections delete unused-db --confirm"],
136
+ async run(ctx, input) {
137
+ const connection = await resolveConnection(ctx, positional(input, "connection"));
138
+ await managementPreflight(ctx, "DELETE", CONNECTION);
139
+ const gate = await confirmation(ctx, input, "db_connection_delete", { id: connection.id, config_version: connection.config_version });
140
+ if (!gate.confirmed)
141
+ return {
142
+ data: { deleted: false, connection: connectionView(connection), confirm: gate.confirm(cavelonCommand("db", "connections", "delete", connection.id, "--confirm")), ...gate.fields },
143
+ text: `Connection ${connection.name} (${connection.id}), ${connection.query_count ?? "unknown"} queries.\n${gate.where}\nNothing was deleted. Delete it with: ${gate.confirm(cavelonCommand("db", "connections", "delete", connection.id, "--confirm"))}`,
144
+ exitCode: gate.exitCode,
145
+ };
146
+ await manage(ctx, "DELETE", CONNECTION, undefined, connection.id);
147
+ return { data: { deleted: true, id: connection.id, name: connection.name }, text: `Deleted connection ${connection.name}.` };
148
+ },
149
+ };
150
+ function publicCertificates(pem) {
151
+ while (pem.endsWith("\0"))
152
+ pem = pem.slice(0, -1);
153
+ const refusal = () => validationError("A public CA certificate bundle is required; private keys and other content are refused.");
154
+ if (pem.includes("PRIVATE KEY") || pem.includes("\0"))
155
+ throw refusal();
156
+ const blocks = [...pem.matchAll(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)];
157
+ if (!blocks.length)
158
+ throw refusal();
159
+ let previous = 0;
160
+ for (const block of blocks) {
161
+ if (pem.slice(previous, block.index).trim())
162
+ throw refusal();
163
+ try {
164
+ new X509Certificate(block[0]);
165
+ }
166
+ catch {
167
+ throw validationError("The public CA certificate is invalid.");
168
+ }
169
+ previous = block.index + block[0].length;
170
+ }
171
+ if (pem.slice(previous).trim())
172
+ throw refusal();
173
+ return pem;
174
+ }
175
+ export const dbConnectionCa = {
176
+ name: "db connections ca", summary: "Upload a public CA certificate bundle (database_connectors.manage); refuse private keys before sending.",
177
+ description: "The file must contain only valid PEM CERTIFICATE blocks. It is bounded by the instance's published CA limit.\n" +
178
+ "The output keeps certificate metadata and fingerprints, never the PEM. Test the connection again after uploading it.",
179
+ readOnly: false, idempotent: true, mcpTool: "db_connection_ca", operations: [`PATCH ${CONNECTION}`],
180
+ positionals: [{ name: "connection", required: true, description: "Connection name or id." }, { name: "file", required: true, description: "Public PEM certificate file, never a private key." }],
181
+ examples: ["cavelon db connections ca shop-db ./public-ca.pem"],
182
+ async run(ctx, input) {
183
+ await connectorOn(ctx);
184
+ const { doc, op } = await workflowOperation(ctx, "PATCH", CONNECTION, "public CA certificate upload");
185
+ const body = doc ? deref(doc, op.requestBody?.content["application/json"]?.schema) : undefined;
186
+ const ca = body?.properties?.ca_certificate_pem;
187
+ const limit = ca?.maxLength ?? ca?.anyOf?.find(s => s.maxLength !== undefined)?.maxLength ?? 32768;
188
+ const file = await fs.open(await confinedPath(ctx, positional(input, "file"), "The public CA certificate file"), "r");
189
+ let pem;
190
+ try {
191
+ if (!(await file.stat()).isFile())
192
+ throw validationError("The public CA certificate must be a regular file.");
193
+ const bytes = Buffer.alloc(limit + 1);
194
+ let bytesRead = 0;
195
+ while (bytesRead < bytes.length) {
196
+ const chunk = await file.read(bytes, bytesRead, bytes.length - bytesRead, bytesRead);
197
+ if (!chunk.bytesRead)
198
+ break;
199
+ bytesRead += chunk.bytesRead;
200
+ }
201
+ if (bytesRead > limit)
202
+ throw validationError("The public CA certificate file exceeds the instance's size limit.");
203
+ pem = publicCertificates(bytes.subarray(0, bytesRead).toString("utf8"));
204
+ }
205
+ finally {
206
+ await file.close();
207
+ }
208
+ const connection = await resolveConnection(ctx, positional(input, "connection"));
209
+ return savedResult(ctx, await manage(ctx, "PATCH", CONNECTION, { ca_certificate_pem: pem }, connection.id), "Updated CA of");
210
+ },
211
+ };
212
+ export const dbLoginScript = {
213
+ name: "db login-script", summary: "Print the instance's published read-only login SQL for a dialect or saved connection; no database is contacted.",
214
+ description: "Needs database_connectors.view. The DBA replaces the script's password placeholder locally, outside the kit.\n" +
215
+ "Only variants this instance publishes are offered; this build publishes read_only. Omitted inputs use its defaults.\n" +
216
+ "For SQL Server, connection_limit_enforced is false; --schema scopes SELECT instead of granting db_datareader.",
217
+ readOnly: true, idempotent: true, mcpTool: "db_login_script", operations: ["GET /api/v1/database-connectors/login-script", `GET ${CONNECTION}/login-script`],
218
+ positionals: [{ name: "dialect", description: "Database dialect; omit only with --connection." }],
219
+ options: {
220
+ connection: textOption("Use dialect, database, user and TLS from this saved connection (name or id).", "<connection>"),
221
+ "database-name": textOption("Database the login may read (without --connection).", "<name>"),
222
+ username: textOption("Database login name (without --connection).", "<name>"),
223
+ schema: textOption("Schema the read grants cover.", "<name>"),
224
+ "egress-ip": { ...textOption("Outbound IP address; omitted uses the instance's configured addresses.", "<ip>"), multiple: true },
225
+ "connection-limit": textOption("Connections to allow; omitted uses the instance's pool size times four.", "<n>"),
226
+ "require-tls": textOption("MySQL REQUIRE SSL (true or false, without --connection).", "<true|false>"),
227
+ },
228
+ examples: ["cavelon db login-script postgresql --database-name shop --username cavelon_reader", "cavelon db login-script --connection shop-db --schema public"],
229
+ async run(ctx, input) {
230
+ const dialect = positional(input, "dialect");
231
+ const connectionRef = stringOption(input, "connection");
232
+ if (Boolean(dialect) === Boolean(connectionRef))
233
+ throw usageError("Give a dialect or --connection, exactly one.");
234
+ if (connectionRef && ["database-name", "username", "require-tls"].some(k => input.options[k] !== undefined))
235
+ throw usageError("With --connection, database, username and TLS come from the saved connection.");
236
+ const query = {};
237
+ for (const [option, field] of Object.entries({ "database-name": "database_name", username: "username", schema: "schema" }))
238
+ query[field] = stringOption(input, option);
239
+ const ips = listOption(input, "egress-ip");
240
+ if (ips.length)
241
+ query.egress_ips = ips;
242
+ const limit = intOption(input, "connection-limit");
243
+ if (limit !== undefined)
244
+ query.connection_limit = String(limit);
245
+ const tls = booleanText(input, "require-tls");
246
+ if (tls !== undefined)
247
+ query.require_tls = String(tls);
248
+ const connection = connectionRef ? await resolveConnection(ctx, connectionRef) : undefined;
249
+ if (dialect)
250
+ query.dialect = dialect;
251
+ let script;
252
+ if (connection) {
253
+ try {
254
+ script = await callStable(ctx, "GET", `${CONNECTION}/login-script`, "database login scripts", { params: { connection_id: [connection.id] }, query });
255
+ }
256
+ catch (error) {
257
+ throw viewerOnly(error);
258
+ }
259
+ }
260
+ else
261
+ script = await read(ctx, "/api/v1/database-connectors/login-script", "database login scripts", query);
262
+ return { data: script, text: `${keyValues(Object.entries(script).filter(([key]) => key !== "script"))}\n\n${script.script}\n\nThe DBA replaces the password placeholder locally, outside the kit.` };
263
+ },
264
+ };
265
+ export const dbSchema = {
266
+ name: "db schema", summary: "Explore readable schemas or one schema's tables and columns (database_connectors.manage); read-only.",
267
+ description: "Reads only the database catalog, under the connection's timeout and read-only boundary. The instance records\n" +
268
+ "counts in its audit log. It caps schemas/tables at 500 and columns at 2,000; truncated flags say what was cut.\n" +
269
+ "Only the tenant Owner (legacy Admin) or a superadmin in Tenant mode may explore, using a session or personal access token.",
270
+ readOnly: true, idempotent: true, mcpTool: "db_schema", operations: [`POST ${CONNECTION}/schema`],
271
+ positionals: [{ name: "connection", required: true, description: "Connection name or id." }, { name: "schema", description: "Schema to inspect; omitted lists schemas." }],
272
+ options: { limit: { ...LIMIT_OPTION, description: "Return at most n schemas or tables (default 50, maximum 500)." }, cursor: CURSOR_OPTION },
273
+ examples: ["cavelon db schema shop-db", "cavelon db schema shop-db public --json"],
274
+ async run(ctx, input) {
275
+ const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 50 });
276
+ const connection = await resolveConnection(ctx, positional(input, "connection"));
277
+ const schema = positional(input, "schema");
278
+ const result = await manage(ctx, "POST", `${CONNECTION}/schema`, schema ? { schema } : {}, connection.id);
279
+ const page = pageOf(schema ? result.tables : result.schemas, limit, stringOption(input, "cursor"));
280
+ const data = { ...result, ...(schema ? { tables: page.items } : { schemas: page.items }), next_cursor: page.next_cursor, total: page.total };
281
+ const lines = schema ? page.items.flatMap(item => { const t = item; return [`${t.name} (${t.kind})`, table(t.columns.map(c => ({ ...c, nullable: c.nullable ? "yes" : "no" })), ["name", "data_type", "nullable"]), ...(t.columns_truncated ? ["Columns truncated by the instance."] : [])]; }) : page.items.map(String);
282
+ return { data, text: [result.error_code ? `Schema exploration failed (${result.error_code}). ${result.driver_message ?? ""}` : lines.join("\n") || "No readable schemas or tables.", ...(result.truncated ? ["The instance truncated the catalog result."] : []), moreHint(page.next_cursor, cavelonCommand("db", "schema", connection.name, ...(schema ? [schema] : [])))].filter(Boolean).join("\n"), exitCode: result.error_code ? ExitCode.failure : ExitCode.ok };
283
+ },
284
+ };