@cavelon/cli 0.1.9 → 0.1.11

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 (64) hide show
  1. package/README.md +23 -10
  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/branches.js +4 -3
  6. package/dist/capacity.js +3 -2
  7. package/dist/code-hints.js +5 -4
  8. package/dist/command.js +6 -0
  9. package/dist/commands/api.js +40 -21
  10. package/dist/commands/async.js +7 -4
  11. package/dist/commands/chat.js +18 -15
  12. package/dist/commands/db.js +367 -0
  13. package/dist/commands/docs.js +87 -9
  14. package/dist/commands/fmt.js +6 -4
  15. package/dist/commands/index.js +8 -0
  16. package/dist/commands/init.js +106 -28
  17. package/dist/commands/limits-set.js +12 -11
  18. package/dist/commands/limits.js +4 -3
  19. package/dist/commands/loops.js +75 -19
  20. package/dist/commands/models.js +12 -13
  21. package/dist/commands/sandboxes.js +22 -16
  22. package/dist/commands/schema.js +6 -5
  23. package/dist/commands/session.js +134 -37
  24. package/dist/commands/setup.js +4 -2
  25. package/dist/commands/solution.js +289 -93
  26. package/dist/commands/tenants.js +58 -22
  27. package/dist/commands/values.js +110 -45
  28. package/dist/commands/work.js +31 -17
  29. package/dist/confirm-token.js +15 -5
  30. package/dist/context.js +3 -1
  31. package/dist/contracts.js +39 -13
  32. package/dist/database-queries.js +301 -0
  33. package/dist/default-route.js +1 -1
  34. package/dist/features.js +2 -1
  35. package/dist/fsutil.js +14 -0
  36. package/dist/harness-ref.js +6 -4
  37. package/dist/http.js +39 -4
  38. package/dist/invoke.js +7 -2
  39. package/dist/kit-codes.js +14 -2
  40. package/dist/limits.js +1 -1
  41. package/dist/main.js +13 -1
  42. package/dist/mcp.js +105 -26
  43. package/dist/openapi.js +5 -2
  44. package/dist/operations.js +3 -2
  45. package/dist/package-check.js +29 -4
  46. package/dist/package-files.js +5 -1
  47. package/dist/package-format.js +10 -0
  48. package/dist/preview-report.js +46 -7
  49. package/dist/principal.js +24 -2
  50. package/dist/printed.js +182 -0
  51. package/dist/project.js +2 -1
  52. package/dist/results.js +1 -1
  53. package/dist/secret-access.js +42 -0
  54. package/dist/session.js +39 -19
  55. package/dist/shell.js +0 -3
  56. package/dist/skills/cavelon-authoring/SKILL.md +88 -4
  57. package/dist/skills/cavelon-long-running/SKILL.md +9 -3
  58. package/dist/skills/cavelon-loop/SKILL.md +81 -19
  59. package/dist/skills/cavelon-testing/SKILL.md +28 -1
  60. package/dist/tenant-choice.js +7 -7
  61. package/dist/trace-view.js +11 -1
  62. package/dist/update-check.js +2 -2
  63. package/dist/user-config.js +24 -0
  64. package/package.json +1 -1
