@cavelon/cli 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +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
+ import { connectorOffer, isProcedureCall } from "../database-queries.js";
4
4
  import { requireFeature } from "../features.js";
5
5
  import { clip, keyValues, moreHint, table } from "../format.js";
6
6
  import { callStable } from "../invoke.js";
@@ -130,6 +130,7 @@ function explainLine(codes) {
130
130
  return "";
131
131
  return `\n\nWhat a code means: ${cavelonCommand("explain", fill("code"))} (${distinct.slice(0, 8).join(", ")})`;
132
132
  }
133
+ const refusalOf = (name, refusal) => `${name} (${refusal.code}${refusal.message ? `: ${clip(refusal.message, 200)}` : ""})`;
133
134
  function firewallSentence(offer) {
134
135
  const { egress_ips: ips, connections_per_process: perProcess } = offer.network;
135
136
  const pool = `Each process of the instance that runs agents opens at most ${perProcess} connection${perProcess === 1 ? "" : "s"} per database connection.`;
@@ -214,18 +215,21 @@ export const dbConnections = {
214
215
  };
215
216
  });
216
217
  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);
218
+ const connections = page.items;
219
+ const refused = connections.filter((c) => c.query_enable_refusal?.code);
220
+ const procedureRefused = connections.filter((c) => c.procedure_call_refusal?.code);
218
221
  return {
219
222
  data: page,
220
223
  text: (table(rows, ["name", "dialect", "target", "tls", "enabled", "last_test", "queries", "id"]) ||
221
224
  `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") +
225
+ caLines(connections).join("\n") +
223
226
  moreHint(page.next_cursor, cavelonCommand("db", "connections")) +
224
227
  (untested.length ? `\n\nNot tested successfully: ${untested.join(", ")}; its queries are not ready for agents. The Owner tests one with: ${cavelonCommand("db", "test", fill("connection"))}` : "") +
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
- : ""),
228
+ (refused.length ? `\n\nQueries cannot be enabled on: ${refused.map((c) => refusalOf(c.name, c.query_enable_refusal)).join("; ")}` : "") +
229
+ (procedureRefused.length
230
+ ? `\n\nStored-procedure queries (EXEC) cannot be saved or run on: ${procedureRefused.map((c) => refusalOf(c.name, c.procedure_call_refusal)).join("; ")}`
231
+ : "") +
232
+ explainLine([...refused.map((c) => c.query_enable_refusal.code), ...procedureRefused.map((c) => c.procedure_call_refusal.code)]),
229
233
  };
230
234
  },
231
235
  };
@@ -249,6 +253,9 @@ export const dbQueries = {
249
253
  const ref = positional(input, "query");
250
254
  if (ref) {
251
255
  const q = await resolveQuery(ctx, ref);
256
+ const connection = (await listConnections(ctx)).find((c) => c.id === q.connection_id);
257
+ const procedure = isProcedureCall(q.sql_text, connection?.dialect);
258
+ const refusal = procedure ? connection?.procedure_call_refusal : undefined;
252
259
  const text = [
253
260
  keyValues([
254
261
  ["query", `${q.slug} (${q.name})`],
@@ -264,11 +271,19 @@ export const dbQueries = {
264
271
  "SQL:",
265
272
  q.sql_text,
266
273
  "",
274
+ ...(procedure
275
+ ? [
276
+ "It calls a stored procedure: the model gets its first result set. It runs only while the connection's last test found no write privileges,",
277
+ "and the instance reads the procedure's definition at every save, enable and test run and refuses one that writes.",
278
+ ...(refusal?.code ? [`Not now on ${connection.name}: ${refusal.code}${refusal.message ? ` (${clip(refusal.message, 200)})` : ""}`] : []),
279
+ "",
280
+ ]
281
+ : []),
267
282
  q.parameters.length ? table(parameterRows(q.parameters), ["name", "filled_by", "type", "required", "constraints", "description"]) : "No parameters.",
268
283
  "",
269
284
  `Its runs (no values, no rows): ${cavelonCommand("db", "runs", q.slug)}`,
270
285
  ].join("\n");
271
- return { data: q, text };
286
+ return { data: q, text: text + explainLine([refusal?.code]) };
272
287
  }
273
288
  const connectionRef = stringOption(input, "connection");
274
289
  const connection = connectionRef ? await resolveConnection(ctx, connectionRef) : undefined;
@@ -348,7 +363,10 @@ export const dbTest = {
348
363
  "step names its code; `cavelon explain <code>` says how to fix it. A finding under write_privileges means the database user\n" +
349
364
  "can write: ask the database administrator for a read-only user. On SQL Server, which has no read-only transaction, the\n" +
350
365
  "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.",
366
+ "acknowledges the write privileges in the Admin; a stored-procedure query (EXEC) runs only on a login the test found\n" +
367
+ "without write privileges, acknowledged or not. A passing test on SQL Server also reads again the procedure each\n" +
368
+ "stored-procedure query calls, and lists those that no longer pass the instance's check (procedure_findings); they stay\n" +
369
+ "as they are, and their next save or enable is refused until the procedure only reads again.",
352
370
  readOnly: false,
353
371
  idempotent: true,
354
372
  mcpEffect: "Runs the connection test on the instance and stores its outcome as the connection's last test; changes no setting.",
@@ -370,19 +388,51 @@ export const dbTest = {
370
388
  }
371
389
  const ok = result.outcome === "ok";
372
390
  const steps = (result.steps ?? []).map((s) => ({ step: s.name, status: s.status, code: s.code ?? null, message: s.driver_message ? clip(s.driver_message, 160) : null }));
391
+ const findings = (Array.isArray(result.procedure_findings) ? result.procedure_findings : []).map((f) => ({
392
+ query: f.slug ?? f.query_id ?? "?",
393
+ code: f.code ?? null,
394
+ message: f.message ? clip(f.message, 200) : null,
395
+ }));
396
+ if (findings.length) {
397
+ ctx.warn(`The test passed, but the procedure of ${findings.length === 1 ? "one stored-procedure query" : `${findings.length} stored-procedure queries`} ` +
398
+ `(${findings.map((f) => f.query).join(", ")}) no longer passes the instance's check: ${findings.length === 1 ? "it stays" : "they stay"} as ${findings.length === 1 ? "it is" : "they are"}, ` +
399
+ "and a save or enable is refused until the procedure only reads again.");
400
+ }
373
401
  const text = [
374
402
  `Connection "${connection.name}" (${connection.dialect}): ${ok ? "test passed" : `test failed (${result.outcome})`}, ${result.duration_ms} ms.`,
375
403
  table(steps, ["step", "status", "code", ...(steps.some((s) => s.message) ? ["message"] : [])], 80),
376
404
  ...(result.server_version ? [`server: ${result.server_version}`] : []),
377
405
  ...(result.write_privileges ? [`write privileges: ${clip(JSON.stringify(result.write_privileges), 300)}`] : []),
406
+ ...(findings.length
407
+ ? ["", "Stored-procedure queries whose procedure no longer passes (they stay as they are; a save or enable is refused):", table(findings, ["query", "code", "message"], 80)]
408
+ : []),
378
409
  ].join("\n");
