@cavelon/cli 0.2.2 → 0.2.4

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
@@ -21,6 +21,16 @@ in Windows PowerShell. With Python, `uvx cavelon` runs the same executable from
21
21
  PyPI, and `uv tool install cavelon` or `pipx install cavelon` installs it. Then
22
22
  `cavelon setup` sets up your coding agents and logs you in.
23
23
 
24
+ Running the one-line installer again updates the CLI, then asks separately
25
+ whether to refresh Cavelon plugins/skills and enable YOLO for new MCP sessions.
26
+ Enter at the YOLO question keeps your choice. Restart your agent afterwards;
27
+ it launches the tools with that personal mode automatically. Critical changes
28
+ still require approval. Other package managers: update the CLI, then run
29
+ `cavelon setup --update`. Change just the mode with
30
+ `cavelon setup --mcp-mode yolo --yes` or `--mcp-mode standard --yes`.
31
+ Interactive `setup` and `setup --update` offer the same YOLO choice, so
32
+ Homebrew, npm, uv and pipx users do not need to run the installer script.
33
+
24
34
  Version 0.1.17 adds Cline, Kilo, Goose and OMP to the OpenCode, Pi and Qwen
25
35
  Code integrations. Each has native settings and four skills; guarded changes
26
36
  use the qualified client dialog or the person’s own terminal:
@@ -167,7 +177,8 @@ Every command takes `--json` (one JSON document on stdout, errors included),
167
177
  | `db instance` | read-only | The dialects the instance runs and the addresses it connects to databases from, which a database's firewall lets in. |