@@ -0,0 +1,182 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { ownsTenant, propertyName } from "./command.js";
3
+ import { CavelonError } from "./errors.js";
4
+ import { shellWord } from "./shell.js";
5
+ export function fill(name) {
6
+ return { placeholder: name };
7
+ }
8
+ const current = new AsyncLocalStorage();
9
+ export function printingFor(target, run) {
10
+ return current.run(target, run);
11
+ }
12
+ export function printMode() {
13
+ return current.getStore()?.mode ?? "cli";
14
+ }
15
+ export function cavelonCommand(...words) {
16
+ return printedCommand(words);
17
+ }
18
+ export function folderCommand(...words) {
19
+ const target = current.getStore();
20
+ return target ? current.run({ mode: target.mode, commands: target.commands, agentShell: target.agentShell }, () => printedCommand(words)) : printedCommand(words);
21
+ }
22
+ export function printedCommand(words, override = {}) {
23
+ const target = current.getStore();
24
+ const spec = target ? commandOf(target.commands, words) : undefined;
25
+ if (target && spec) {
26
+ const env = override.env !== undefined ? override.env ?? undefined : target.env;
27
+ if (target.mode === "mcp") {
28
+ const call = toolCall(target, spec, words.slice(spec.name.split(" ").length), env);
29
+ if (call)
30
+ return call;
31
+ }
32
+ const line = withTarget(spec, words, { ...target, env });
33
+ return commandLine(target.agentShell ? withTokenPlaceholder(line) : line);
34
+ }
35
+ return commandLine(words);
36
+ }
37
+ function withTokenPlaceholder(words) {
38
+ const at = words.indexOf("--confirm");
39
+ if (at < 0)
40
+ return [...words];
41
+ const next = words[at + 1];
42
+ if (next !== undefined && (typeof next !== "string" || !next.startsWith("-")))
43
+ return [...words];
44
+ return [...words.slice(0, at + 1), fill(PREVIEW_TOKEN_NAME), ...words.slice(at + 1)];
45
+ }
46
+ function commandLine(words) {
47
+ return ["cavelon", ...words.map((w) => (typeof w === "string" ? shellWord(w) : `<${w.placeholder}>`))].join(" ");
48
+ }
49
+ function commandOf(commands, words) {
50
+ const lead = [];
51
+ for (const word of words.slice(0, 3)) {
52
+ if (typeof word !== "string" || word.startsWith("-"))
53
+ break;
54
+ lead.push(word);
55
+ }
56
+ for (let n = lead.length; n > 0; n--) {
57
+ const spec = commands.find((c) => c.name === lead.slice(0, n).join(" "));
58
+ if (spec)
59
+ return spec;
60
+ }
61
+ return undefined;
62
+ }
63
+ const has = (words, flag) => words.some((w) => w === flag || (typeof w === "string" && w.startsWith(`${flag}=`)));
64
+ function withTarget(spec, words, target) {
65
+ const added = [];
66
+ if (target.instance && !has(words, "--instance"))
67
+ added.push("--instance", target.instance);
68
+ if (target.env && spec.options?.env && !has(words, "--env"))
69
+ added.push("--env", target.env);
70
+ if (target.tenant && takesTenant(spec) && !has(words, "--tenant"))
71
+ added.push("--tenant", target.tenant);
72
+ const at = words.indexOf("--confirm");
73
+ return at < 0 ? [...words, ...added] : [...words.slice(0, at), ...added, ...words.slice(at)];
74
+ }
75
+ function takesTenant(spec) {
76
+ return !spec.tenantless && !ownsTenant(spec);
77
+ }
78
+ const PREVIEW_TOKEN_NAME = "confirm_token of its preview";
79
+ export const PREVIEW_TOKEN = `<${PREVIEW_TOKEN_NAME}>`;
80
+ function toolCall(target, spec, args, env) {
81
+ const tool = spec.mcpTool ? spec : spec.mcpInstead ? target.commands.find((c) => c.name === spec.mcpInstead) : undefined;
82
+ if (!tool?.mcpTool)
83
+ return undefined;
84
+ const out = {};
85
+ const positionals = [...(tool.positionals ?? [])];
86
+ const value = (w) => (w === undefined ? undefined : typeof w === "string" ? w : `<${w.placeholder}>`);
87
+ for (let i = 0; i < args.length; i++) {
88
+ const word = args[i];
89
+ if (typeof word === "string" && word.startsWith("--")) {
90
+ const eq = word.indexOf("=");
91
+ const name = eq < 0 ? word.slice(2) : word.slice(2, eq);
92
+ const inline = eq < 0 ? undefined : word.slice(eq + 1);
93
+ const take = () => inline ?? value(args[++i]);
94
+ if (name === "json")
95
+ continue;
96
+ if (name === "instance") {
97
+ take();
98
+ continue;
99
+ }
100
+ if (name === "tenant" && takesTenant(tool)) {
101
+ out.tenant = take();
102
+ continue;
103
+ }
104
+ const own = tool === spec ? undefined : spec.options?.[name];
105
+ const option = tool.options?.[name] ?? (own ? { ...own, cliOnly: true } : undefined);
106
+ if (!option)
107
+ return undefined;
108
+ if (option.type === "string") {
109
+ const v = take();
110
+ if (option.cliOnly)
111
+ continue;
112
+ if (option.multiple)
113
+ out[propertyName(name)] = [...(out[propertyName(name)] ?? []), v];
114
+ else
115
+ out[propertyName(name)] = v;
116
+ }
117
+ else if (option.mcpToken) {
118
+ const next = args[i + 1];
119
+ const token = inline ?? (next !== undefined && (typeof next !== "string" || !next.startsWith("-")) ? value(args[++i]) : undefined);
120
+ out[propertyName(name)] = token ?? PREVIEW_TOKEN;
121
+ }
122
+ else if (!option.cliOnly) {
123
+ out[propertyName(name)] = true;
124
+ }
125
+ continue;
126
+ }
127
+ const p = positionals[0];
128
+ if (!p)
129
+ return undefined;
130
+ const key = propertyName(p.name);
131
+ if (p.variadic)
132
+ out[key] = [...(out[key] ?? []), value(word)];
133
+ else {
134
+ out[key] = value(word);
135
+ positionals.shift();
136
+ }
137
+ }
138
+ if (target.tenant && takesTenant(tool) && out.tenant === undefined)
139
+ out.tenant = target.tenant;
140
+ if (env && tool.options?.env && out.env === undefined)
141
+ out.env = env;
142
+ return `${tool.mcpTool} ${JSON.stringify(out)}`;
143
+ }
144
+ const NAMED_COMMAND = /`cavelon ([^`]+)`/g;
145
+ const SPAN_WORD = /<[^>]*>|\S+/g;
146
+ export function spoken(text) {
147
+ if (!current.getStore() || !text.includes("`cavelon "))
148
+ return text;
149
+ return text.replace(NAMED_COMMAND, (whole, line) => {
150
+ const words = (line.match(SPAN_WORD) ?? []).map((w) => (w.startsWith("<") && w.endsWith(">") ? fill(w.slice(1, -1)) : w));
151
+ const printed = printedCommand(words);
152
+ if (printed === commandLine(words))
153
+ return whole;
154
+ return `\`${printed.endsWith(" {}") ? printed.slice(0, -" {}".length) : printed}\``;
155
+ });
156
+ }
157
+ const HINT_FIELDS = new Set(["hint", "next", "fix", "cli_fix", "kit_hint", "warnings"]);
158
+ export function spokenHints(value) {
159
+ if (!current.getStore())
160
+ return value;
161
+ const walk = (v, hint) => {
162
+ if (typeof v === "string")
163
+ return hint ? spoken(v) : v;
164
+ if (Array.isArray(v))
165
+ return v.map((item) => walk(item, hint));
166
+ if (v && typeof v === "object")
167
+ return Object.fromEntries(Object.entries(v).map(([key, item]) => [key, walk(item, HINT_FIELDS.has(key))]));
168
+ return v;
169
+ };
170
+ return walk(value, false);
171
+ }
172
+ export function spokenError(error) {
173
+ if (!(error instanceof CavelonError) || !current.getStore())
174
+ return error;
175
+ const hint = error.hint === undefined ? undefined : spoken(error.hint);
176
+ const details = spokenHints(error.details);
177
+ const blockerDetails = spokenHints(error.blockerDetails);
178
+ if (hint === error.hint && JSON.stringify(details) === JSON.stringify(error.details) && JSON.stringify(blockerDetails) === JSON.stringify(error.blockerDetails))
179
+ return error;
180
+ const { exitCode, code, message, docs, status, blockers } = error;
181
+ return new CavelonError(exitCode, { code, message, hint, docs, status, details, blockers, blockerDetails });
182
+ }
package/dist/project.js CHANGED
@@ -4,6 +4,7 @@ import { parse } from "yaml";
4
4
  import { readTextFile } from "./fsutil.js";
