@cavelon/cli 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +34 -15
  2. package/dist/access.js +194 -0
  3. package/dist/acting.js +123 -0
  4. package/dist/agent-env.js +20 -2
  5. package/dist/change-confirmation.js +93 -0
  6. package/dist/commands/api.js +77 -30
  7. package/dist/commands/chat.js +16 -8
  8. package/dist/commands/db.js +474 -0
  9. package/dist/commands/docs.js +83 -7
  10. package/dist/commands/index.js +7 -0
  11. package/dist/commands/limits-set.js +11 -5
  12. package/dist/commands/loops.js +72 -9
  13. package/dist/commands/models.js +12 -6
  14. package/dist/commands/sandboxes.js +7 -2
  15. package/dist/commands/session.js +111 -24
  16. package/dist/commands/setup.js +1 -1
  17. package/dist/commands/solution.js +211 -54
  18. package/dist/commands/tenants.js +55 -12
  19. package/dist/commands/values.js +104 -23
  20. package/dist/commands/work.js +13 -5
  21. package/dist/confirm-token.js +90 -7
  22. package/dist/context.js +5 -1
  23. package/dist/contracts.js +37 -12
  24. package/dist/database-queries.js +301 -0
  25. package/dist/fsutil.js +14 -0
  26. package/dist/http.js +69 -3
  27. package/dist/install.js +30 -0
  28. package/dist/invoke.js +12 -2
  29. package/dist/kit-codes.js +9 -2
  30. package/dist/mcp.js +106 -19
  31. package/dist/openapi.js +7 -0
  32. package/dist/package-check.js +19 -0
  33. package/dist/preview-report.js +2 -2
  34. package/dist/principal.js +24 -2
  35. package/dist/printed.js +5 -0
  36. package/dist/secret-access.js +30 -9
  37. package/dist/session.js +36 -8
  38. package/dist/skills/cavelon-authoring/SKILL.md +93 -10
  39. package/dist/skills/cavelon-long-running/SKILL.md +18 -8
  40. package/dist/skills/cavelon-loop/SKILL.md +126 -41
  41. package/dist/skills/cavelon-testing/SKILL.md +32 -3
  42. package/dist/trace-view.js +10 -0
  43. package/dist/update-check.js +2 -2
  44. package/dist/user-config.js +24 -0
  45. package/package.json +1 -1
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { actingTarget, targetLine } from "./acting.js";
2
3
  import { drivenByAgent } from "./agent-env.js";
3
4
  import { CavelonError, ExitCode } from "./errors.js";
4
5
  import { canonical } from "./package-files.js";
5
- import { PREVIEW_TOKEN } from "./printed.js";
6
+ import { personCommand, PREVIEW_TOKEN } from "./printed.js";
6
7
  export const CONFIRM_TOKEN = /^[0-9a-f]{12}$/;