168
178
  | `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). |
169
179
  | `db test <connection>` | changing | The tenant Owner tests a connection step by step; exit 3 when a step fails. |
170
- | `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. |
180
+ | `db test-run <query> [--draft] [--value name=value…]` | changing | Test a saved query or validate and test edited package SQL before apply. Writes dry-run and report rollback evidence; exit 3 when it fails. Drafts need the Owner's managing PAT. |
181
+ | `db queries delete\|enable\|disable\|rename <query> [<new-slug>] [--confirm]` | changing | Preview a saved-query change, then obtain the person's approval. Delete reports removed assignments; pull follows the change. |
171
182
  | `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. |
172
183
  | `loop cancel <run> [--confirm]` | changing (destructive) | Stop a trigger run and its loops; without `--confirm`, shows what would stop. |
173
184
  | `loop watch <run> [--loop] [--timeout 10m]` | read-only | One line per decided iteration and per state change, then the loop's outcome; returns when it ends or pauses. |
package/dist/access.js CHANGED
@@ -31,6 +31,7 @@ export const OPERATION_PERMISSIONS = {
31
31
  "GET /api/v1/database-connectors/connections/{connection_id}/login-script": ["database_connectors.view"],
32
32
  "POST /api/v1/database-connectors/queries/{query_id}/test-run": [["database_connectors.test", "database_connectors.manage"]],
33
33
  "POST /api/v1/database-connectors/queries": ["database_connectors.manage"],
34
+ "POST /api/v1/database-connectors/queries/test-run": ["database_connectors.manage"],
34
35
  "PATCH /api/v1/database-connectors/queries/{query_id}": ["database_connectors.manage"],
35
36
  "DELETE /api/v1/database-connectors/queries/{query_id}": ["database_connectors.manage"],
36
37
  "PUT /api/v1/variables/{name}": [SETTINGS_VALUES],
@@ -0,0 +1,35 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { CavelonError, ExitCode } from "./errors.js";
4
+ import { withoutBom, writePrivateFile } from "./fsutil.js";
5
+ import { configDir } from "./paths.js";
6
+ export async function readMcpMode(env) {
7
+ const file = path.join(configDir(env), "automation.json");
8
+ try {
9
+ const stat = await fs.lstat(file);
10
+ if (!stat.isFile() || stat.isSymbolicLink())
11
+ throw new Error("expected a regular file");
12
+ const value = JSON.parse(withoutBom(await fs.readFile(file, "utf8")));
13
+ if (!value || typeof value !== "object" || Array.isArray(value))
14
+ throw new Error("expected an object");
15
+ const settings = value;
16
+ if (settings.format !== 1 || !["standard", "yolo"].includes(String(settings.mcp_mode)))
17
+ throw new Error("unrecognized settings format or mode");
18
+ return settings.mcp_mode;
19
+ }
20
+ catch (error) {
21
+ if (error.code === "ENOENT")
22
+ return "standard";
23
+ throw new CavelonError(ExitCode.failure, {
24
+ code: "automation_settings_invalid",
25
+ message: `Cannot read the personal MCP mode in ${file}; leaving this file unchanged.`,
26
+ hint: "Restore a regular JSON file with format: 1 and mcp_mode: standard or yolo, or move it aside and run cavelon setup again.",
27
+ });
28
+ }
29
+ }
30
+ export async function saveMcpMode(env, mode) {
31
+ if (await readMcpMode(env) === mode)
32
+ return false;
33
+ await writePrivateFile(configDir(env), path.join(configDir(env), "automation.json"), JSON.stringify({ format: 1, mcp_mode: mode }, null, 2) + "\n");
34
+ return true;
35
+ }
@@ -0,0 +1,120 @@
1
+ export const CITUS_ADMIN_FUNCTIONS = new Set([
2
+ "alter_distributed_table",
3
+ "alter_old_partitions_set_access_method",
4
+ "alter_role_if_exists",
5
+ "alter_table_set_access_method",
6
+ "assign_distributed_transaction_id",
7
+ "broadcast_intermediate_result",
8
+ "check_distributed_deadlocks",
9
+ "citus_activate_node",
10
+ "citus_add_inactive_node",
11
+ "citus_add_local_table_to_metadata",
12
+ "citus_add_node",
13
+ "citus_add_rebalance_strategy",
14
+ "citus_add_secondary_node",
15
+ "citus_cleanup_orphaned_resources",
16
+ "citus_cleanup_orphaned_shards",
17
+ "citus_copy_shard_placement",
18
+ "citus_create_restore_point",
19
+ "citus_disable_node",
20
+ "citus_drain_node",
21
+ "citus_drop_all_shards",
22
+ "citus_finalize_upgrade_to_citus11",
23
+ "citus_finish_citus_upgrade",
24
+ "citus_finish_pg_upgrade",
25
+ "citus_job_cancel",
26
+ "citus_job_wait",
27
+ "citus_move_shard_placement",
28
+ "citus_pause_node_within_txn",
29
+ "citus_prepare_pg_upgrade",
30
+ "citus_rebalance_start",
31
+ "citus_rebalance_stop",
32
+ "citus_rebalance_wait",
33
+ "citus_remove_node",
34
+ "citus_run_local_command",
35
+ "citus_schema_distribute",
36
+ "citus_schema_move",
37
+ "citus_schema_undistribute",
38
+ "citus_set_coordinator_host",
39
+ "citus_set_default_rebalance_strategy",
40
+ "citus_set_node_property",
41
+ "citus_split_shard_by_split_points",
42
+ "citus_stat_statements_reset",
43
+ "citus_stat_tenants_local_reset",
44
+ "citus_stat_tenants_reset",
45
+ "citus_task_wait",
46
+ "citus_unmark_object_distributed",
47
+ "citus_update_node",
48
+ "citus_update_shard_statistics",
49
+ "citus_update_table_statistics",
50
+ "citus_validate_rebalance_strategy_functions",
51
+ "create_distributed_function",
52
+ "create_distributed_table",
53
+ "create_distributed_table_concurrently",
54
+ "create_intermediate_result",
55
+ "create_reference_table",
56
+ "create_time_partitions",
57
+ "drop_old_time_partitions",
58
+ "fetch_intermediate_results",
59
+ "fix_all_partition_shard_index_names",
60
+ "fix_partition_shard_index_names",
61
+ "fix_pre_citus10_partitioned_table_constraint_names",
62
+ "isolate_tenant_to_new_shard",
63
+ "lock_relation_if_exists",
64
+ "lock_shard_metadata",
65
+ "lock_shard_resources",
66
+ "master_activate_node",
67
+ "master_add_inactive_node",
68
+ "master_add_node",
69
+ "master_add_secondary_node",
70
+ "master_copy_shard_placement",
71
+ "master_create_empty_shard",
72
+ "master_disable_node",
73
+ "master_drain_node",
74
+ "master_get_new_placementid",
75
+ "master_get_new_shardid",
76
+ "master_move_shard_placement",
77
+ "master_remove_distributed_table_metadata_from_workers",
78
+ "master_remove_node",
79
+ "master_remove_partition_metadata",
80
+ "master_run_on_worker",
81
+ "master_set_node_property",
82
+ "master_unmark_object_distributed",
83
+ "master_update_node",
84
+ "master_update_shard_statistics",
85
+ "master_update_table_statistics",
86
+ "notify_constraint_dropped",
87
+ "rebalance_table_shards",
88
+ "recover_prepared_transactions",
89
+ "remove_local_tables_from_metadata",
90
+ "replicate_reference_tables",
91
+ "replicate_table_shards",
92
+ "start_metadata_sync_to_all_nodes",
93
+ "start_metadata_sync_to_node",
94
+ "stop_metadata_sync_to_node",
95
+ "truncate_local_data_after_distributing_table",
96
+ "undistribute_table",
97
+ "update_distributed_table_colocation",
98
+ "worker_adjust_identity_column_seq_ranges",
99
+ "worker_apply_inter_shard_ddl_command",
100
+ "worker_apply_sequence_command",
101
+ "worker_apply_shard_ddl_command",
102
+ "worker_change_sequence_dependency",
103
+ "worker_copy_table_to_node",
104
+ "worker_create_or_alter_role",
105
+ "worker_create_or_replace_object",
106
+ "worker_create_truncate_trigger",
107
+ "worker_drop_all_shell_tables",
108
+ "worker_drop_distributed_table",
109
+ "worker_drop_sequence_dependency",
110
+ "worker_drop_shell_table",
111
+ "worker_fix_partition_shard_index_names",
112
+ "worker_fix_pre_citus10_partitioned_table_constraint_names",
113
+ "worker_nextval",
114
+ "worker_partition_query_result",
115
+ "worker_record_sequence_dependency",
116
+ "worker_save_query_explain_analyze",
117
+ "worker_split_copy",
118
+ "worker_split_shard_release_dsm",
119
+ "worker_split_shard_replication_setup",
120
+ ]);
package/dist/command.js CHANGED
@@ -38,6 +38,7 @@ export function ownsTenant(spec) {
38
38
  export const GLOBAL_OPTIONS = {
39
39
  json: { type: "boolean", description: "Print one JSON document instead of text." },
40
40
  yolo: { type: "boolean", cliOnly: true, description: "Automatically apply eligible routine changes in this process's selected target; critical changes still need a person." },
41
+ "no-yolo": { type: "boolean", cliOnly: true, description: "Use standard mode for this process, overriding the personal MCP startup mode." },
41
42
  instance: { type: "string", value: "<url>", description: "The instance URL (overrides CAVELON_URL and cavelon.yaml)." },
42
43
  tenant: { type: "string", value: "<tenant>", description: "Tenant slug, name or id (overrides CAVELON_TENANT and cavelon.yaml)." },
43
44
  help: { type: "boolean", short: "h", description: "Show help for the command." },
@@ -12,7 +12,7 @@ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
12
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, personCommand } from "../printed.js";
15
+ import { cavelonCommand, personCommand } from "../printed.js";
16
16
  import { apiApproval } from "../api-approval-policy.js";
17
17
  import { yoloAllows } from "../automation-policy.js";
18
18
  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. " +
@@ -154,13 +154,13 @@ function secretsIn(doc, op, args) {
154
154
  }
155
155
  return [...found];
156
156
  }
157
- function secretRefusal(op, fields, driven) {
157
+ function secretRefusal(op, fields) {
158
158
  const named = fields.map((f) => `"${f}"`).join(", ");
159
159
  return new CavelonError(ExitCode.needsAction, {
160
160
  code: "secret_field_for_a_person",
161
161
  message: `The request to ${op.alias} sets ${named}, which the instance marks as a secret value (x-cavelon-secret); ` +
162
- `a person enters secret values, so ${notSentBy(driven)}`,
163
- hint: `A person sets a secret value in their own terminal with \`${cavelonCommand("secrets", "set", fill("name"))}\`, or enters it in the Admin. Leave the field out to send the rest.`,
162
+ "cavelon api never sends secret fields, including from a person's terminal.",
163
+ hint: "Enter database passwords, private keys and keytabs in the Admin under Settings › Security & access › Databases. For other secrets, use the Admin or the dedicated secrets command where the instance allows it. Leave the field out to send the rest.",
164
164
  details: { fields },