379
410
  return {
380
411
  data: { connection: { id: connection.id, name: connection.name, dialect: connection.dialect }, ...result },
381
- text: text + explainLine(steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code)),
412
+ text: text + explainLine([...steps.filter((s) => s.code && s.status !== "ok").map((s) => s.code), ...findings.map((f) => f.code)]),
382
413
  exitCode: ok ? ExitCode.ok : ExitCode.validation,
383
414
  };
384
415
  },
385
416
  };
417
+ const RUN_REFUSAL_STEPS = {
418
+ database_connection_untested: (q) => `The tenant Owner tests the connection first: ${cavelonCommand("db", "test", q.connection_name)}`,
419
+ write_privileges_block_procedure: (q) => `The connection's login needs to lose its write privileges (a database administrator's change), then the tenant Owner tests it again: ${cavelonCommand("db", "test", q.connection_name)}`,
420
+ procedure_definition_unreadable: () => "The connection's login needs VIEW DEFINITION on the procedure, and the procedure must not be created WITH ENCRYPTION.",
421
+ procedure_definition_writes: () => "The procedure must only read (temporary tables and table variables are fine), or a superadmin writes the query as a SELECT.",
422
+ };
423
+ function refusedRun(error, query) {
424
+ if (!(error instanceof CavelonError) || error.status !== 409)
425
+ return error;
426
+ const step = RUN_REFUSAL_STEPS[error.code];
427
+ return new CavelonError(error.exitCode, {
428
+ code: error.code,
429
+ status: error.status,
430
+ message: error.message,
431
+ hint: [error.hint, step?.(query), `\`${cavelonCommand("explain", error.code)}\` says more.`].filter(Boolean).join(" "),
432
+ docs: error.docs,
433
+ details: error.details,
434
+ });
435
+ }
386
436
  function typed(parameter, raw) {
387
437
  const type = parameter?.type ?? "string";
388
438
  if (type === "integer" || type === "number") {
@@ -421,7 +471,11 @@ export const dbTestRun = {
421
471
  description: "Needs the tenant Owner's permission (database_connectors.test); it reads the customer's own data. Give each parameter\n" +
422
472
  "with --value name=value, those the platform fills from the signed-in visitor (end_user.*) too: that is how an\n" +
423
473
  "identity-scoped query is checked for one customer. The instance records the run (counts only) and audits it with your\n" +
424
- "name; the rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.",
474
+ "name; the rows come back once and are never stored. A failed run names its code; `cavelon explain <code>` says more.\n" +
475
+ "A stored-procedure query (SQL Server) shows the procedure's first result set; the instance refuses its run (exit 4)\n" +
476
+ "while the connection's last test found write privileges or the procedure's definition writes or cannot be read, and\n" +
477
+ "a run whose procedure ended the connector's transaction comes back with a notice saying so and whether the query was\n" +
478
+ "switched off.",
425
479
  readOnly: false,
426
480
  idempotent: true,
427
481
  mcpEffect: "Runs the saved query once on the instance; it leaves a run record (counts only) and an audit entry, and changes no setting.",
@@ -446,7 +500,7 @@ export const dbTestRun = {
446
500
  });
447
501
  }
448
502
  catch (error) {
449
- throw ownerOnly(error, "A test run");
503
+ throw refusedRun(ownerOnly(error, "A test run"), query);
450
504
  }
451
505
  const ok = result.outcome === "ok" && !result.error_code;
452
506
  const columns = result.columns ?? [];
@@ -458,6 +512,7 @@ export const dbTestRun = {
458
512
  ["outcome", result.error_code ? `${result.outcome} (${result.error_code}${result.sqlstate ? `, SQLSTATE ${result.sqlstate}` : ""})` : result.outcome],
459
513
  ["rows", ok ? `${result.returned_rows ?? rows.length} returned of ${result.row_count ?? "?"}${result.truncated ? ", truncated for the model" : ""}` : undefined],
460
514
  ["duration_ms", result.duration_ms],
515
+ ["notice", result.notice || undefined],
461
516
  ]),