5
5
  import { CavelonError, ExitCode, usageError } from "./errors.js";
6
6
  import { layoutFrom } from "./package-files.js";
7
+ import { cavelonCommand } from "./printed.js";
7
8
  export const PROJECT_FILE = "cavelon.yaml";
8
9
  function stringField(value, ...keys) {
9
10
  if (typeof value === "string" && value.trim())
@@ -100,7 +101,7 @@ export async function readEnvFile(project, name) {
100
101
  const known = await envNames(project);
101
102
  throw usageError(`No ${ENV_DIR}/${name}.yaml in this solution; nothing was sent.`, known.length
102
103
  ? `Its env files: ${known.join(", ")}. Pass one of them to --env, or write ${ENV_DIR}/${name}.yaml first.`
103
- : "`cavelon init` writes env/test.yaml and env/prod.yaml.");
104
+ : `\`${cavelonCommand("init")}\` writes env/test.yaml and env/prod.yaml.`);
104
105
  }
105
106
  let raw;
106
107
  try {
package/dist/results.js CHANGED
@@ -2,7 +2,7 @@ import { CavelonError } from "./errors.js";
2
2
  import { clip } from "./format.js";
3
3
  import { failedAssertions } from "./trace-view.js";
4
4
  import { callStable } from "./invoke.js";
5
- import { cavelonCommand } from "./shell.js";
5
+ import { cavelonCommand } from "./printed.js";
6
6
  export function caseKnowledgeOutcomes(r) {
7
7
  if (!Array.isArray(r.tool_calls))
8
8
  return null;
@@ -0,0 +1,42 @@
1
+ import { CavelonError, ExitCode } from "./errors.js";
2
+ import { cavelonCommand, fill } from "./printed.js";
3
+ export const SECRETS_PERMISSIONS = ["settings.secrets.manage", "settings.manage"];
4
+ export const SECRET_SETTER = "A tenant Owner (or another role allowed to manage secrets) sets it, in the Admin under Settings › Secrets or with their own token";
5
+ export function maySetSecrets(principal) {
6
+ if (!principal)
7
+ return null;
8
+ if (principal.kind === "api_key")
9
+ return false;
10
+ if (!principal.permissions || principal.mode !== "tenant")
11
+ return null;
12
+ return SECRETS_PERMISSIONS.some((p) => principal.permissions.includes(p));
13
+ }
14
+ export { permissionsNamed } from "./access.js";
15
+ export const VARIABLE_SETTER = "A tenant Owner (or another role allowed to manage the tenant's settings) sets it, in the Admin under Settings › Variables or with their own token";
16
+ export function variableSetterHint(name, value) {
17
+ const shown = value !== undefined && value.length <= 120 && !value.includes("\n") ? value : fill("value");
18
+ return `${VARIABLE_SETTER}: \`${cavelonCommand("variables", "set", name, shown)}\`.`;
19
+ }
20
+ export function variablesPermissionMissing(verb, name, permissions, value) {
21
+ const needs = permissions.length ? permissions.join(" or ") : "a permission to manage the tenant's settings";
22
+ return new CavelonError(ExitCode.unauthorized, {
23
+ code: "permission_missing",
24
+ status: 403,
25
+ message: `This credential may not ${verb} tenant variables: the instance refused it, as that needs ${needs}. Variable ${name} is unchanged.`,
26
+ hint: variableSetterHint(name, value),
27
+ details: { name, permissions, sent: true },
28
+ });
29
+ }
30
+ export function secretSetterHint(name) {
31
+ return `${SECRET_SETTER}: \`${cavelonCommand("secrets", "set", name)}\`.`;
32
+ }
33
+ export function secretsPermissionMissing(verb, name, permissions) {
34
+ const needs = permissions.length ? permissions.join(" or ") : "a permission to manage secrets";
35
+ return new CavelonError(ExitCode.unauthorized, {
36
+ code: "permission_missing",
37
+ status: 403,
38
+ message: `This token's role may not ${verb} secrets: the instance refused it, as that needs ${needs}. Secret ${name} is unchanged.`,
39
+ hint: secretSetterHint(name),
40
+ details: { name, permissions, sent: true },
41
+ });
42
+ }
package/dist/session.js CHANGED
@@ -5,20 +5,12 @@ import { exactMatch } from "./choose.js";
5
5
  import { readTenantless } from "./principal.js";
6
6
  import { listsTenants, searchTenants, tenantMissError } from "./tenant-choice.js";
7
7
  import { findProject, readEnvFile } from "./project.js";
8
- import { loadUserConfig, tokenKind, updateInstance } from "./user-config.js";
9
- import { shellWord } from "./shell.js";
8
+ import { cachedTenantRef, loadUserConfig, tokenKind, updateInstance, withoutTenantRef, withTenantRefs, } from "./user-config.js";
9
+ import { cavelonCommand, fill } from "./printed.js";
10
10
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
11
  export function isUuid(value) {
12
12
  return UUID.test(value);
13
13
  }
14
- export function contextFlags(session) {
15
- let flags = "";
16
- if (session.urlSource === "option" && session.url)
17
- flags += ` --instance ${shellWord(session.url)}`;
18
- if (session.tenantSource === "option" && session.tenant)
19
- flags += ` --tenant ${shellWord(session.tenant)}`;
20
- return flags;
21
- }
22
14
  function isLocalHost(hostname) {
23
15
  return (hostname === "localhost" ||
24
16
  hostname.endsWith(".localhost") ||
@@ -62,7 +54,7 @@ export async function resolveSession(env, cwd, globals) {
62
54
  let envFile;
63
55
  if (globals.solutionEnv) {
64
56
  if (!project) {
65
- throw usageError(`--env ${globals.solutionEnv} needs a solution folder.`, "Run it inside a folder with cavelon.yaml, or run `cavelon init` first.");
57
+ throw usageError(`--env ${globals.solutionEnv} needs a solution folder.`, `Run it inside a folder with cavelon.yaml, or run \`${cavelonCommand("init")}\` first.`);
66
58
  }
67
59
  envFile = await readEnvFile(project, globals.solutionEnv);
68
60
  }
@@ -105,6 +97,10 @@ export async function resolveSession(env, cwd, globals) {
105
97
  [session.tenant, session.tenantSource] = [envFile.tenant, `env/${envFile.name}.yaml`];
106
98
  else if (projectMatches && project?.tenant)
107
99
  [session.tenant, session.tenantSource] = [project.tenant, "cavelon.yaml"];
100
+ else if (globals.sessionTenants?.get(url)) {
101
+ session.sessionTenant = globals.sessionTenants.get(url);
102
+ [session.tenant, session.tenantSource] = [session.sessionTenant.ref, "session"];
103
+ }
108
104
  else if (settings.tenant)
109
105
  [session.tenant, session.tenantSource] = [settings.tenant, "use"];
110
106
  return session;
@@ -114,7 +110,7 @@ export function requireInstance(session) {
114
110
  throw new CavelonError(ExitCode.usage, {
115
111
  code: "no_instance",
116
112
  message: "No Cavelon instance selected.",
117
- hint: "Run `cavelon login --instance <url>`, set CAVELON_URL, or work inside a folder with cavelon.yaml.",
113
+ hint: `Run \`${cavelonCommand("login", "--instance", fill("url"))}\`, set CAVELON_URL, or work inside a folder with cavelon.yaml.`,
118
114
  });
119
115
  }
120
116
  return session.url;
@@ -233,23 +229,47 @@ async function findTenant(client, ref) {
233
229
  }
234
230
  return { known: memberships };
235
231
  }
236
- export async function resolveTenantId(env, session, client) {
232
+ export function knownTenantId(session, now = new Date()) {
237
233
  if (!session.tenant || !session.url)
238
234
  return undefined;
239
235
  if (session.tokenKind === "api_key")
240
236
  return undefined;
241
237
  if (isUuid(session.tenant))
242
238
  return session.tenant;
243
- const cached = session.settings.tenant_ids?.[session.tenant];
244
- if (cached)
245
- return cached;
239
+ if (session.tenantSource === "session" && session.sessionTenant)
240
+ return session.sessionTenant.id;
246
241
  if (session.tenantSource === "use" && session.settings.tenant_id)
247
242
  return session.settings.tenant_id;
248
- const found = await lookupTenantId(client, session.tenant, session.tenantSource);
243
+ return cachedTenantRef(session.settings, session.tenant, session.token, now);
244
+ }
245
+ export async function resolveTenantId(env, session, client, now = new Date()) {
246
+ if (!session.tenant || !session.url)
247
+ return undefined;
248
+ if (session.tokenKind === "api_key")
249
+ return undefined;
250
+ const known = knownTenantId(session, now);
249
251
  const url = session.url;
250
252
  const slug = session.tenant;
251
- await updateInstance(env, url, (current) => ({ ...current, tenant_ids: { ...current.tenant_ids, [slug]: found.id } }));
252
- return found.id;
253
+ const fromCache = known !== undefined && !isUuid(slug) && session.tenantSource !== "use" && session.tenantSource !== "session";
254
+ const resolve = async () => {
255
+ const found = await lookupTenantId(client, slug, session.tenantSource);
256
+ if (client.target.token) {
257
+ const token = client.target.token;
258
+ await updateInstance(env, url, (current) => withTenantRefs(current, [slug], found.id, token, now));
259
+ }
260
+ return found.id;
261
+ };
262
+ if (!fromCache)
263
+ return known ?? resolve();
264
+ client.revalidateTenant = async () => {
265
+ await updateInstance(env, url, (current) => withoutTenantRef(current, slug));
266
+ const fresh = await resolve().catch(() => undefined);
267
+ if (!fresh || fresh === client.target.tenantId)
268
+ return false;
269
+ client.target.tenantId = fresh;
270
+ return true;
271
+ };
272
+ return known;
253
273
  }
254
274
  export async function reloadSettings(env, url) {
255
275
  return (await loadUserConfig(env)).instances[url] ?? {};
package/dist/shell.js CHANGED
@@ -36,6 +36,3 @@ export function shellWord(word, shell = current) {
36
36
  return `"${word.replaceAll('"', '""')}"`;
37
37
  }
38
38
  }
39
- export function cavelonCommand(...words) {
40
- return ["cavelon", ...words.map((w) => shellWord(w))].join(" ");
41
- }
@@ -70,7 +70,8 @@ for a public widget), **propose the change; the person decides.**
70
70
  otherwise refuses naming the role and the Admin page; `--tenant <tenant>`
71
71
  then sets one tenant's own run cap. Without a `change` it cannot be changed
72
72
  at runtime. Tell the person who changes it and where, and design within it
73
- meanwhile; never ask for an operator's token.
73
+ meanwhile; never ask for an operator's token. A docs page marked "Platform
74
+ page" describes such an operator's task: this token can read it, not do it.
74
75
  - A rate limit only goes down to what the operator allows; above the ceiling
75
76
  (`maximum_setting`), it is the operator's too. That holds for the per-visitor
76
77
  limits (`rate_limit_chat_visitor_rpm`, `rate_limit_widget_visitor_rpm`) as
@@ -138,7 +139,9 @@ it and where, as the output says.
138
139
 
139
140
  A file of a section the instance does not know is kept as it is; the preview
140
141
  lists it under "ignored". `package/manifest.yaml` names the package format
141
- version; leave it as `pull` wrote it. Some fields are not applied by an
142
+ version and the tenant the package is for; leave it as `pull` or `init`
143
+ wrote it (`init` writes a minimal one for a new solution, and the first `pull`
144
+ replaces it). Some fields are not applied by an
142
145
  import: the preview lists them under "not applied", each with the command
143
146
  that sets it (a solution's `status` with `cavelon activate`, its `is_default`
144
147
  with `cavelon harness default`).
@@ -293,14 +296,95 @@ schema has them: `cavelon validate` reports an unknown section):
293
296
  - **Variables** are plain text that anyone who may view the tenant's settings
294
297
  reads. You may set one with `cavelon variables set <name> <value>` (the
295
298
  `variables_set` tool) when the value is not a credential and you know it;
296
- ask the person otherwise. `cavelon variables list` shows them.
299
+ ask the person otherwise. Setting one needs the permission a secret needs: a
300
+ Builder's role may not (`cavelon whoami` says "may set variables: no", and
301
+ `apply` says so under "needs variables"); then tell the person that a tenant
302
+ Owner sets it, in the Admin under Settings › Variables or with their own
303
+ token. `cavelon variables list` shows them. A variable
304
+ is tenant-wide: replacing a value previews the old and the new one and
305
+ changes nothing without `--confirm` (the `confirm_token` over MCP); every
306
+ solution of the tenant reads it, active ones too, so show the person that
307
+ preview and confirm only with their yes. A new variable is set at once.
297
308
  - **Secrets are set by a person, never by you.** Tell the person the exact
298
309
  command `apply` printed, `cavelon secrets set <name>` (with the `--env` and
299
310
  `--tenant` it printed), to run in their own terminal; it asks for the value
300
311
  without echoing it. Never ask for the value, never put it into a file,
301
312
  an argument or a message, and never put a credential into a variable.
302
313
  `cavelon secrets list` (the `secrets_list` tool) shows which are set,
303
- never a value. A tenant API key cannot set a secret at all.
314
+ never a value. A tenant API key cannot set a secret at all, and neither can
315
+ a person whose role may not manage secrets (a Builder): `cavelon whoami`
316
+ says "may set secrets: no", and `secrets set`, `activate` and `status` then
317
+ name who does instead. Tell the person that a tenant Owner sets it, in the
318
+ Admin under Settings › Secrets or with their own token; do not suggest the
319
+ command to someone whose role cannot run it.
320
+
321
+ ## Database query tools
322
+
323
+ A database query tool lets an agent answer from a customer's live database. A
324
+ saved, read-only query is one tool (`tool_type: database_query` in
325
+ `package/tools.yaml`); the model only calls it and fills the parameters it is
326
+ given, and never writes SQL. `cavelon schema tools.database_query` lists the
327
+ fields this instance takes; `cavelon docs get administration/database-connectors`
328
+ says who does what on the instance.
329
+
330
+ ```yaml
331
+ - slug: order_status # the function name the model calls: a-z, 0-9, - and _
332
+ name: Order status # the label in the Admin
333
+ description: Status and shipping date of one of the signed-in visitor's orders, by order number.
334
+ tool_type: database_query
335
+ scope: tenant_local
336
+ database_query:
337
+ connection: { name: shop-db, dialect: postgresql } # by name only: never a host, user or password
338
+ sql_text: SELECT number, status, shipped_at FROM orders WHERE number = :order_no AND email = :email LIMIT 5
339
+ parameters:
340
+ - name: order_no
341
+ type: string
342
+ description: Order number as printed on the confirmation, e.g. A-10023
343
+ pattern: "^[A-Z]-[0-9]{4,8}$"
344
+ max_length: 20
345
+ - name: email
346
+ source: end_user.email # filled by the instance from the signed-in visitor
347
+ type: string
348
+ max_rows: 5
349
+ allows_anonymous: false
350
+ ```
351
+
352
+ - **Who writes a query.** Only a superadmin of the instance creates or changes
353
+ a query, in the Admin; your token never does. The query's SQL, parameters,
354
+ limits and `allows_anonymous`, and the tool's own `slug`, `name` and
355
+ `description`, are all part of the query. `cavelon validate` warns
356
+ (`database_query_changed`) for each query tool that differs from the last
357
+ pull or apply, and the import preview blocks it
358
+ (`database_query_needs_superadmin`), which stops the whole apply. Propose a
359
+ query change to the person as a diff of `package/tools.yaml`; they hand it
360
+ to a superadmin, who imports the package in the Admin. What you may change
361
+ freely is how agents and skills use the tool: the assignment
362
+ (`tool_assignments` with `config_overrides` `name`, `description` or
363
+ `max_calls`) is no query change. `params_json_schema` and `default_config`
364
+ of a query tool are derived from the query, and the instance ignores the
365
+ package's (`database_query_fields_ignored`).
366
+ - **Identity parameters.** A parameter with `source: end_user.id`,
367
+ `end_user.external_subject` or `end_user.email` is filled by the instance
368
+ from the signed-in visitor's verified identity (an email only once
369
+ verified), never by the model: it is a required string without
370
+ constraints. Scope every query that returns a person's data by such a
371
+ parameter, so a visitor only reads their own rows. Without a signed-in
372
+ visitor the call answers `identity_required` and the query does not run.
373
+ - **`allows_anonymous`.** Set it to true only for public data (stock, prices,
374
+ opening hours) and only on a query without an identity parameter; the
375
+ instance refuses it otherwise (`anonymous_with_context_parameter`).
376
+ - **Safe query design.** One `SELECT` or `WITH` statement; select only the
377
+ columns the answer needs (never `SELECT *`); always bound the rows (`LIMIT`,
378
+ `TOP`, `FETCH FIRST`) and keep `max_rows` small; constrain every model
379
+ parameter (`pattern`, `max_length`, `enum`, `minimum`/`maximum`) and
380
+ describe it, since the model fills it from the conversation; where a lookup
381
+ has no identity parameter, ask for a second factor (an order number and its
382
+ postal code) rather than one guessable key. Each `:name` in the SQL needs
383
+ exactly one parameter of that name (a literal colon is `\:`); validate checks
384
+ this (`bind_mismatch`) and each parameter's type and constraints.
385
+ - `cavelon explain <code>` explains every code the connector uses: what
386
+ `validate` and the preview name, the codes of a failed call (`timeout`,
387
+ `identity_required`, …) and of a connection test.
304
388
 
305
389
  ## After each edit
306
390
 
@@ -57,14 +57,20 @@ Do not work around it; use the other column.
57
57
  ## Run and follow
58
58
 
59
59
  ```bash
60
- cavelon loop start <trigger> --input @request.json # prints the run id and an operation id
60
+ cavelon loop start <trigger> --input @request.json # previews: the trigger, its solution, the payload
61
+ cavelon loop start <trigger> --input @request.json --confirm <token> # starts it: the run id and an operation id
61
62
  cavelon loop watch <run> --timeout 5m # each iteration's verdict, then the loop's outcome
62
63
  cavelon loop iterations <run> # state, budget, iterations (a page at a time)
63
64
  cavelon wait <operation-id> --timeout 90s # exit 0 done, 1 failed, 5 needs a person, 6 still running
64
65
  ```
65
66
 
66
67
  A loop started from `cavelon` runs **as the person whose token it is**, checked
67
- again on every iteration. If `loop start` exits 8 (a timeout, a cut
68
+ again on every iteration, and spends the tenant's budget. So `loop start`
69
+ previews first and starts nothing without `--confirm`: run the confirm command
70
+ it prints (from your shell it carries the preview's token; over MCP call
71
+ `loop_start` again with `confirm` set to its `confirm_token`). Confirm on your
72
+ own only for a trigger of a draft solution in a test environment; show the
73
+ person the preview of any other. If `loop start` exits 8 (a timeout, a cut
68
74
  connection), the run may have started: retry only with the
69
75
  `--idempotency-key <key>` its error names, never without it, or a second run
70
76
  starts and spends the budget again. `cavelon trace <operation-id>` reads the
@@ -72,7 +78,7 @@ run's traces. Keep each `watch` or `wait` under your shell's time
72
78
  limit and run it again to resume (exit 6 means still running). Over MCP, use the
73
79
  `loop_iterations` and `operation_status` tools; `loop_iterations` never
74
80
  blocks, and `operation_status` waits only when given a `timeout` (at most 50
75
- seconds).
81
+ seconds); its `resume` is the `operation_status` call to make again.
76
82
 
77
83
  - **Pause** at the next safe point: `cavelon loop pause <run>`. Resume with
78
84
  `cavelon loop resume <run>`. A paused loop makes `wait` and `loop watch` exit