165
165
  });
166
166
  }
@@ -209,7 +209,8 @@ export const api = {
209
209
  "Other changes still need the person's yes: the MCP client asks them, or they send it from their own terminal.\n" +
210
210
  "A changed request needs a new preview; confirm: true is refused. Instance confirmation requirements always win.\n" +
211
211
  "Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
212
- "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
212
+ "sends a file outside the solution folder. Secret body fields (x-cavelon-secret) are refused in every mode, including\n" +
213
+ "a person's terminal; enter passwords, keys and keytabs in the Admin. On an\n" +
213
214
  "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
214
215
  "approval is refused. A person's own terminal sends at once.\n" +
215
216
  "In a solution folder, the persona operations (get_bot_persona, upsert_bot_persona, …) get the folder's solution as\n" +
@@ -273,10 +274,10 @@ export const api = {
273
274
  details: { source: kept.source, ...(kept.reason ? { reason: kept.reason } : {}) },
274
275
  });
275
276
  }
276
- const secrets = secretsIn(doc, op, args);
277
- if (secrets.length)
278
- throw secretRefusal(op, secrets, driven);
279
277
  }
278
+ const secrets = secretsIn(doc, op, args);
279
+ if (secrets.length)
280
+ throw secretRefusal(op, secrets);
280
281
  if (driven && !op.readOnly) {
281
282
  const words = [
282
283
  "api",
@@ -508,7 +509,7 @@ export const apiDescribe = {
508
509
  : `For a person: it ${kept.reason}, and this instance marks no operation, so an agent does not send it. ${kept.hint}`);
509
510
  }
510
511
  if (secrets.length)
511
- lines.push(`Secret values (x-cavelon-secret): ${secrets.join(", ")}. A person enters them; an agent leaves them out.`);
512
+ lines.push(`Secret values (x-cavelon-secret): ${secrets.join(", ")}. Enter them in the Admin; cavelon api never sends them.`);
512
513
  if (op.confirmation) {
513
514
  lines.push(`Bound confirmation required (x-cavelon-confirmation)${op.confirmationWhen ? `: ${op.confirmationWhen}` : "."} cavelon asks the instance for the ` +
514
515
  "confirmation once the person approved the call: in their own terminal, or in the MCP client's dialog. The instance binds the id to the token, tenant and exact request; it does not verify the person's answer.");
@@ -13,15 +13,15 @@ import { connectionView, connectorOn, read, resolveConnection, viewerOnly, withP
13
13
  const CONNECTIONS = "/api/v1/database-connectors/connections";
14
14
  const CONNECTION = `${CONNECTIONS}/{connection_id}`;
15
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) {
16
+ export async function managementPreflight(ctx, method, route) {
17
17
  await connectorOn(ctx);
18
- const { op } = await workflowOperation(ctx, method, route, "database connection management");
18
+ const { doc, op } = await workflowOperation(ctx, method, route, "database connection and query management");
19
19
  const access = operationAccess(await accessFor(await ctx.client()), `${method} ${route}`);
20
20
  if (op.personOnly?.marked || access.person) {
21
21
  const reason = op.personOnly?.marked ? op.personOnly.reason : access.person;
22
22
  throw new CavelonError(ExitCode.needsAction, {
23
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.",
24
+ hint: "A person manages database connections and queries in the Admin under Settings › Security & access › Databases. This instance may be older than management with a personal access token.",
25
25
  });
26
26
  }
27
27
  if (access.allowed === false)
@@ -29,6 +29,7 @@ async function managementPreflight(ctx, method, route) {
29
29
  code: "permission_missing", status: 403, message: `This credential lacks ${allOf(access.missing)} for ${method} ${route}.`,
30
30
  hint: manageHint, details: { permissions: access.missing, sent: false },
31
31
  });
32
+ return { doc, op };
32
33
  }
33
34
  async function manage(ctx, method, route, body, id) {
34
35
  try {
@@ -38,7 +39,7 @@ async function manage(ctx, method, route, body, id) {
38
39
  catch (error) {
39
40
  if (error instanceof CavelonError && error.code === "credential_required_for_target_change") {
40
41
  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
+ hint: "A person changes a credential-bearing connection's target, SSH tunnel or Kerberos login in the Admin under Settings › Security & access › Databases, supplying its password, SSH key or keytab again. The kit never takes those credentials." });
42
43
  }
43
44
  throw withPermissionHint(error, manageHint);
44
45
  }
@@ -53,6 +54,17 @@ const connectionOptions = {
53
54
  "tls-mode": textOption("TLS mode, checked against the published schema; omitted on create uses the instance's default.", "<mode>"),
54
55
  "statement-timeout-ms": textOption("Statement timeout in milliseconds, within the instance's bounds.", "<ms>"),
55
56
  enabled: textOption("Enable or disable the connection (true or false); omitted leaves the instance's default or current value.", "<true|false>"),
57
+ "follows-redirects": textOption("Follow checked listener redirects (Oracle or SQL Server); cannot combine with an SSH tunnel.", "<true|false>"),
58
+ "auth-method": textOption("Sign-in method from the published schema (password or kerberos); credentials stay in the Admin.", "<method>"),
59
+ "kerberos-realm": textOption("Kerberos realm, for example CORP.EXAMPLE.COM.", "<realm>"),
60
+ "kerberos-principal": textOption("Kerberos account name without the realm.", "<principal>"),
61
+ "kerberos-kdc": { type: "string", multiple: true, value: "<host>", description: "KDC host on port 88; repeat for multiple KDCs. Use --kerberos-kdcs for explicit ports." },
62
+ "kerberos-kdcs": textOption('Public KDC JSON array, for example [{"host":"kdc.example.com","port":88}]; null clears it.', "<json>"),
63
+ "ssh-host": textOption("SSH bastion host. Also give --ssh-username and --ssh-host-key-fingerprint.", "<host>"),
64
+ "ssh-port": textOption("Bastion port (default 22); the instance checks private target permissions.", "<port>"),
65
+ "ssh-username": textOption("SSH forwarding account; a person enters its private key in the Admin.", "<username>"),
66
+ "ssh-host-key-fingerprint": textOption("Required SHA256 bastion host-key fingerprint; no trust on first use.", "<SHA256:...>"),
67
+ "remove-ssh-tunnel": { type: "boolean", description: "Remove the SSH tunnel; a credential-bearing connection may require the Admin." },
56
68
  };
57
69
  function booleanText(input, name) {
58
70
  const value = stringOption(input, name);
@@ -66,7 +78,7 @@ function connectionBody(input, name) {
66
78
  const body = {};
67
79
  if (name !== undefined)
68
80
  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" })) {
81
+ for (const [option, field] of Object.entries({ name: "name", dialect: "dialect", host: "host", "database-name": "database_name", username: "username", "tls-mode": "tls_mode", "auth-method": "auth_method", "kerberos-realm": "kerberos_realm", "kerberos-principal": "kerberos_principal" })) {
70
82
  const value = stringOption(input, option);
71
83
  if (value !== undefined)
72
84
  body[field] = value;
@@ -79,17 +91,58 @@ function connectionBody(input, name) {
79
91
  const enabled = booleanText(input, "enabled");
80
92
  if (enabled !== undefined)
81
93
  body.is_enabled = enabled;
94
+ const redirects = booleanText(input, "follows-redirects");
95
+ if (redirects !== undefined)
96
+ body.follows_redirects = redirects;
97
+ const kdcs = listOption(input, "kerberos-kdc");
98
+ const rawKdcs = stringOption(input, "kerberos-kdcs");
99
+ if (kdcs.length && rawKdcs !== undefined)
100
+ throw usageError("Use --kerberos-kdc or --kerberos-kdcs, not both.");
101
+ if (kdcs.length)
102
+ body.kerberos_kdcs = kdcs.map(host => ({ host, port: 88 }));
103
+ if (rawKdcs !== undefined) {
104
+ try {
105
+ body.kerberos_kdcs = JSON.parse(rawKdcs);
106
+ }
107
+ catch {
108
+ throw usageError("--kerberos-kdcs needs a JSON array of public host/port objects, or null.");
109
+ }
110
+ }
111
+ const ssh = { host: stringOption(input, "ssh-host"), port: intOption(input, "ssh-port"), username: stringOption(input, "ssh-username"), host_key_fingerprint: stringOption(input, "ssh-host-key-fingerprint") };
112
+ const hasSsh = Object.values(ssh).some(v => v !== undefined);
113
+ if (input.options["remove-ssh-tunnel"] && hasSsh)
114
+ throw usageError("Do not combine --remove-ssh-tunnel with SSH settings.");
115
+ if (hasSsh) {
116
+ if (!ssh.host || !ssh.username || !ssh.host_key_fingerprint)
117
+ throw usageError("An SSH tunnel needs --ssh-host, --ssh-username and --ssh-host-key-fingerprint together.");
118
+ body.ssh_tunnel = { ...ssh, port: ssh.port ?? 22 };
119
+ }
120
+ if (input.options["remove-ssh-tunnel"])
121
+ body.ssh_tunnel = null;
122
+ if (body.ssh_tunnel && redirects === true)
123
+ throw usageError("An SSH tunnel cannot follow listener redirects.");
82
124
  return body;
83
125
  }
84
126
  async function savedResult(ctx, connection, verb) {
85
127
  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)}` :
128
+ const credential = connection.auth_method === "kerberos" ? "kerberos-keytab" : "password";
129
+ const person = principal?.needs_a_person?.find(o => o.method === "PUT" && o.path === `${CONNECTION}/${credential}`) ?? null;
130
+ const pending = [];
131
+ if (connection.auth_method === "kerberos" && !connection.kerberos_keytab_set && !connection.password_set)
132
+ pending.push("a person sets the Kerberos keytab or password in the Admin under Settings › Security & access › Databases");
133
+ if (connection.auth_method !== "kerberos" && !connection.password_set)
134
+ pending.push("a person sets the database password in the Admin under Settings › Security & access › Databases");
135
+ if (connection.ssh_tunnel && !connection.ssh_tunnel.private_key_set)
136
+ pending.push("a person sets the SSH private key in the Admin under Settings › Security & access › Databases");
137
+ const next = pending.length ? `${pending.join("; ")}; then run ${cavelonCommand("db", "test", connection.name)}.` : connection.password_set || connection.kerberos_keytab_set ? `Test the connection: ${cavelonCommand("db", "test", connection.name)}` :
88
138
  `${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
139
  return { data: { connection: connectionView(connection), needs_a_person: person, next_step: next }, text: `${verb} connection ${connection.name} (${connection.id}).\n${keyValues([
90
140
  ["dialect", connection.dialect], ["target", `${connection.host}:${connection.port}/${connection.database_name}`], ["username", connection.username],
91
141
  ["tls_mode", connection.tls_mode], ["password_set", connection.password_set], ["allows_writes", connection.allows_writes],
92
142
  ["ca_certificates", connection.ca_certificates], ["ca_certificate_sha256", connection.ca_certificate_sha256],
143
+ ["auth_method", connection.auth_method], ["kerberos_realm", connection.kerberos_realm], ["kerberos_principal", connection.kerberos_principal],
144
+ ["kerberos_keytab_set", connection.kerberos_keytab_set], ["follows_redirects", connection.follows_redirects],
145
+ ["ssh_bastion", connection.ssh_tunnel?.host], ["authorized_keys_entry", connection.ssh_tunnel?.authorized_keys_entry],
93
146
  ])}\n${next}` };
94
147
  }
95
148
  export const dbConnectionCreate = {
@@ -123,6 +176,11 @@ export const dbConnectionUpdate = {
123
176
  if (!Object.keys(body).length)
124
177
  throw usageError("Give at least one connection field to change.");
125
178
  const connection = await resolveConnection(ctx, positional(input, "connection"));
179
+ const access = operationAccess(await accessFor(await ctx.client()), `PATCH ${CONNECTION}`);
180
+ const modes = ["disable", "require", "verify_ca", "verify_full"];
181
+ if (access.personWhen && typeof body.tls_mode === "string" && modes.includes(connection.tls_mode) && modes.includes(body.tls_mode) && modes.indexOf(body.tls_mode) < modes.indexOf(connection.tls_mode)) {
182
+ throw personConnectionChange("weaken TLS");
183
+ }
126
184
  return savedResult(ctx, await manage(ctx, "PATCH", CONNECTION, body, connection.id), "Updated");
127
185
  },
128
186
  };
@@ -173,14 +231,19 @@ function publicCertificates(pem) {
173
231
  return pem;
174
232
  }
175
233
  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" +
234
+ name: "db connections ca", summary: "Show the person-only Admin CA step where published; older instances may accept a public certificate upload.",
235
+ description: "A current instance keeps every CA change for a person in the Admin; the kit refuses before reading the file.\n" +
236
+ "On an older instance without that published restriction, the file must contain only valid PEM CERTIFICATE blocks.\n" +
237
+ "It is bounded by the instance's published CA limit.\n" +
178
238
  "The output keeps certificate metadata and fingerprints, never the PEM. Test the connection again after uploading it.",
179
239
  readOnly: false, idempotent: true, mcpTool: "db_connection_ca", operations: [`PATCH ${CONNECTION}`],
180
240
  positionals: [{ name: "connection", required: true, description: "Connection name or id." }, { name: "file", required: true, description: "Public PEM certificate file, never a private key." }],
181
241
  examples: ["cavelon db connections ca shop-db ./public-ca.pem"],
182
242
  async run(ctx, input) {
183
243
  await connectorOn(ctx);
244
+ const access = operationAccess(await accessFor(await ctx.client()), `PATCH ${CONNECTION}`);
245
+ if (access.personWhen || access.person)
246
+ throw personConnectionChange("change the CA certificate");
184
247
  const { doc, op } = await workflowOperation(ctx, "PATCH", CONNECTION, "public CA certificate upload");
185
248
  const body = doc ? deref(doc, op.requestBody?.content["application/json"]?.schema) : undefined;
186
249
  const ca = body?.properties?.ca_certificate_pem;
@@ -209,6 +272,13 @@ export const dbConnectionCa = {
209
272
  return savedResult(ctx, await manage(ctx, "PATCH", CONNECTION, { ca_certificate_pem: pem }, connection.id), "Updated CA of");
210
273
  },
211
274
  };
275
+ function personConnectionChange(change) {
276
+ return new CavelonError(ExitCode.needsAction, {
277
+ code: "operation_for_a_person", message: `A token cannot ${change}. Nothing was sent.`,
278
+ hint: "A person uses the Admin under Settings › Security & access › Databases › the connection › CA certificate or TLS settings.",
279
+ details: { sent: false },
280
+ });
281
+ }
212
282
  export const dbLoginScript = {
213
283
  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
284
  description: "Needs database_connectors.view. The DBA replaces the script's password placeholder locally, outside the kit.\n" +
@@ -0,0 +1,66 @@
1
+ import { confirmation, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
2
+ import { createHash } from "node:crypto";
3
+ import { positional } from "../command.js";
4
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
5
+ import { clip, keyValues } from "../format.js";
6
+ import { callStable, previewRequest } from "../invoke.js";
7
+ import { cavelonCommand } from "../printed.js";
8
+ import { resolveQuery } from "./db.js";
9
+ import { managementPreflight } from "./db-connections.js";
10
+ const ROUTE = "/api/v1/database-connectors/queries/{query_id}";
11
+ const evidenceFor = (query) => ({ id: query.id, slug: query.slug, version: query.version, kind: query.kind, is_enabled: query.is_enabled,
12
+ sql_sha256: createHash("sha256").update(query.sql_text).digest("hex") });
13
+ function queryChange(change) {
14
+ const method = change === "delete" ? "DELETE" : "PATCH";
15
+ const tool = `db_query_${change}`;
16
+ return {
17
+ name: `db queries ${change}`,
18
+ summary: `${change[0].toUpperCase()}${change.slice(1)} a saved database query; preview first, then the person confirms.`,
19
+ description: "Needs database_connectors.manage. Each preview is bound to this query's version and the exact change.\n" +
20
+ "Rechecks the query after approval; a changed query needs a fresh preview.\n" +
21
+ "Deleting also removes its agent and skill assignments; the result lists what the instance removed.\n" +
22
+ "Run cavelon pull afterwards so the package follows the saved query.\n" + PERSON_CONFIRMS_HELP,
23
+ readOnly: false, destructive: change === "delete", mcpTool: tool, operations: [`${method} ${ROUTE}`],
24
+ positionals: [{ name: "query", required: true, description: "Saved query's slug or id." },
25
+ ...(change === "rename" ? [{ name: "new-slug", required: true, description: "New tool slug, checked against the instance's schema." }] : [])],
26
+ options: { confirm: { type: "boolean", mcpToken: true, description: "Send the exact previewed change after the person's approval." } },
27
+ examples: [`cavelon db queries ${change} order_status${change === "rename" ? " order_lookup" : ""}`],
28
+ async run(ctx, input) {
29
+ const { doc, op } = await managementPreflight(ctx, method, ROUTE);
30
+ const query = await resolveQuery(ctx, positional(input, "query"));
31
+ const slug = positional(input, "new-slug");
32
+ if (change === "rename" && !slug?.trim())
33
+ throw usageError("Give the new query slug.");
34
+ const body = change === "delete" ? undefined : change === "rename" ? { slug } : { is_enabled: change === "enable" };
35
+ previewRequest(doc, op, { params: { query_id: [query.id] }, body });
36
+ const words = ["db", "queries", change, query.id, ...(slug ? [slug] : []), "--confirm"];
37
+ const evidence = evidenceFor(query);
38
+ const gate = await confirmation(ctx, input, tool, { query: evidence, method, body }, {
39
+ person: { what: `${change} saved ${query.kind ?? "unknown-kind"} database query ${query.slug} (version ${query.version}, SQL SHA-256 ${evidence.sql_sha256})${slug ? ` to ${slug}` : ""}${change === "delete" ? " and remove its agent and skill assignments" : ""}.`, words },
40
+ });
41
+ if (!gate.confirmed)
42
+ return {
43
+ data: { sent: false, query: evidence, change, body: body ?? null,
44
+ confirm: gate.confirm(cavelonCommand(...words)), ...gate.fields },
45
+ text: `${keyValues([["query", query.slug], ["version", query.version], ["kind", query.kind], ["sql_sha256", evidence.sql_sha256], ["change", change], ["new_slug", slug]])}\n${gate.where}\n${gate.mismatch ?? "Nothing was changed."}\n${gate.confirm(cavelonCommand(...words))}`,
46
+ exitCode: gate.exitCode,
47
+ };
48
+ await managementPreflight(ctx, method, ROUTE);
49
+ if (JSON.stringify(evidenceFor(await resolveQuery(ctx, query.id))) !== JSON.stringify(evidence)) {
50
+ ctx.approved = undefined;
51
+ throw new CavelonError(ExitCode.conflict, {
52
+ code: "token_mismatch", message: "The saved query changed while approval was pending. Nothing was changed by this command.",
53
+ hint: "Request a fresh preview and approve the query as it is now.", details: { sent: false },
54
+ });
55
+ }
56
+ const result = await callStable(ctx, method, ROUTE, "saved database query management", { params: { query_id: [query.id] }, body });
57
+ const next = `Run ${cavelonCommand("pull")} so package/ follows this change.`;
58
+ return { data: { sent: true, change, ...result, next_step: next },
59
+ text: `${change} completed for ${query.slug}.${change === "delete" ? `\nRemoved assignments: ${clip(JSON.stringify(result.removed_references ?? {}), 3000)}` : ""}\n${next}` };
60
+ },
61
+ };
62
+ }
63
+ export const dbQueryDelete = queryChange("delete");
64
+ export const dbQueryEnable = queryChange("enable");
65
+ export const dbQueryDisable = queryChange("disable");
66
+ export const dbQueryRename = queryChange("rename");