462
517
  "",
463
518
  "What the model sees:",
@@ -401,8 +401,9 @@ export const setup = {
401
401
  tenantless: true,
402
402
  summary: "Set up your coding agents for Cavelon and log in, in one guided step.",
403
403
  description: "Finds Claude Code, Codex, Cursor, VS Code with GitHub Copilot, Gemini CLI and Kiro, shows what it will change for each, asks once\n" +
404
- "and does it: Claude Code and Codex get the Cavelon plugin through their own plugin command; the others get the `cavelon` MCP\n" +
405
- "server in their user MCP configuration and the skills in their user skills folder. It touches nothing else in those files and\n" +
404
+ "and does it: Claude Code and Codex get the Cavelon plugin through their own plugin command, Gemini CLI the extension of this\n" +
405
+ "release (or the files, when the release has none); the others get the `cavelon` MCP server in their user MCP configuration\n" +
406
+ "and the skills in their user skills folder. It touches nothing else in those files and\n" +
406
407
  "records what it did, so --remove undoes exactly that. Then it logs in if needed, choosing the tenant by name as `login` does.\n" +
407
408
  "The server starts as `cavelon mcp` when cavelon is installed, otherwise through npx. --check reports what is set up and\n" +
408
409
  "working: each agent's entry, the MCP server starting, and the login. An agent found but never set up for Cavelon is\n" +
@@ -140,6 +140,164 @@ export function queryProblems(query, schema) {
140
140
  }
141
141
  return problems;
142
142
  }