7
8
  export function confirmToken(target, tool, change) {
8
9
  return createHash("sha256")
@@ -23,30 +24,76 @@ export function withToken(printed, token) {
23
24
  return `${command.slice(0, at)} --confirm ${token}${command.slice(at + " --confirm".length)}`;
24
25
  return `${command} --confirm ${token}`;
25
26
  }
26
- export async function confirmation(ctx, input, tool, change) {
27
+ export const PERSON_CONFIRMS_HELP = "A coding agent cannot confirm it: over MCP the client asks the person, and from an agent's shell the person runs the\n" +
28
+ "confirm in their own terminal.";
29
+ export async function confirmation(ctx, input, tool, change, options = {}) {
30
+ const gate = await gateOf(ctx, input, tool, change, options);
31
+ if (gate.confirmed)
32
+ return { ...gate, where: "" };
33
+ const target = await actingTarget(ctx, options);
34
+ return { ...gate, fields: { target, ...gate.fields }, where: targetLine(target) };
35
+ }
36
+ async function gateOf(ctx, input, tool, change, options) {
27
37
  const given = input.options.confirm;
28
38
  const driven = drivenByAgent(ctx);
29
39
  const tokenGiven = typeof given === "string" && given !== "";
30
- if (!driven && !tokenGiven)
40
+ const approve = () => {
41
+ if (!driven)
42
+ ctx.approved = { guarded: Boolean(options.person) };
43
+ };
44
+ if (!driven && !tokenGiven) {
45
+ if (given === true)
46
+ approve();
31
47
  return { confirmed: given === true, fields: {}, confirm: (command) => command };
48
+ }
32
49
  if (driven?.by === "mcp" && given === true)
33
50
  throw confirmTokenRequired(tool);
34
51
  const session = await ctx.session();
35
52
  const token = confirmToken({ url: session.url, tenant: session.tenant }, tool, change);
53
+ const person = driven && options.person ? { ...options.person, route: personRoute(ctx, driven) } : undefined;
54
+ if (person) {
55
+ const command = personCommand(...person.words);
56
+ const confirm = () => (person.route === "client" ? confirmThroughClient(tool, token) : confirmInTerminal(command));
57
+ const fields = { ...(person.route === "client" ? { confirm_token: token } : {}), needs_person: person.route };
58
+ if (given === true || given === "") {
59
+ return {
60
+ confirmed: false,
61
+ fields,
62
+ confirm,
63
+ mismatch: "A coding agent cannot confirm this change; nothing was changed: the person confirms it in their own terminal.",
64
+ exitCode: ExitCode.needsAction,
65
+ };
66
+ }
67
+ if (!tokenGiven)
68
+ return { confirmed: false, fields, confirm };
69
+ if (given === token) {
70
+ await personApproves(ctx, driven, { tool, what: person.what, command }, options);
71
+ return { confirmed: true, fields: {}, confirm };
72
+ }
73
+ return {
74
+ confirmed: false,
75
+ fields: { ...fields, token_mismatch: true },
76
+ confirm,
77
+ mismatch: "The confirm token is not this change's: the change differs from its preview, or the token is another one's. Nothing was changed.",
78
+ exitCode: ExitCode.conflict,
79
+ };
80
+ }
36
81
  const confirm = (command) => (driven?.by === "mcp" ? confirmWith(tool, token) : driven ? withToken(command, token) : command);
37
82
  if (given === true && driven?.by === "agent") {
38
83
  return {
39
84
  confirmed: false,
40
85
  fields: { confirm_token: token, token_required: true },
41
86
  confirm,
42
- mismatch: `--confirm alone does not confirm when a coding agent runs cavelon (${driven.variable} is set). Nothing was changed: show the person this preview, and with their yes run the command below, which carries this change's token.`,
87
+ mismatch: `--confirm alone does not confirm when a coding agent runs cavelon. Nothing was changed: show the person this preview, and with their yes run the command below, which carries this change's token.`,
43
88
  exitCode: ExitCode.needsAction,
44
89
  };
45
90
  }
46
91
  if (!tokenGiven)
47
92
  return { confirmed: false, fields: { confirm_token: token }, confirm };
48
- if (given === token)
93
+ if (given === token) {
94
+ approve();
49
95
  return { confirmed: true, fields: {}, confirm };
96
+ }
50
97
  return {
51
98
  confirmed: false,
52
99
  fields: { confirm_token: token, token_mismatch: true },
@@ -55,10 +102,46 @@ export async function confirmation(ctx, input, tool, change) {
55
102
  exitCode: ExitCode.conflict,
56
103
  };
57
104
  }
58
- export function shellTokenRequired(command, variable) {
105
+ export function personRoute(ctx, driven) {
106
+ return driven.by === "mcp" && ctx.askPerson ? "client" : "terminal";
107
+ }
108
+ export const PERSON_WAIT_MS = 10 * 60_000;
109
+ export async function personApproves(ctx, driven, change, target = {}) {
110
+ if (personRoute(ctx, driven) === "terminal")
111
+ throw needsPerson(change.command);
112
+ const where = targetLine(await actingTarget(ctx, target));
113
+ const answer = await ctx.askPerson([change.what, where, `A coding agent asks to make this change through cavelon (${change.tool}). Approve only this exact change.`].filter(Boolean).join("\n"));
114
+ if (answer === "approved") {
115
+ ctx.approved = { guarded: change.guarded ?? true };
116
+ return;
117
+ }
118
+ throw new CavelonError(ExitCode.needsAction, {
119
+ code: "confirm_declined",
120
+ message: answer === "declined"
121
+ ? "The person did not approve the change; nothing was changed."
122
+ : `The person did not answer within ${PERSON_WAIT_MS / 60_000} minutes, or the client could not ask; nothing was changed.`,
123
+ hint: `Ask the person whether they want it. With their yes, call ${change.tool} again with the same confirm token, or they run ${change.command} in their own terminal.`,
124
+ details: { answer, person_command: change.command },
125
+ });
126
+ }
127
+ export function needsPerson(command) {
128
+ return new CavelonError(ExitCode.needsAction, {
129
+ code: "confirm_needs_person",
130
+ message: `A coding agent cannot confirm this change; nothing was changed. The person confirms it in their own terminal: ${command}`,
131
+ hint: "Show the person the preview and the command; they run it themselves, outside the agent.",
132
+ details: { person_command: command },
133
+ });
134
+ }
135
+ export function confirmThroughClient(tool, token) {
136
+ return `Show the person this, then call ${tool} again with the same arguments and confirm: "${token}": the client then asks the person to approve exactly this change, and nothing changes without their yes.`;
137
+ }
138
+ export function confirmInTerminal(command) {
139
+ return `${command} (the person runs it in their own terminal: a coding agent cannot confirm this change)`;
140
+ }
141
+ export function shellTokenRequired(command) {
59
142
  return new CavelonError(ExitCode.needsAction, {
60
143
  code: "confirm_token_required",
61
- message: `--confirm alone does not confirm when a coding agent runs cavelon (${variable} is set); nothing was changed.`,
144
+ message: "--confirm alone does not confirm when a coding agent runs cavelon; nothing was changed.",
62
145
  hint: `Run \`${command}\` without --confirm, show the person the preview, and with their yes run the command it prints, which carries the change's token.`,
63
146
  });
64
147
  }
package/dist/context.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { checkKeyTenant } from "./acting.js";
1
2
  import { Contracts } from "./contracts.js";
3
+ import { changeConfirmer } from "./change-confirmation.js";
2
4
  import { ApiClient } from "./http.js";
3
5
  import { colorEnabled, styleFor } from "./io.js";
4
6
  import { requireInstance, requireToken, resolveSession, resolveTenantId } from "./session.js";
@@ -32,7 +34,9 @@ export function createContext(io, globals, mode = "cli") {
32
34
  clientPromise ??= (async () => {
33
35
  const session = await ctx.session();
34
36
  const client = new ApiClient({ url: requireInstance(session), token: requireToken(session) }, io.env);
35
- client.target.tenantId = await resolveTenantId(io.env, session, client);
37
+ client.confirmer = changeConfirmer(ctx, client);
38
+ client.target.tenantId =
39
+ session.tokenKind === "api_key" ? await checkKeyTenant(client, session, (m) => ctx.warn(m)) : await resolveTenantId(io.env, session, client, io.now());
36
40
  return client;
37
41
  })();
38
42
  return clientPromise;
package/dist/contracts.js CHANGED
@@ -4,7 +4,7 @@ import { CavelonError, ExitCode } from "./errors.js";
4
4
  import { NOT_HERE } from "./http.js";
5
5
  import { cacheDir, instanceKey } from "./paths.js";
6
6
  import { cavelonCommand } from "./printed.js";
7
- import { readJsonFile, readTextFile, writeFileAtomic } from "./fsutil.js";
7
+ import { readJsonFile, readTextFile, writePrivateFile } from "./fsutil.js";
8
8
  import { SUPPORTED_CONTRACTS } from "./version.js";
9
9
  const NOT_MODIFIED = Symbol("not modified");
10
10
  const RELEASE_TTL_SECONDS = 3600;
@@ -37,6 +37,9 @@ export class Contracts {
37
37
  static isDevelopment(version) {
38
38
  return version === "unknown" || /dev|snapshot|local/i.test(version);
39
39
  }
40
+ async write(file, content) {
41
+ await writePrivateFile(cacheDir(this.env), file, content);
42
+ }
40
43
  versionDir(version) {
41
44
  return path.join(this.root, version.replace(/[^A-Za-z0-9._-]+/g, "_"));
42
45
  }
@@ -49,12 +52,14 @@ export class Contracts {
49
52
  if (this.caps !== undefined && !options.refresh)
50
53
  return this.caps;
51
54
  const state = await readJsonFile(path.join(this.root, "state.json"));
52
- if (!options.refresh && state && this.fresh(state.checked_at, state.version)) {
53
- const cached = await readJsonFile(path.join(this.versionDir(state.version), "capabilities.json"));
55
+ if (!options.refresh && state) {
56
+ const file = path.join(this.versionDir(state.version), this.cacheName("capabilities.json"));
57
+ const meta = await readJsonFile(`${file}.meta.json`);
58
+ const cached = this.fresh(meta?.fetched_at, state.version) ? await readJsonFile(file) : undefined;
54
59
  if (cached) {
55
60
  this.caps = cached;
56
61
  this.versionValue = state.version;
57
- this.cachedAt = state.checked_at;
62
+ this.cachedAt = meta?.fetched_at;
58
63
  return cached;
59
64
  }
60
65
  }
@@ -76,9 +81,11 @@ export class Contracts {
76
81
  else {
77
82
  this.caps = response.data;
78
83
  this.versionValue = response.data.instance.version || "unknown";
79
- await writeFileAtomic(path.join(this.versionDir(this.versionValue), "capabilities.json"), JSON.stringify(response.data, null, 2));
84
+ const file = path.join(this.versionDir(this.versionValue), this.cacheName("capabilities.json"));
85
+ await this.write(file, JSON.stringify(response.data, null, 2));
86
+ await this.write(`${file}.meta.json`, JSON.stringify({ fetched_at: now }));
80
87
  }
81
- await writeFileAtomic(path.join(this.root, "state.json"), JSON.stringify({ version: this.versionValue, checked_at: now }, null, 2));
88
+ await this.write(path.join(this.root, "state.json"), JSON.stringify({ version: this.versionValue, checked_at: now }, null, 2));
82
89
  return this.caps;
83
90
  }
84
91
  async liveCapabilities() {
@@ -112,11 +119,11 @@ export class Contracts {
112
119
  if (loaded === NOT_MODIFIED) {
113
120
  if (!cached)
114
121
  throw new Error(`${file}: the instance answered 304 Not Modified without being sent an ETag.`);
115
- await writeFileAtomic(metaFile, JSON.stringify({ ...meta, fetched_at: fetchedAt }));
122
+ await this.write(metaFile, JSON.stringify({ ...meta, fetched_at: fetchedAt }));
116
123
  return cached.value;
117
124
  }
118
- await writeFileAtomic(target, loaded.serialized);
119
- await writeFileAtomic(metaFile, JSON.stringify({ fetched_at: fetchedAt, ...(loaded.etag ? { etag: loaded.etag } : {}) }));
125
+ await this.write(target, loaded.serialized);
126
+ await this.write(metaFile, JSON.stringify({ fetched_at: fetchedAt, ...(loaded.etag ? { etag: loaded.etag } : {}) }));
120
127
  return loaded.value;
121
128
  }
122
129
  async getJson(route, etag, options = {}) {
@@ -188,7 +195,7 @@ export class Contracts {
188
195
  const state = await readJsonFile(path.join(this.root, "state.json"));
189
196
  if (!state)
190
197
  return undefined;
191
- const target = path.join(this.versionDir(state.version), file);
198
+ const target = path.join(this.versionDir(state.version), this.cacheName(file));
192
199
  const text = await readTextFile(target);
193
200
  if (text === undefined)
194
201
  return undefined;
@@ -199,7 +206,7 @@ export class Contracts {
199
206
  catch {
200
207
  return undefined;
201
208
  }
202
- const meta = file === "capabilities.json" ? { fetched_at: state.checked_at } : await readJsonFile(`${target}.meta.json`);
209
+ const meta = await readJsonFile(`${target}.meta.json`);
203
210
  return {
204
211
  value,
205
212
  version: state.version,
@@ -212,8 +219,26 @@ export class Contracts {
212
219
  static packageSchemaFile(version) {
213
220
  return `package-schema-${version.replace(/[^A-Za-z0-9._-]+/g, "_")}.json`;
214
221
  }
222
+ audience() {
223
+ const { token = "", tenantId = "" } = this.client.target;
224
+ const tenant = token.startsWith("cbp_") ? "" : tenantId;
225
+ return createHash("sha256").update(`cavelon-audience\0${token}\0${tenant}`).digest("hex").slice(0, 16);
226
+ }
227
+ tenantKey() {
228
+ const { token = "", tenantId = "" } = this.client.target;
229
+ if (!tenantId || token.startsWith("cbp_"))
230
+ return this.audience();
231
+ return createHash("sha256").update(`cavelon-tenant\0${tenantId}`).digest("hex").slice(0, 16);
232
+ }
233
+ cacheName(file) {
234
+ return file === "capabilities.json" ? Contracts.keyedName(file, this.tenantKey()) : file;
235
+ }
236
+ static keyedName(file, key) {
237
+ const dot = file.lastIndexOf(".");
238
+ return dot > 0 ? `${file.slice(0, dot)}.${key}${file.slice(dot)}` : `${file}.${key}`;
239
+ }
215
240
  async text(file, load, options = {}) {
216
- return this.cached(file, async () => {
241
+ return this.cached(Contracts.keyedName(file, this.audience()), async () => {
217
242
  const text = await load();
218
243
  return { value: text, serialized: text };
219
244
  }, (text) => text, options);
@@ -0,0 +1,301 @@
1
+ import path from "node:path";
2
+ import { readJsonFile } from "./fsutil.js";
3
+ import { stateDir, writeState } from "./local-state.js";
4
+ import { locate } from "./package-files.js";
5
+ import { canonical, settledForm } from "./package-format.js";
6
+ export const QUERY_TOOL_TYPE = "database_query";
7
+ const QUERY_FIELD = "database_query";
8
+ const TOOLS_SECTION = "tools";
9
+ const DERIVED_FIELDS = ["params_json_schema", "default_config"];
10
+ const QUERY_FIELDS = ["name", "description", QUERY_FIELD];
11
+ export const QUERY_CHANGED_CODE = "database_query_changed";
12
+ export const QUERY_FIELDS_IGNORED_CODE = "database_query_fields_ignored";
13
+ export const NEEDS_SUPERADMIN_CODE = "database_query_needs_superadmin";
14
+ const BASELINE_FILE = "database-queries.json";
15
+ const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
16
+ function resolveRef(schema, node) {
17
+ let current = isObject(node) ? node : undefined;
18
+ for (let hops = 0; current && typeof current.$ref === "string" && hops < 10; hops++) {
19
+ const ref = current.$ref;
20
+ if (!ref.startsWith("#/$defs/"))
21
+ return undefined;
22
+ current = schema.$defs?.[ref.slice("#/$defs/".length)];
23
+ }
24
+ return current;
25
+ }
26
+ function toolSchema(schema) {
27
+ if (!schema)
28
+ return undefined;
29
+ const tools = resolveRef(schema, schema.properties?.[TOOLS_SECTION]);
30
+ return resolveRef(schema, tools?.items);
31
+ }
32
+ export function schemaKnowsQueries(schema) {
33
+ const properties = toolSchema(schema)?.properties;
34
+ return isObject(properties) && QUERY_FIELD in properties;
35
+ }
36
+ function parameterSchema(schema) {
37
+ const field = toolSchema(schema)?.properties?.[QUERY_FIELD];
38
+ const branches = isObject(field) && Array.isArray(field.anyOf) ? field.anyOf : [field];
39
+ for (const branch of branches) {
40
+ const query = resolveRef(schema, branch);
41
+ const parameters = query?.properties?.parameters;
42
+ const items = isObject(parameters) ? resolveRef(schema, parameters.items) : undefined;
43
+ if (items)
44
+ return items;
45
+ }
46
+ return undefined;
47
+ }
48
+ export function queryTools(pkg) {
49
+ const tools = pkg[TOOLS_SECTION];
50
+ if (!Array.isArray(tools))
51
+ return [];
52
+ return tools.flatMap((tool, index) => isObject(tool) && tool.tool_type === QUERY_TOOL_TYPE && typeof tool.slug === "string" ? [{ index, slug: tool.slug, tool }] : []);
53
+ }
54
+ const BIND = /(?<![:\p{L}\p{N}_\\]):([\p{L}\p{N}_]+)(?!:)/gu;
55
+ export function bindNames(sql) {
56
+ const names = [];
57
+ for (const match of sql.matchAll(BIND))
58
+ if (!names.includes(match[1]))
59
+ names.push(match[1]);
60
+ return names;
61
+ }
62
+ const CONSTRAINTS_BY_TYPE = {
63
+ string: ["max_length", "pattern", "enum"],
64
+ integer: ["minimum", "maximum", "enum"],
65
+ number: ["minimum", "maximum", "enum"],
66
+ };
67
+ const CONSTRAINTS = ["max_length", "pattern", "enum", "minimum", "maximum"];
68
+ const problem = (code, message, at) => ({ code, message, ...(at ? { at } : {}) });
69
+ const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
70
+ function parameterProblems(p, index, defaults) {
71
+ const name = typeof p.name === "string" ? p.name : `#${index + 1}`;
72
+ const source = p.source ?? defaults.source;
73
+ const type = typeof (p.type ?? defaults.type) === "string" ? String(p.type ?? defaults.type) : "string";
74
+ const required = p.required ?? defaults.required;
75
+ const at = `parameters/${index}`;
76
+ const said = (what) => `parameter '${name}': ${what}`;
77
+ const set = CONSTRAINTS.filter((key) => p[key] !== undefined && p[key] !== null);
78
+ if (typeof source === "string" && source !== defaults.source) {
79
+ if (type !== "string")
80
+ return [problem("parameter_context_not_string", said(`a context parameter (${source}) has type string`), `${at}/type`)];
81
+ if (required === false)
82
+ return [problem("parameter_context_optional", said(`a context parameter (${source}) is always required`), `${at}/required`)];
83
+ if (set.length)
84
+ return [problem("parameter_context_constrained", said(`the platform fills a context parameter, so ${set.join(", ")} does not apply`), `${at}/${set[0]}`)];
85
+ return [];
86
+ }
87
+ const problems = [];
88
+ if (typeof p.description !== "string" || !p.description.trim()) {
89
+ problems.push(problem("parameter_description_missing", said("the model needs a description of what to fill in"), at));
90
+ }
91
+ const misplaced = set.filter((key) => !(CONSTRAINTS_BY_TYPE[type] ?? []).includes(key));
92
+ if (misplaced.length) {
93
+ problems.push(problem("parameter_constraint_not_applicable", said(`${misplaced.join(", ")} does not apply to type ${type}`), `${at}/${misplaced[0]}`));
94
+ return problems;
95
+ }
96
+ if (isNumber(p.minimum) && isNumber(p.maximum) && p.minimum > p.maximum) {
97
+ problems.push(problem("parameter_bounds_inverted", said("minimum is greater than maximum"), `${at}/minimum`));
98
+ }
99
+ if (type === "integer" && [p.minimum, p.maximum].some((b) => isNumber(b) && !Number.isInteger(b))) {
100
+ problems.push(problem("parameter_bounds_not_integer", said("an integer's bounds must be integers"), at));
101
+ }
102
+ if (Array.isArray(p.enum)) {
103
+ const fits = (v) => type === "string"
104
+ ? typeof v === "string" && (!isNumber(p.max_length) || v.length <= p.max_length)
105
+ : type === "integer"
106
+ ? Number.isInteger(v)
107
+ : isNumber(v);
108
+ if (!p.enum.every(fits))
109
+ problems.push(problem("parameter_enum_invalid", said(`every enum value must be a ${type} within its limits`), `${at}/enum`));
110
+ else if (new Set(p.enum.map((v) => JSON.stringify(v))).size !== p.enum.length)
111
+ problems.push(problem("parameter_enum_repeats", said("enum values repeat"), `${at}/enum`));
112
+ }
113
+ return problems;
114
+ }
115
+ export function queryProblems(query, schema) {
116
+ const props = (parameterSchema(schema)?.properties ?? {});
117
+ const defaults = { source: props.source?.default ?? "model", type: props.type?.default ?? "string", required: props.required?.default ?? true };
118
+ const parameters = Array.isArray(query.parameters) ? query.parameters.filter(isObject) : [];
119
+ const problems = [];
120
+ const names = parameters.map((p) => p.name).filter((n) => typeof n === "string");
121
+ const repeated = [...new Set(names.filter((n, i) => names.indexOf(n) !== i))].sort((a, b) => a.localeCompare(b, "en"));
122
+ if (repeated.length)
123
+ problems.push(problem("parameter_names_repeat", `parameter names repeat: ${repeated.join(", ")}`, "parameters"));
124
+ parameters.forEach((p, index) => problems.push(...parameterProblems(p, index, defaults)));
125
+ if (typeof query.sql_text === "string" && query.sql_text.trim()) {
126
+ const found = bindNames(query.sql_text);
127
+ const missing = found.filter((n) => !names.includes(n)).sort((a, b) => a.localeCompare(b, "en"));
128
+ const unused = [...new Set(names)].filter((n) => !found.includes(n)).sort((a, b) => a.localeCompare(b, "en"));
129
+ if (missing.length || unused.length) {
130
+ const parts = [
131
+ ...(missing.length ? [`placeholders without a declared parameter: ${missing.map((n) => `:${n}`).join(", ")}`] : []),
132
+ ...(unused.length ? [`declared parameters the SQL never uses: ${unused.join(", ")}`] : []),
133
+ ];
134
+ problems.push(problem("bind_mismatch", `The SQL and its parameters disagree; ${parts.join("; ")}.`, "sql_text"));
135
+ }
136
+ }
137
+ const context = parameters.some((p) => typeof p.source === "string" && p.source !== defaults.source);
138
+ if (query.allows_anonymous === true && context) {
139
+ problems.push(problem("anonymous_with_context_parameter", "allows_anonymous is true, but a parameter is filled from the signed-in visitor's identity, so the query needs a visitor anyway.", "allows_anonymous"));
140
+ }
141
+ return problems;
142
+ }
143
+ function settledTool(schema, tool) {
144
+ const settled = settledForm(schema, schema.properties?.[TOOLS_SECTION], [tool]);
145
+ return Array.isArray(settled) && isObject(settled[0]) ? settled[0] : tool;
146
+ }
147
+ function baselineOf(schema, tool) {
148
+ const settled = settledTool(schema, tool);
149
+ const out = {};
150
+ for (const key of [...QUERY_FIELDS, ...DERIVED_FIELDS])
151
+ if (settled[key] !== undefined)
152
+ out[key] = settled[key];
153
+ return out;
154
+ }
155
+ export async function readQueryBaseline(root) {
156
+ const stored = await readJsonFile(path.join(stateDir(root), BASELINE_FILE));
157
+ return stored && isObject(stored.tools) ? stored : undefined;
158
+ }
159
+ export async function rememberQueries(root, pkg, schema, by, now) {
160
+ if (!schema || !schemaKnowsQueries(schema))
161
+ return;
162
+ const previous = by === "apply" ? (await readQueryBaseline(root))?.tools : undefined;
163
+ const tools = {};
164
+ for (const { slug, tool } of queryTools(pkg)) {
165
+ const kept = previous?.[slug];
166
+ tools[slug] = !isObject(tool[QUERY_FIELD]) && kept ? { ...baselineOf(schema, tool), ...pick(kept, QUERY_FIELDS) } : baselineOf(schema, tool);
167
+ }
168
+ const baseline = { written_at: now.toISOString(), by, tools };
169
+ await writeState(root, BASELINE_FILE, `${JSON.stringify(baseline, null, 2)}\n`);
170
+ }
171
+ function pick(tool, keys) {
172
+ const out = {};
173
+ for (const key of keys)
174
+ if (tool[key] !== undefined)
175
+ out[key] = tool[key];
176
+ return out;
177
+ }
178
+ const same = (a, b) => canonical(a ?? null) === canonical(b ?? null);
179
+ export function queryChanges(pkg, schema, baseline) {
180
+ const out = [];
181
+ for (const { slug, index, tool } of queryTools(pkg)) {
182
+ if (!isObject(tool[QUERY_FIELD]))
183
+ continue;
184
+ const before = baseline.tools[slug];
185
+ const now = baselineOf(schema, tool);
186
+ if (!before) {
187
+ out.push({ slug, index, created: true, fields: [...QUERY_FIELDS] });
188
+ continue;
189
+ }
190
+ const fields = QUERY_FIELDS.filter((key) => !same(before[key], now[key]));
191
+ if (fields.length)
192
+ out.push({ slug, index, created: false, fields });
193
+ }
194
+ return out;
195
+ }
196
+ export function checkQueryTools(disk, schema, baseline) {
197
+ if (!schemaKnowsQueries(schema))
198
+ return [];
199
+ const findings = [];
200
+ for (const { slug, index, tool } of queryTools(disk.package)) {
201
+ const query = tool[QUERY_FIELD];
202
+ if (!isObject(query))
203
+ continue;
204
+ for (const problem of queryProblems(query, schema)) {
205
+ findings.push({
206
+ code: problem.code,
207
+ severity: "error",
208
+ ...locate(disk, `/${TOOLS_SECTION}/${index}/${QUERY_FIELD}${problem.at ? `/${problem.at}` : ""}`),
209
+ message: `Query tool "${slug}": ${problem.message}`,
210
+ });
211
+ }
212
+ }
213
+ if (!baseline)
214
+ return findings;
215
+ for (const change of queryChanges(disk.package, schema, baseline)) {
216
+ const what = change.created
217
+ ? `is new since the last ${baseline.by}: creating a query`
218
+ : `changes its ${change.fields.map((f) => (f === QUERY_FIELD ? "query (database_query)" : f)).join(", ")} since the last ${baseline.by}: ` +
219
+ `${change.fields.some((f) => f !== QUERY_FIELD) ? "a query tool's own name and description belong to the query, and changing one" : "changing a query"}`;
220
+ findings.push({
221
+ code: QUERY_CHANGED_CODE,
222
+ severity: "warning",
223
+ ...locate(disk, `/${TOOLS_SECTION}/${change.index}`),
224
+ message: `Query tool "${change.slug}" ${what} needs a superadmin in the Admin, and the import preview of a personal access token ` +
225
+ `blocks it (${NEEDS_SUPERADMIN_CODE}). An agent's or skill's override of the tool's name, description or max_calls is no query change.`,
226
+ });
227
+ }
228
+ for (const { slug, index, tool } of queryTools(disk.package)) {
229
+ const before = baseline.tools[slug];
230
+ if (!before)
231
+ continue;
232
+ const now = baselineOf(schema, tool);
233
+ const edited = DERIVED_FIELDS.filter((key) => !same(before[key], now[key]));
234
+ if (!edited.length)
235
+ continue;
236
+ findings.push({
237
+ code: QUERY_FIELDS_IGNORED_CODE,
238
+ severity: "warning",
239
+ ...locate(disk, `/${TOOLS_SECTION}/${index}/${edited[0]}`),
240
+ message: `Query tool "${slug}" changes its ${edited.join(" and ")}; the instance derives ${edited.length === 1 ? "it" : "them"} from the query's parameters and ignores the package's.`,
241
+ });
242
+ }
243
+ return findings;
244
+ }
245
+ export function connectorOffer(caps) {
246
+ const features = isObject(caps?.features) ? caps.features : {};
247
+ const section = isObject(caps?.database_connector) ? caps.database_connector : {};
248
+ return {
249
+ ...(typeof features.database_connector_enabled === "boolean" ? { enabled: features.database_connector_enabled } : {}),
250
+ ...(Array.isArray(section.dialects) ? { dialects: section.dialects.filter((d) => typeof d === "string") } : {}),
251
+ ...(typeof section.may_write_queries === "boolean" ? { may_write_queries: section.may_write_queries } : {}),
252
+ ...(typeof section.setting === "string" ? { setting: section.setting } : {}),
253
+ ...(typeof section.queries_written_by === "string" ? { queries_written_by: section.queries_written_by } : {}),
254
+ };
255
+ }
256
+ const named = (slugs) => slugs.map((s) => `"${s}"`).join(", ");
257
+ export function applyQueryNotes(pkg, changes, offer) {
258
+ const tools = queryTools(pkg);
259
+ if (!tools.length)
260
+ return { warnings: [] };
261
+ const warnings = [];
262
+ const setting = offer.setting ?? "its setting";
263
+ if (offer.enabled === false) {
264
+ warnings.push(`The package holds database query tools (${named(tools.map((t) => t.slug))}), and this instance has the database connector switched off (${setting}): ` +
265
+ "the import may carry them, but no agent gets a database tool until its operator switches the connector on.");
266
+ }
267
+ else if (offer.enabled && offer.dialects) {
268
+ const unrun = tools.filter((t) => {
269
+ const dialect = isObject(t.tool[QUERY_FIELD]) && isObject(t.tool[QUERY_FIELD].connection) ? t.tool[QUERY_FIELD].connection.dialect : undefined;
270
+ return typeof dialect === "string" && !offer.dialects.includes(dialect);
271
+ });
272
+ if (unrun.length) {
273
+ warnings.push(`This instance runs ${offer.dialects.length ? `only ${offer.dialects.join(", ")} queries` : "no database queries"}; ${named(unrun.map((t) => t.slug))} ` +
274
+ `${unrun.length === 1 ? "names" : "name"} another dialect, so no agent can call ${unrun.length === 1 ? "it" : "them"} here.`);
275
+ }
276
+ }
277
+ const slugs = changes.map((c) => c.slug);
278
+ if (slugs.length && offer.may_write_queries === false) {
279
+ warnings.push(`This apply would ${changes.every((c) => c.created) ? "create" : "create or change"} the database quer${slugs.length === 1 ? "y" : "ies"} ${named(slugs)}, ` +
280
+ `which this credential may not do (may_write_queries is false): the preview blocks ${slugs.length === 1 ? "it" : "them"}, and one blocked query stops the whole import. ` +
281
+ (offer.queries_written_by ? `${offer.queries_written_by} ` : "") +
282
+ "To apply the rest first, leave each such query as the instance holds it (restore the tool's entry as the last pull wrote it, or remove its database_query block).");
283
+ }
284
+ return {
285
+ warnings,
286
+ data: {
287
+ tools: tools.map((t) => t.slug),
288
+ changed: changes.map((c) => ({ slug: c.slug, created: c.created, fields: c.fields })),
289
+ connector_enabled: offer.enabled ?? null,
290
+ dialects: offer.dialects ?? null,
291
+ may_write_queries: offer.may_write_queries ?? null,
292
+ },
293
+ };
294
+ }
295
+ export function queryBlockedHint(files) {
296
+ const where = files.length ? ` in ${files.join(", ")}` : "";
297
+ return ("A database query the import would create or change stops the whole import: nothing is applied while one blocks. " +
298
+ "A superadmin applies it in the Admin (the blocker's hint names where); after that, apply passes while the queries match. " +
299
+ `To apply the other changes first, leave each blocked query as the instance holds it${where}: restore the tool's entry as the last pull wrote it, ` +
300
+ "or remove its database_query block (the tool then keeps the instance's query, name and description), and apply again.");
301
+ }
package/dist/fsutil.js CHANGED
@@ -41,3 +41,17 @@ export async function writeFileAtomic(file, content, mode = 0o644, dirMode = 0o7
41
41
  await fs.chmod(tmp, existing & mode).catch(() => undefined);
42
42
  await fs.rename(tmp, file);
43
43
  }
44
+ export async function writePrivateFile(base, file, content) {
45
+ await writeFileAtomic(file, content, 0o600, 0o700);
46
+ const root = path.resolve(base);
47
+ for (let dir = path.dirname(path.resolve(file));; dir = path.dirname(dir)) {
48
+ const rel = path.relative(root, dir);
49
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
50
+ break;
51
+ const mode = await fs.stat(dir).then((st) => st.mode & 0o777, () => undefined);
52
+ if (mode !== undefined && mode & 0o077)
53
+ await fs.chmod(dir, mode & 0o700).catch(() => undefined);
54
+ if (rel === "")
55
+ break;
56
+ }
57
+ }