143
+ export const PROCEDURE_CALL_FORM = "EXEC [schema].[procedure] @p1 = :p1, @p2 = :p2";
144
+ const PROCEDURE_DIALECT = "mssql";
145
+ const WORD_START = /[A-Za-z_]/;
146
+ const WORD_PART = /[A-Za-z0-9_$]/;
147
+ function closing(sql, start, quote, backslash) {
148
+ for (let i = start + 1; i < sql.length; i++) {
149
+ if (backslash && sql[i] === "\\") {
150
+ i++;
151
+ continue;
152
+ }
153
+ if (sql[i] !== quote)
154
+ continue;
155
+ if (sql[i + 1] === quote) {
156
+ i++;
157
+ continue;
158
+ }
159
+ return i + 1;
160
+ }
161
+ return undefined;
162
+ }
163
+ function sqlTokens(sql, dialect) {
164
+ const tokens = [];
165
+ let i = 0;
166
+ while (i < sql.length) {
167
+ const char = sql[i];
168
+ if (/\s/.test(char)) {
169
+ i++;
170
+ continue;
171
+ }
172
+ let end;
173
+ let kind;
174
+ if (sql.startsWith("--", i)) {
175
+ const newline = sql.indexOf("\n", i);
176
+ end = newline === -1 ? sql.length : newline;
177
+ kind = "comment";
178
+ }
179
+ else if (sql.startsWith("/*", i)) {
180
+ const close = sql.indexOf("*/", i + 2);
181
+ if (close === -1)
182
+ return undefined;
183
+ end = close + 2;
184
+ kind = "comment";
185
+ }
186
+ else if (char === "'") {
187
+ end = closing(sql, i, "'", dialect === "mysql");
188
+ kind = "string";
189
+ }
190
+ else if (char === '"') {
191
+ end = closing(sql, i, '"', dialect === "mysql");
192
+ kind = dialect === "mysql" ? "string" : "identifier";
193
+ }
194
+ else if (char === "`" && dialect === "mysql") {
195
+ end = closing(sql, i, "`", false);
196
+ kind = "identifier";
197
+ }
198
+ else if (char === "[" && dialect === PROCEDURE_DIALECT) {
199
+ end = closing(sql, i, "]", false);
200
+ kind = "identifier";
201
+ }
202
+ else if (WORD_START.test(char)) {
203
+ end = i + 1;
204
+ while (end < sql.length && WORD_PART.test(sql[end]))
205
+ end++;
206
+ kind = "word";
207
+ }
208
+ else {
209
+ end = i + 1;
210
+ kind = char === ";" ? "semicolon" : "symbol";
211
+ }
212
+ if (end === undefined)
213
+ return undefined;
214
+ tokens.push({ kind, text: sql.slice(i, end), start: i });
215
+ i = end;
216
+ }
217
+ return tokens;
218
+ }
219
+ const isWord = (token, ...words) => token?.kind === "word" && words.includes(token.text.toUpperCase());
220
+ const isSymbol = (token, text) => token?.kind === "symbol" && token.text === text;
221
+ const touching = (first, second) => second.start === first.start + first.text.length;
222
+ const DYNAMIC_SQL_PROCEDURES = ["sp_executesql", "sp_sqlexec", "sp_execute", "sp_execute_external_script", "sp_invoke_external_rest_endpoint"];
223
+ const DYNAMIC_SQL_PREFIXES = ["xp_", "sp_prep", "sp_cursor", "sp_oa", "sp_msforeach"];
224
+ function namePart(token) {
225
+ if (token?.kind === "identifier" && token.text.startsWith("[") && token.text.length > 2)
226
+ return token.text.slice(1, -1).replaceAll("]]", "]");
227
+ return token?.kind === "word" ? token.text : undefined;
228
+ }
229
+ function procedureFormProblem(sql, code) {
230
+ const tokens = code[code.length - 1]?.kind === "semicolon" ? code.slice(0, -1) : code;
231
+ if (!isWord(tokens[0], "EXEC", "EXECUTE"))
232
+ return "Nothing may stand before EXEC.";
233
+ if (tokens.length < 2)
234
+ return "EXEC names no procedure.";
235
+ const parts = [];
236
+ let position = 1;
237
+ for (;;) {
238
+ const part = namePart(tokens[position]);
239
+ if (part === undefined)
240
+ return `${tokens[position]?.text ?? "Nothing"} is not a procedure name.`;
241
+ parts.push(part);
242
+ position++;
243
+ if (!isSymbol(tokens[position], "."))
244
+ break;
245
+ if (parts.length === 2)
246
+ return "The procedure is named by at most a schema and its name, not a database or server.";
247
+ position++;
248
+ }
249
+ const procedure = parts[parts.length - 1];
250
+ const lower = procedure.toLowerCase();
251
+ if (DYNAMIC_SQL_PROCEDURES.includes(lower) || DYNAMIC_SQL_PREFIXES.some((prefix) => lower.startsWith(prefix))) {
252
+ return `${procedure} runs SQL text or code outside the database; a query may not call it.`;
253
+ }
254
+ const args = tokens.slice(position);
255
+ for (let index = 0; index < args.length;) {
256
+ const [at, name, equals, colon, bind] = args.slice(index, index + 5);
257
+ const argument = isSymbol(at, "@") && name?.kind === "word" && touching(at, name) && isSymbol(equals, "=") && isSymbol(colon, ":") && bind?.kind === "word" && touching(colon, bind) && !bind.text.includes("$");
258
+ if (!argument) {
259
+ const shown = args.slice(index, index + 5);
260
+ const last = shown[shown.length - 1];
261
+ return `The argument '${sql.slice(shown[0].start, last.start + last.text.length)}' is not written @name = :placeholder.`;
262
+ }
263
+ index += 5;
264
+ if (index === args.length)
265
+ break;
266
+ if (!isSymbol(args[index], ","))
267
+ return `'${args[index].text}' follows an argument, where only a comma and the next argument may stand.`;
268
+ if (index + 1 === args.length)
269
+ return "The arguments end with a comma.";
270
+ index++;
271
+ }
272
+ return undefined;
273
+ }
274
+ export function procedureCallProblem(sql, dialect) {
275
+ if (!dialect)
276
+ return undefined;
277
+ const tokens = sqlTokens(sql, dialect);
278
+ if (!tokens)
279
+ return undefined;
280
+ const code = tokens.filter((t) => t.kind !== "comment");
281
+ const first = code.find((t) => !isSymbol(t, "("));
282
+ if (!isWord(first, "EXEC", "EXECUTE"))
283
+ return undefined;
284
+ if (dialect !== PROCEDURE_DIALECT) {
285
+ return problem("not_select", `the SQL calls a stored procedure (${first.text.toUpperCase()}), which only a query on a SQL Server (${PROCEDURE_DIALECT}) connection may do; ` +
286
+ `on ${dialect} the instance refuses it (not_select). Write the query as a SELECT.`, "sql_text");
287
+ }
288
+ if (code.some((t, i) => t.kind === "semicolon" && i !== code.length - 1))
289
+ return undefined;
290
+ const why = procedureFormProblem(sql, code);
291
+ if (!why)
292
+ return undefined;
293
+ return problem("procedure_call_form", `${why} A stored-procedure query is exactly ${PROCEDURE_CALL_FORM}, every argument a :placeholder (procedure_call_form).`, "sql_text");
294
+ }
295
+ export function isProcedureCall(sql, dialect) {
296
+ if (dialect !== PROCEDURE_DIALECT)
297
+ return false;
298
+ const code = sqlTokens(sql, dialect)?.filter((t) => t.kind !== "comment");
299
+ return isWord(code?.find((t) => !isSymbol(t, "(")), "EXEC", "EXECUTE");
300
+ }
143
301
  function settledTool(schema, tool) {
144
302
  const settled = settledForm(schema, schema.properties?.[TOOLS_SECTION], [tool]);
145
303
  return Array.isArray(settled) && isObject(settled[0]) ? settled[0] : tool;
@@ -209,6 +367,16 @@ export function checkQueryTools(disk, schema, baseline) {
209
367
  message: `Query tool "${slug}": ${problem.message}`,
210
368
  });
211
369
  }
370
+ const dialect = isObject(query.connection) && typeof query.connection.dialect === "string" ? query.connection.dialect : undefined;
371
+ const call = typeof query.sql_text === "string" ? procedureCallProblem(query.sql_text, dialect) : undefined;
372
+ if (call) {
373
+ findings.push({
374
+ code: call.code,
375
+ severity: "warning",
376
+ ...locate(disk, `/${TOOLS_SECTION}/${index}/${QUERY_FIELD}/${call.at}`),
377
+ message: `Query tool "${slug}": ${call.message}`,
378
+ });
379
+ }
212
380
  }
213
381
  if (!baseline)
214
382
  return findings;
package/dist/install.js CHANGED
@@ -79,7 +79,7 @@ function pypiInstall(facts, p, lower) {
79
79
  return { method: "uv-tool", path: file, update: "uv tool upgrade cavelon", source: "github" };
80
80
  if (follows("pipx", "venvs") || under(facts.env.PIPX_HOME))
81
81
  return { method: "pipx", path: file, update: "pipx upgrade cavelon", source: "github" };
82
- if (lower.includes("uv") && lower.some((s) => s.startsWith("archive-v"))) {
82
+ if ((lower.includes("uv") || under(facts.env.UV_CACHE_DIR)) && lower.some((s) => s.startsWith("archive-v"))) {
83
83
  return { method: "uvx", path: file, advice: "uvx reuses the release it cached; `uvx cavelon@latest` runs the newest.", source: "github" };
84
84
  }
85
85
  return { method: "pip", path: file, update: "pip install --upgrade cavelon", source: "github" };
@@ -11,7 +11,7 @@ export function invocation(file, args, env = process.env, platform = process.pla
11
11
  export function runProgram(file, args, options) {
12
12
  const how = invocation(file, args, options.env);
13
13
  return new Promise((resolve) => {
14
- execFile(how.file, how.args, {
14
+ const child = execFile(how.file, how.args, {
15
15
  env: options.env,
16
16
  cwd: options.cwd,
17
17
  timeout: options.timeoutMs,
@@ -29,6 +29,7 @@ export function runProgram(file, args, options) {
29
29
  return resolve({ code: err.code, stdout, stderr });
30
30
  resolve({ code: null, stdout, stderr, error: err.message });
31
31
  });
32
+ child.stdin?.end();
32
33
  });
33
34
  }
34
35
  export function probeMcpServer(command, args, options) {
@@ -1,14 +1,17 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { bundledSkills, generatedCopy, INSTALLED_MCP_COMMAND, mcpCommand } from "./agents.js";
4
- import { readTextFile, writeFileAtomic } from "./fsutil.js";
4
+ import { readJsonFile, readTextFile, writeFileAtomic } from "./fsutil.js";
5
5
  import { findProgram } from "./git.js";
6
6
  import { isGenerated, removeBlock, removeJsonEntry, upsertBlock, upsertJsonEntry } from "./markers.js";
7
- import { homeDir } from "./paths.js";
7
+ import { cacheDir, homeDir } from "./paths.js";
8
8
  import { runProgram } from "./run-program.js";
9
+ import { KIT_VERSION } from "./version.js";
9
10
  export const MARKETPLACE_SOURCE = "goodguys-gmbh/cavelon-dev-kit";
10
11
  export const MARKETPLACE = "cavelon-dev-kit";
11
12
  export const PLUGIN_ID = "cavelon@cavelon-dev-kit";
13
+ export const GEMINI_EXTENSION = "cavelon";
14
+ export const GEMINI_SOURCE = `https://github.com/${MARKETPLACE_SOURCE}`;
12
15
  function vscodeUserDir(env, platform) {
13
16
  const home = homeDir(env);
14
17
  if (platform === "win32")
@@ -18,11 +21,14 @@ function vscodeUserDir(env, platform) {
18
21
  return path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "Code", "User");
19
22
  }
20
23
  const json = (file, key = "mcpServers", extra = {}) => ({ file, format: "json", keys: [key, "cavelon"], extra });
24
+ function geminiHome(env) {
25
+ return path.join(env.GEMINI_CLI_HOME || homeDir(env), ".gemini");
26
+ }
21
27
  export function setupAgents(env, platform = process.platform) {
22
28
  const home = homeDir(env);
23
29
  const claudeDir = env.CLAUDE_CONFIG_DIR || path.join(home, ".claude");
24
30
  const codexDir = env.CODEX_HOME || path.join(home, ".codex");
25
- const geminiDir = path.join(env.GEMINI_CLI_HOME || home, ".gemini");
31
+ const geminiDir = geminiHome(env);
26
32
  const vscode = vscodeUserDir(env, platform);
27
33
  return [
28
34
  {
@@ -64,6 +70,7 @@ export function setupAgents(env, platform = process.platform) {
64
70
  label: "Gemini CLI",
65
71
  commands: ["gemini"],
66
72
  folders: [geminiDir],
73
+ plugin: "gemini",
67
74
  mcp: json(path.join(geminiDir, "settings.json")),
68
75
  skills: path.join(geminiDir, "skills"),
69
76
  },
@@ -146,6 +153,10 @@ async function pluginState(kind, program, env) {
146
153
  return { error: `\`${display(program, args)}\` did not answer in JSON` };
147
154
  }
148
155
  };
156
+ if (kind === "gemini") {
157
+ const manifest = await readJsonFile(path.join(geminiHome(env), "extensions", GEMINI_EXTENSION, "gemini-extension.json"));
158
+ return { marketplace: true, installed: manifest?.name === GEMINI_EXTENSION, enabled: true };
159
+ }
149
160
  const plugins = await read(["plugin", "list", "--json"]);
150
161
  if ("error" in plugins)
151
162
  return { error: plugins.error };
@@ -165,7 +176,25 @@ async function pluginState(kind, program, env) {
165
176
  function firstLine(text) {
166
177
  return (text.split(/\r?\n/).find((l) => l.trim()) ?? "").trim().slice(0, 300);
167
178
  }
179
+ function lastLine(text) {
180
+ return (text.split(/\r?\n/).findLast((l) => l.trim()) ?? "").trim().slice(0, 300);
181
+ }
182
+ async function geminiFolder(kind, env) {
183
+ if (kind !== "gemini")
184
+ return undefined;
185
+ const dir = path.join(cacheDir(env), "gemini");
186
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
187
+ return dir;
188
+ }
168
189
  function pluginCommands(kind) {
190
+ if (kind === "gemini") {
191
+ return {
192
+ marketplaceAdd: [],
193
+ marketplaceRemove: [],
194
+ install: ["extensions", "install", GEMINI_SOURCE, "--ref", `v${KIT_VERSION}`, "--consent"],
195
+ uninstall: ["extensions", "uninstall", GEMINI_EXTENSION],
196
+ };
197
+ }
169
198
  return {
170
199
  marketplaceAdd: ["plugin", "marketplace", "add", MARKETPLACE_SOURCE],
171
200
  marketplaceRemove: ["plugin", "marketplace", "remove", MARKETPLACE],
@@ -175,23 +204,23 @@ function pluginCommands(kind) {
175
204
  }
176
205
  export async function planAgent(agent, found, env, command, skills, platform = process.platform) {
177
206
  const usePlugin = Boolean(agent.plugin && found.program);
207
+ const state = usePlugin ? await pluginState(agent.plugin, found.program, env) : undefined;
178
208
  const plan = { agent, found, method: usePlugin ? "plugin" : "files", changes: [] };
179
- if (usePlugin) {
209
+ if (usePlugin && state) {
180
210
  const kind = agent.plugin;
181
211
  const program = found.program;
182
212
  const commands = pluginCommands(kind);
183
- const state = await pluginState(kind, program, env);
184
213
  if ("error" in state) {
185
214
  plan.changes.push({ kind: "plugin", summary: "install the Cavelon plugin", target: display(program, commands.install), outcome: "failed", reason: state.error });
186
215
  return plan;
187
216
  }
188
217
  plan.plugin = state;
189
- if (!state.marketplace) {
218
+ if (!state.marketplace && commands.marketplaceAdd.length) {
190
219
  plan.changes.push({ kind: "marketplace", summary: "add the Cavelon plugin marketplace", target: display(program, commands.marketplaceAdd), outcome: "planned" });
191
220
  }
192
221
  plan.changes.push({
193
222
  kind: "plugin",
194
- summary: "install the Cavelon plugin (skills and tools)",
223
+ summary: kind === "gemini" ? "install the Cavelon extension (skills and tools)" : "install the Cavelon plugin (skills and tools)",
195
224
  target: display(program, commands.install),
196
225
  outcome: state.installed ? "unchanged" : "planned",
197
226
  ...(state.installed && !state.enabled ? { reason: `it is installed but turned off; turn it on in ${agent.label}` } : {}),
@@ -306,11 +335,19 @@ export async function applyPlan(plan, env, command, skills, record) {
306
335
  }
307
336
  try {
308
337
  if (change.kind === "marketplace" || change.kind === "plugin") {
309
- const commands = pluginCommands(plan.agent.plugin);
338
+ const kind = plan.agent.plugin;
339
+ const commands = pluginCommands(kind);
310
340
  const args = change.kind === "marketplace" ? commands.marketplaceAdd : commands.install;
311
- const result = await runProgram(plan.found.program, args, { env, timeoutMs: RUN_TIMEOUT_MS });
341
+ const result = await runProgram(plan.found.program, args, { env, timeoutMs: RUN_TIMEOUT_MS, cwd: await geminiFolder(kind, env) });
312
342
  if (result.code !== 0) {
313
- done.push({ ...change, outcome: "failed", reason: result.error ?? firstLine(result.stderr || result.stdout) ?? `exit ${result.code}` });
343
+ if (kind === "gemini") {
344
+ const reason = result.error ?? (lastLine(`${result.stdout}\n${result.stderr}`) || `exit ${result.code}`);
345
+ done.push({ ...change, outcome: "skipped", reason: `${reason}; the tools server and skills go into Gemini CLI's files instead` });
346
+ done.push(await mcpChange(plan.agent.mcp, command, true, record));
347
+ done.push(await skillsChange(plan.agent.skills, skills, true, record));
348
+ break;
349
+ }
350
+ done.push({ ...change, outcome: "failed", reason: result.error ?? (firstLine(result.stderr || result.stdout) || `exit ${result.code}`) });
314
351
  break;
315
352
  }
316
353
  if (change.kind === "marketplace")
@@ -318,6 +355,8 @@ export async function applyPlan(plan, env, command, skills, record) {
318
355
  else
319
356
  record.plugin_installed = true;
320
357
  done.push({ ...change, outcome: "done" });
358
+ if (kind === "gemini" && change.kind === "plugin")
359
+ done.push(...(await removeFiles(plan.agent, record, skills, new Set())));
321
360
  }
322
361
  else if (change.kind === "mcp") {
323
362
  done.push(await mcpChange(plan.agent.mcp, command, true, record));
@@ -340,7 +379,7 @@ export async function removeAgent(agent, record, env, skills, sharedSkillDirs) {
340
379
  const commands = pluginCommands(agent.plugin);
341
380
  const steps = [];
342
381
  if (record.plugin_installed)
343
- steps.push(["plugin", commands.uninstall, "uninstall the Cavelon plugin", "plugin_installed"]);
382
+ steps.push(["plugin", commands.uninstall, `uninstall the Cavelon ${agent.plugin === "gemini" ? "extension" : "plugin"}`, "plugin_installed"]);
344
383
  if (record.marketplace_added)
345
384
  steps.push(["marketplace", commands.marketplaceRemove, "remove the Cavelon plugin marketplace", "marketplace_added"]);
346
385
  for (const [kind, args, summary, key] of steps) {
@@ -348,7 +387,7 @@ export async function removeAgent(agent, record, env, skills, sharedSkillDirs) {
348
387
  changes.push({ kind, summary, target: [agent.commands[0], ...args].join(" "), outcome: "failed", reason: `${agent.commands[0]} is not on the PATH; run it yourself` });
349
388
  continue;
350
389
  }
351
- const result = await runProgram(found.program, args, { env, timeoutMs: RUN_TIMEOUT_MS });
390
+ const result = await runProgram(found.program, args, { env, timeoutMs: RUN_TIMEOUT_MS, cwd: await geminiFolder(agent.plugin, env) });
352
391
  if (result.code === 0) {
353
392
  delete record[key];
354
393
  changes.push({ kind, summary, target: display(found.program, args), outcome: "removed" });
@@ -358,6 +397,11 @@ export async function removeAgent(agent, record, env, skills, sharedSkillDirs) {
358
397
  }
359
398
  }
360
399
  }
400
+ changes.push(...(await removeFiles(agent, record, skills, sharedSkillDirs)));
401
+ return changes;
402
+ }
403
+ async function removeFiles(agent, record, skills, sharedSkillDirs) {
404
+ const changes = [];
361
405
  if (record.mcp) {
362
406
  const change = await removeMcp(agent.mcp, record.mcp);
363
407
  if (change.outcome !== "failed" && change.outcome !== "skipped")
@@ -444,23 +488,25 @@ async function topmostMissing(dir) {
444
488
  export async function checkAgent(agent, env, record, platform = process.platform) {
445
489
  const found = await findAgent(agent, env, platform);
446
490
  const check = { name: agent.name, label: agent.label, found: Boolean(found.program || found.folder), method: null, ok: true, details: [], servers: [] };
447
- if (agent.plugin && found.program) {
491
+ const state = agent.plugin && found.program ? await pluginState(agent.plugin, found.program, env) : undefined;
492
+ const viaFiles = !state || (agent.plugin === "gemini" && ("error" in state || !state.installed));
493
+ const what = agent.plugin === "gemini" ? "extension" : "plugin";
494
+ if (state && !viaFiles) {
448
495
  check.method = "plugin";
449
- const state = await pluginState(agent.plugin, found.program, env);
450
496
  if ("error" in state) {
451
497
  check.ok = false;
452
498
  check.details.push(`could not ask ${agent.label} about its plugins: ${state.error}`);
453
499
  }
454
500
  else if (!state.installed) {
455
501
  check.ok = false;
456
- check.details.push("the Cavelon plugin is not installed");
502
+ check.details.push(`the Cavelon ${what} is not installed`);
457
503
  }
458
504
  else if (!state.enabled) {
459
505
  check.ok = false;
460
- check.details.push(`the Cavelon plugin is installed but turned off; turn it on in ${agent.label}`);
506
+ check.details.push(`the Cavelon ${what} is installed but turned off; turn it on in ${agent.label}`);
461
507
  }
462
508
  else {
463
- check.details.push("the Cavelon plugin is installed");
509
+ check.details.push(`the Cavelon ${what} is installed`);
464
510
  if (platform !== "win32")
465
511
  check.servers.push(await serverCommand(env, platform));
466
512
  }
@@ -388,6 +388,18 @@ says who does what on the instance.
388
388
  postal code) rather than one guessable key. Each `:name` in the SQL needs
389
389
  exactly one parameter of that name (a literal colon is `\:`); validate checks
390
390
  this (`bind_mismatch`) and each parameter's type and constraints.
391
+ - **Stored procedures (SQL Server only).** On an `mssql` connection the SQL
392
+ may instead be exactly one call, `EXEC [schema].[procedure] @p1 = :p1, @p2 =
393
+ :p2`: every argument a placeholder with a declared parameter, no literal,
394
+ `OUTPUT`, option or dynamic SQL (`procedure_call_form`; on another dialect
395
+ `not_select`). `cavelon validate` warns of both. Put fixed values inside the
396
+ procedure. The model gets the first result set. The instance saves, enables
397
+ and runs such a query only while the connection's last test found no write
398
+ privileges, acknowledged or not (`write_privileges_block_procedure`), and
399
+ only for a procedure whose definition the login may read and that only
400
+ reads (`procedure_definition_unreadable`, `procedure_definition_writes`):
401
+ ask the person for a read-only login with `EXECUTE` and `VIEW DEFINITION`
402
+ on procedures that read. Where a procedure is not needed, write a `SELECT`.
391
403
  - `cavelon explain <code>` explains every code the connector uses: what
392
404
  `validate` and the preview name, the codes of a failed call (`timeout`,
393
405
  `identity_required`, …) and of a connection test.
@@ -106,9 +106,12 @@ use it when you parse the result.
106
106
  `mssql` (SQL Server). A SQL Server login that can write keeps the
107
107
  connection's queries from running (`write_privileges_unacknowledged`) until
108
108
  it may only read or a superadmin acknowledges it in the Admin, so ask for a
109
- read-only login. `cavelon db connections` shows which exist, whether their
109
+ read-only login. A stored-procedure query (`EXEC`, SQL Server only) needs
110
+ one without any write privileges, acknowledged or not
111
+ (`write_privileges_block_procedure`), and a procedure that only reads.
112
+ `cavelon db connections` shows which exist, whether their
110
113
  last test passed, when their CA certificates expire and why a connection's
111
- queries cannot be enabled. A pull writes each query's SQL into
114
+ queries, or its stored-procedure queries, cannot be enabled. A pull writes each query's SQL into
112
115
  `package/tools.yaml`, so the repository holds it: review it like code.
113
116
 
114
117
  ## The loop
@@ -152,6 +152,13 @@ the Admin. Then:
152
152
  Owner runs it once with `cavelon db test-run <query> --value <name>=<value>`,
153
153
  identity parameters included; it shows what the model would see. Never put
154
154
  a real customer's data into a test file.
155
+ - A stored-procedure query (SQL Server) is test-run the same way; the
156
+ instance refuses the run while the connection's login can write or the
157
+ procedure's definition writes or cannot be read, with a code
158
+ `cavelon explain` explains. A run whose procedure committed or rolled back
159
+ fails with `query_failed` and a `notice`: the query is switched off, and a
160
+ person fixes the procedure. `cavelon db test <connection>` lists the
161
+ procedure queries whose procedure no longer passes (`procedure_findings`).
155
162
  - `cavelon db runs <query>` lists each run's outcome and error code (never a
156
163
  value or a row), and `cavelon trace` shows the code a failed call answered
157
164
  the model with on the tool's span (`error_code`); `cavelon explain <code>`
@@ -224,12 +224,23 @@ const PLUGIN_UPDATE = {
224
224
  claude: "`claude plugin marketplace update cavelon-dev-kit` and `claude plugin update cavelon@cavelon-dev-kit`",
225
225
  codex: "`codex plugin marketplace upgrade cavelon-dev-kit` and `codex plugin add cavelon@cavelon-dev-kit`",
226
226
  };
227
+ const INSTALL_DOCS = `https://github.com/${REPOSITORY}/blob/main/docs/install`;
227
228
  function pluginUpdate(client) {
228
229
  const name = client?.toLowerCase() ?? "";
229
230
  if (name.includes("claude"))
230
- return PLUGIN_UPDATE.claude;
231
+ return `with ${PLUGIN_UPDATE.claude}`;
231
232
  if (name.includes("codex"))
232
- return PLUGIN_UPDATE.codex;
233
+ return `with ${PLUGIN_UPDATE.codex}`;
234
+ if (name.includes("gemini"))
235
+ return "with `gemini extensions update cavelon`";
236
+ if (name.includes("cursor"))
237
+ return `as ${INSTALL_DOCS}/cursor.md#update says`;
238
+ if (name.includes("kiro"))
239
+ return `as ${INSTALL_DOCS}/kiro.md#update says`;
240
+ if (name.includes("copilot"))
241
+ return "with `copilot plugin update cavelon`";
242
+ if (name.includes("visual studio code") || name.includes("vscode"))
243
+ return `as ${INSTALL_DOCS}/vscode-copilot.md#update says`;
233
244
  return undefined;
234
245
  }
235
246
  export function sessionWarning(facts) {
@@ -249,10 +260,12 @@ export function sessionWarning(facts) {
249
260
  if (pluginBehind) {
250
261
  said.push(`The Cavelon plugin is ${plugin}${latest ? "" : `, older than cavelon ${newest}`}.`);
251
262
  const commands = pluginUpdate(facts.client);
252
- asks.push(commands ? `Update the plugin with ${commands}.` : `Update the plugin: in Claude Code with ${PLUGIN_UPDATE.claude}; in Codex with ${PLUGIN_UPDATE.codex}.`);
263
+ asks.push(commands
264
+ ? `Update the plugin ${commands}.`
265
+ : `Update the plugin: in Claude Code with ${PLUGIN_UPDATE.claude}; in Codex with ${PLUGIN_UPDATE.codex}; in another agent as its page in ${INSTALL_DOCS}/ says.`);
253
266
  }
254
267
  else if (latest && plugin === undefined && pluginUpdate(facts.client)) {
255
- asks.push(`If they use the Cavelon plugin, also update it with ${pluginUpdate(facts.client)}.`);
268
+ asks.push(`If they use the Cavelon plugin, also update it ${pluginUpdate(facts.client)}.`);
256
269
  }
257
270
  if (skillsBehind) {
258
271
  said.push(`The skills \`cavelon init --agents\` wrote in this solution folder are from cavelon ${skills}.`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cavelon/cli",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "The cavelon binary: CLI and local MCP server for building Cavelon solutions with a coding agent.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/goodguys-gmbh/cavelon-dev-kit",