@cavelon/cli 0.0.0 → 0.1.1

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 (61) hide show
  1. package/README.md +697 -3
  2. package/dist/LICENSE +201 -0
  3. package/dist/agents.js +91 -0
  4. package/dist/branches.js +61 -0
  5. package/dist/capacity.js +162 -0
  6. package/dist/cli.js +4 -0
  7. package/dist/command.js +62 -0
  8. package/dist/commands/api.js +243 -0
  9. package/dist/commands/async.js +207 -0
  10. package/dist/commands/docs.js +158 -0
  11. package/dist/commands/index.js +112 -0
  12. package/dist/commands/init.js +452 -0
  13. package/dist/commands/inventory.js +56 -0
  14. package/dist/commands/limits-set.js +624 -0
  15. package/dist/commands/limits.js +156 -0
  16. package/dist/commands/loops.js +792 -0
  17. package/dist/commands/models.js +197 -0
  18. package/dist/commands/sandboxes.js +667 -0
  19. package/dist/commands/session.js +476 -0
  20. package/dist/commands/solution.js +760 -0
  21. package/dist/commands/tenants.js +266 -0
  22. package/dist/commands/values.js +383 -0
  23. package/dist/commands/work.js +744 -0
  24. package/dist/context.js +56 -0
  25. package/dist/contracts.js +189 -0
  26. package/dist/credentials.js +134 -0
  27. package/dist/errors.js +64 -0
  28. package/dist/features.js +37 -0
  29. package/dist/format.js +36 -0
  30. package/dist/fsutil.js +40 -0
  31. package/dist/git.js +41 -0
  32. package/dist/http.js +286 -0
  33. package/dist/invoke.js +161 -0
  34. package/dist/io.js +49 -0
  35. package/dist/limits.js +299 -0
  36. package/dist/local-state.js +60 -0
  37. package/dist/main.js +227 -0
  38. package/dist/markers.js +113 -0
  39. package/dist/mcp.js +130 -0
  40. package/dist/openapi.js +223 -0
  41. package/dist/operations.js +107 -0
  42. package/dist/package-check.js +342 -0
  43. package/dist/package-files.js +329 -0
  44. package/dist/pair-order.js +39 -0
  45. package/dist/paths.js +28 -0
  46. package/dist/principal.js +33 -0
  47. package/dist/project.js +138 -0
  48. package/dist/prompt.js +34 -0
  49. package/dist/results.js +66 -0
  50. package/dist/session.js +166 -0
  51. package/dist/shell.js +41 -0
  52. package/dist/skills/cavelon-authoring/SKILL.md +214 -0
  53. package/dist/skills/cavelon-long-running/SKILL.md +181 -0
  54. package/dist/skills/cavelon-loop/SKILL.md +158 -0
  55. package/dist/skills/cavelon-testing/SKILL.md +90 -0
  56. package/dist/sse.js +44 -0
  57. package/dist/tar.js +172 -0
  58. package/dist/user-config.js +36 -0
  59. package/dist/version.js +17 -0
  60. package/dist/zip.js +132 -0
  61. package/package.json +40 -4
@@ -0,0 +1,760 @@
1
+ import path from "node:path";
2
+ import { parseDocument } from "yaml";
3
+ import { CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE, capacityCodeIn, capacityHint, MODEL_ENDPOINT_BUSY } from "../capacity.js";
4
+ import { boolOption, intOption, positional, stringOption } from "../command.js";
5
+ import { Contracts } from "../contracts.js";
6
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
7
+ import { clip, keyValues } from "../format.js";
8
+ import { readTextFile, writeFileAtomic } from "../fsutil.js";
9
+ import { uncommitted } from "../git.js";
10
+ import { callStable } from "../invoke.js";
11
+ import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
12
+ import { deletePreview, digest, listPreviews, loadPreview, savePreview, writeState, } from "../local-state.js";
13
+ import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
14
+ import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
15
+ import { readPackage, writePackage } from "../package-files.js";
16
+ import { readPrincipal } from "../principal.js";
17
+ import { isUuid, requireInstance } from "../session.js";
18
+ import { listedPages } from "./docs.js";
19
+ import { writeInventory } from "./inventory.js";
20
+ import { cavelonCommand, shellWord } from "../shell.js";
21
+ import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
22
+ const HARNESS_OPTION = { type: "string", value: "<slug>", description: "The solution (harness); default: env file, then cavelon.yaml." };
23
+ const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant, solution and runtime bindings." };
24
+ export function requireSolution(session) {
25
+ if (!session.project) {
26
+ throw new CavelonError(ExitCode.usage, {
27
+ code: "no_solution",
28
+ message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).",
29
+ hint: "Run `cavelon init` for a new solution, then `cavelon pull --harness <slug>` for an existing one.",
30
+ });
31
+ }
32
+ return session.project;
33
+ }
34
+ function harnessRef(session, input) {
35
+ const option = stringOption(input, "harness");
36
+ if (option)
37
+ return { ref: option, source: "option" };
38
+ if (session.envFile?.harness)
39
+ return { ref: session.envFile.harness, source: `env/${session.envFile.name}.yaml` };
40
+ if (session.project?.harness)
41
+ return { ref: session.project.harness, source: "cavelon.yaml" };
42
+ return {};
43
+ }
44
+ async function findHarness(ctx, ref) {
45
+ if (isUuid(ref)) {
46
+ try {
47
+ return await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}", "reading solutions", { params: { harness_id: [ref] } });
48
+ }
49
+ catch (error) {
50
+ if (error instanceof CavelonError && error.status === 404)
51
+ return undefined;
52
+ throw error;
53
+ }
54
+ }
55
+ try {
56
+ return await callStable(ctx, "GET", "/api/v1/harnesses/by-slug/{slug}", "finding solutions by slug", { params: { slug: [ref] } });
57
+ }
58
+ catch (error) {
59
+ if (error instanceof CavelonError && error.status === 404)
60
+ return undefined;
61
+ throw error;
62
+ }
63
+ }
64
+ function harnessNotFound(ref, source) {
65
+ return new CavelonError(ExitCode.failure, {
66
+ code: "solution_not_found",
67
+ message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.`,
68
+ hint: "`cavelon harness list` shows them; `cavelon harness new <slug>` creates one, and an env file's harness is created by `apply`.",
69
+ });
70
+ }
71
+ export async function schemaFor(ctx, version, offline) {
72
+ const contracts = await ctx.contracts();
73
+ const wanted = version ?? (await contracts.cachedOnly("capabilities.json"))?.value?.contracts?.package_versions?.current;
74
+ if (wanted) {
75
+ const cached = await contracts.cachedOnly(Contracts.packageSchemaFile(wanted));
76
+ if (cached)
77
+ return { schema: cached.value, source: "cache" };
78
+ }
79
+ if (offline)
80
+ return { schema: null, source: "none" };
81
+ return { schema: await contracts.packageSchema(wanted), source: "instance" };
82
+ }
83
+ export async function catalogFor(ctx, offline) {
84
+ const contracts = await ctx.contracts();
85
+ const cached = await contracts.cachedOnly("error-catalog.json");
86
+ if (cached || offline)
87
+ return cached?.value ?? null;
88
+ return contracts.errorCatalog().catch(() => null);
89
+ }
90
+ async function limitsFor(ctx, offline) {
91
+ const contracts = await ctx.contracts();
92
+ const cached = await contracts.cachedOnly("capabilities.json");
93
+ if (cached || offline)
94
+ return cached ? parseLimits(cached.value) : undefined;
95
+ const live = await contracts.capabilities().catch(() => null);
96
+ return live ? parseLimits(live) : undefined;
97
+ }
98
+ async function acceptedVersions(ctx) {
99
+ const contracts = await ctx.contracts();
100
+ const cached = await contracts.cachedOnly("capabilities.json");
101
+ return cached?.value?.contracts?.package_versions?.accepted;
102
+ }
103
+ function findingLine(f) {
104
+ const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
105
+ const at = f.path ? ` ${f.path}` : "";
106
+ return `${f.severity === "error" ? "error" : "warning"} ${f.code} ${where}${at}: ${f.message}`;
107
+ }
108
+ export async function setProjectKey(project, key, value) {
109
+ const text = (await readTextFile(project.file)) ?? "";
110
+ const doc = parseDocument(text);
111
+ if (doc.get(key) === value)
112
+ return;
113
+ doc.set(key, value);
114
+ await writeFileAtomic(project.file, doc.toString({ lineWidth: 0 }));
115
+ }
116
+ export const pull = {
117
+ name: "pull",
118
+ summary: "Write the instance's package into package/ (split along the schema's sections) and the inventory into .cavelon/.",
119
+ description: "With a solution (--harness, or cavelon.yaml's harness), exports that solution; without one, the tenant's full configuration.\n" +
120
+ "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance. Files of sections\n" +
121
+ "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force.",
122
+ readOnly: false,
123
+ destructive: true,
124
+ idempotent: true,
125
+ mcpTool: "pull",
126
+ options: {
127
+ harness: { type: "string", value: "<slug>", description: "The solution to export; recorded in cavelon.yaml when it names none." },
128
+ force: { type: "boolean", description: "Overwrite package files that have uncommitted changes." },
129
+ },
130
+ examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
131
+ async run(ctx, input) {
132
+ const session = await ctx.session();
133
+ const project = requireSolution(session);
134
+ const url = requireInstance(session);
135
+ const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
136
+ if (!boolOption(input, "force")) {
137
+ const dirty = (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)"?$/i.test(f));
138
+ if (dirty?.length) {
139
+ throw new CavelonError(ExitCode.conflict, {
140
+ code: "uncommitted_changes",
141
+ message: `pull would overwrite uncommitted changes: ${dirty.slice(0, 5).join(", ")}${dirty.length > 5 ? ` and ${dirty.length - 5} more` : ""}.`,
142
+ hint: "Commit them first (then resolve the difference in git), or pass --force to discard them.",
143
+ details: { files: dirty },
144
+ });
145
+ }
146
+ }
147
+ const { ref } = harnessRef(session, input);
148
+ let harness;
149
+ if (ref) {
150
+ harness = await findHarness(ctx, ref);
151
+ if (!harness)
152
+ throw harnessNotFound(ref);
153
+ }
154
+ const scope = harness ? "agent_graph" : "full_config";
155
+ const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
156
+ query: { scope, harness_id: harness?.id },
157
+ timeoutMs: 120_000,
158
+ });
159
+ if (!exported || typeof exported !== "object" || Array.isArray(exported)) {
160
+ throw new CavelonError(ExitCode.server, { code: "export_invalid", message: "The instance's export is not a package." });
161
+ }
162
+ const version = packageVersionOf(exported);
163
+ const { schema } = await schemaFor(ctx, version, false);
164
+ if (!schema)
165
+ ctx.warn("The instance does not publish its package schema; every top-level key became a file of its own.");
166
+ const report = await writePackage(project.root, project.layout, exported, schema);
167
+ if (harness && !project.harness)
168
+ await setProjectKey(project, "harness", harness.slug);
169
+ if (version && project.packageVersion !== version)
170
+ await setProjectKey(project, "package_version", version);
171
+ const client = await ctx.client();
172
+ const inventory = await writeInventory(ctx, project.root, ctx.io.now());
173
+ const record = {
174
+ at: ctx.io.now().toISOString(),
175
+ instance: url,
176
+ tenant_id: client.target.tenantId ?? null,
177
+ harness: harness ? { id: harness.id, slug: harness.slug } : null,
178
+ scope,
179
+ package_version: version ?? null,
180
+ files: report,
181
+ };
182
+ await writeState(project.root, "pull.json", JSON.stringify(record, null, 2));
183
+ for (const file of report.kept)
184
+ ctx.warn(`Kept ${file}: its section is not in this instance's package schema.`);
185
+ for (const section of report.refused)
186
+ ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
187
+ const changed = report.written.length + report.removed.length;
188
+ const lines = [
189
+ `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
190
+ (Object.keys(project.layout.items).length ? ` and ${Object.values(project.layout.items).join("/, ")}/` : "") +
191
+ ` (format ${version ?? "unknown"}).`,
192
+ ...report.written.map((f) => `written ${f}`),
193
+ ...report.removed.map((f) => `removed ${f}`),
194
+ `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
195
+ `Inventory: ${inventory.file} (${inventory.counts.map((c) => `${c.count} ${c.label}`).join(", ")})`,
196
+ changed ? `See what changed: git diff -- ${layoutDirs.join(" ")}` : "Nothing changed on the instance since the last pull.",
197
+ ];
198
+ return { data: { ...record, inventory }, text: lines.join("\n") };
199
+ },
200
+ };
201
+ async function validatePackage(ctx, project, offline) {
202
+ const disk = await readPackage(project.root, project.layout);
203
+ const version = packageVersionOf(disk.package) ?? project.packageVersion;
204
+ const { schema } = await schemaFor(ctx, version, offline);
205
+ if (!schema) {
206
+ throw new CavelonError(ExitCode.failure, {
207
+ code: "package_schema_unavailable",
208
+ message: `No package schema${version ? ` for format ${version}` : ""} is cached for ${requireInstance(await ctx.session())}.`,
209
+ hint: offline
210
+ ? "Run `cavelon validate` once without --offline (or `cavelon pull`) while the instance is reachable."
211
+ : "The instance does not publish its package schema (/api/v1/meta/package-schema).",
212
+ });
213
+ }
214
+ const findings = checkPackage(disk, {
215
+ schema,
216
+ catalog: await catalogFor(ctx, offline),
217
+ accepted: await acceptedVersions(ctx),
218
+ limits: await limitsFor(ctx, offline),
219
+ });
220
+ return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null };
221
+ }
222
+ export const validate = {
223
+ name: "validate",
224
+ summary: "Check the package files against the instance's package schema, offline.",
225
+ description: "Uses the schema and error catalog cached by init, pull or apply; fetches them only when none is cached (never with --offline).\n" +
226
+ "Warns (never fails) when a fan-out or Map loop's max_concurrency is above the instance's branch width, and when the\n" +
227
+ "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published.\n" +
228
+ "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.",
229
+ readOnly: true,
230
+ idempotent: true,
231
+ mcpTool: "validate",
232
+ options: {
233
+ offline: { type: "boolean", description: "Never contact the instance, even when nothing is cached." },
234
+ limit: { type: "string", value: "<n>", description: "Print at most n findings (default 50)." },
235
+ },
236
+ async run(ctx, input) {
237
+ const session = await ctx.session();
238
+ const project = requireSolution(session);
239
+ requireInstance(session);
240
+ const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
241
+ const { disk, findings, schemaVersion } = await validatePackage(ctx, project, boolOption(input, "offline"));
242
+ const errors = findings.filter((f) => f.severity === "error");
243
+ const warnings = findings.filter((f) => f.severity === "warning");
244
+ if (disk.empty)
245
+ ctx.warn(`No package files in ${project.layout.package}/ yet; \`cavelon pull\` brings an existing solution.`);
246
+ const shown = findings.slice(0, limit);
247
+ const data = {
248
+ valid: errors.length === 0,
249
+ schema_version: schemaVersion,
250
+ sections: Object.keys(disk.package).length,
251
+ errors: errors.length,
252
+ warnings: warnings.length,
253
+ findings: shown,
254
+ more: Math.max(0, findings.length - shown.length),
255
+ };
256
+ const text = [
257
+ ...shown.map(findingLine),
258
+ ...(data.more ? [`… and ${data.more} more (--limit).`] : []),
259
+ errors.length
260
+ ? `${errors.length} error${errors.length === 1 ? "" : "s"}, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}. \`cavelon explain <code>\` says more.`
261
+ : `Valid against package schema ${schemaVersion ?? "?"} (${data.sections} sections${warnings.length ? `, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}` : ""}).`,
262
+ ].join("\n");
263
+ return { data, text, exitCode: errors.length ? ExitCode.validation : ExitCode.ok };
264
+ },
265
+ };
266
+ function valueNeeds(list) {
267
+ return (list ?? []).map((n) => (typeof n === "string" ? { name: n } : n)).filter((n) => typeof n.name === "string" && n.name !== "");
268
+ }
269
+ function setCommands(preview, flags) {
270
+ const needs = preview.target_needs ?? {};
271
+ return {
272
+ secrets: valueNeeds(needs.secrets).map((n) => secretSetCommand(n.name, flags)),
273
+ variables: valueNeeds(needs.variables).map((n) => variableSetCommand(n.name, flags)),
274
+ };
275
+ }
276
+ function needLines(needs, command, more) {
277
+ const shown = needs.slice(0, 10).map((n) => {
278
+ const about = n.description ? ` (${clip(n.description, 80)})` : "";
279
+ return `\n - ${n.name}${about}: ${command(n.name)}`;
280
+ });
281
+ return shown.join("") + (needs.length > 10 ? `\n … ${needs.length - 10} more: ${more}` : "");
282
+ }
283
+ function indented(lines) {
284
+ return lines.map((line) => "\n " + line).join("");
285
+ }
286
+ function counts(map) {
287
+ const entries = Object.entries(map ?? {}).filter(([, n]) => n);
288
+ return entries.length ? entries.map(([k, n]) => `${n} ${k}`).join(", ") : "";
289
+ }
290
+ function list(items, max = 10) {
291
+ return items.length > max ? `${items.slice(0, max).join(", ")} and ${items.length - max} more` : items.join(", ");
292
+ }
293
+ function needsLines(needs, flags) {
294
+ const lines = [];
295
+ const secrets = valueNeeds(needs.secrets);
296
+ if (secrets.length) {
297
+ const each = needLines(secrets, (name) => secretSetCommand(name, flags), "cavelon secrets list --missing" + flags);
298
+ lines.push(["needs secrets", `${each}\n (a person runs these in a terminal, or sets them in the Admin; never the agent)`]);
299
+ }
300
+ const variables = valueNeeds(needs.variables);
301
+ if (variables.length)
302
+ lines.push(["needs variables", needLines(variables, (name) => variableSetCommand(name, flags), "cavelon variables list" + flags)]);
303
+ const grants = (needs.oauth_grants ?? []).map((g) => [g.kind, g.tool_slug, g.capability].filter(Boolean).join(" "));
304
+ if (grants.length)
305
+ lines.push(["needs grants", `${list(grants)} (a person connects them in the Admin)`]);
306
+ const bindings = (needs.runtime_bindings ?? []).map((b) => `${b.key}${b.kind ? ` (${b.kind})` : ""}`);
307
+ if (bindings.length)
308
+ lines.push(["needs bindings", `${list(bindings)} (runtime_bindings in env/<name>.yaml)`]);
309
+ const triggers = (needs.trigger_identities ?? []).map((t) => `${t.harness_slug}/${t.trigger_slug}: ${(t.problems ?? []).join(", ")}${t.admin_path ? ` → ${t.admin_path}` : ""}`);
310
+ if (triggers.length)
311
+ lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
312
+ return lines;
313
+ }
314
+ export function previewText(p, flags = "") {
315
+ const lines = [["ready", p.ready ? "yes" : "no"]];
316
+ const s = p.summary ?? {};
317
+ for (const [label, map] of [["creates", s.creates], ["updates", s.updates], ["deletes", s.deletes]]) {
318
+ const text = counts(map);
319
+ if (text)
320
+ lines.push([label, text]);
321
+ }
322
+ if (lines.length === 1)
323
+ lines.push(["changes", "none"]);
324
+ if (p.blockers?.length)
325
+ lines.push(["blockers", p.blockers.map((b) => `\n - ${clip(b, 300)}`).join("")]);
326
+ if (p.warnings?.length)
327
+ lines.push(["warnings", p.warnings.slice(0, 10).map((w) => `\n - ${clip(w, 300)}`).join("") + (p.warnings.length > 10 ? `\n … ${p.warnings.length - 10} more` : "")]);
328
+ const ignored = [...(p.ignored?.sections ?? []), ...(p.ignored?.fields ?? [])];
329
+ if (ignored.length)
330
+ lines.push(["ignored", list(ignored)]);
331
+ const impact = p.impact ?? {};
332
+ const active = (impact.active_harnesses ?? []).map((h) => {
333
+ const via = [...(h.tools ?? []), ...(h.knowledge_bases ?? []), ...(h.sandboxes ?? [])];
334
+ return `${h.name ?? h.harness_slug} (${h.harness_slug})${via.length ? ` through ${list(via, 5)}` : ""}`;
335
+ });
336
+ if (active.length)
337
+ lines.push(["reaches active", active.map((a) => `\n - ${a}`).join("")]);
338
+ if (impact.sandbox_writers?.length)
339
+ lines.push(["busy sandboxes", list(impact.sandbox_writers.map((w) => w.name ?? w.sandbox_id ?? "?"))]);
340
+ for (const budget of p.loop_budgets ?? []) {
341
+ const limits = Object.entries(budget.limits ?? {}).map(([k, v]) => `${k} ${v}`).join(", ");
342
+ lines.push([`loop ${budget.node_slug}`, `${limits}${budget.worst_case_cost != null ? `; worst case ${JSON.stringify(budget.worst_case_cost)}` : ""}`]);
343
+ }
344
+ lines.push(...needsLines(p.target_needs ?? {}, flags));
345
+ return keyValues(lines);
346
+ }
347
+ function previewIdOption(input) {
348
+ const id = stringOption(input, "confirm");
349
+ if (id !== undefined && !id.trim())
350
+ throw usageError("--confirm needs the preview id that `cavelon apply` printed.");
351
+ return id?.trim();
352
+ }
353
+ async function confirmPreview(ctx, project, previewId) {
354
+ const stored = await loadPreview(project.root, previewId);
355
+ if (!stored) {
356
+ throw new CavelonError(ExitCode.usage, {
357
+ code: "preview_unknown",
358
+ message: `No open preview ${previewId} in this solution.`,
359
+ hint: "Run `cavelon apply` (with the same --env or --harness) for a new preview and confirm its id; `cavelon status` lists the open ones.",
360
+ });
361
+ }
362
+ const session = await ctx.session();
363
+ if (requireInstance(session) !== stored.instance) {
364
+ throw new CavelonError(ExitCode.conflict, {
365
+ code: "preview_other_instance",
366
+ message: `Preview ${previewId} was made on ${stored.instance}, not ${session.url}.`,
367
+ hint: "Confirm it with the instance it was made on, or preview again here.",
368
+ });
369
+ }
370
+ const client = await ctx.client();
371
+ if (stored.tenant_id && session.tokenKind !== "api_key" && client.target.tenantId && client.target.tenantId !== stored.tenant_id) {
372
+ throw new CavelonError(ExitCode.conflict, {
373
+ code: "preview_other_tenant",
374
+ message: `Preview ${previewId} was made for tenant ${stored.tenant_id}, but this command acts in ${client.target.tenantId}.`,
375
+ hint: stored.env ? `Pass the same --env ${stored.env} as the preview.` : "Use the tenant of the preview, or preview again here.",
376
+ });
377
+ }
378
+ if (stored.tenant_id && session.tokenKind !== "api_key")
379
+ client.target.tenantId = stored.tenant_id;
380
+ const disk = await readPackage(project.root, project.layout);
381
+ if (digest(disk.package) !== stored.package_digest) {
382
+ ctx.warn("The package files changed since this preview; importing what the preview showed. Run `cavelon apply` to preview the files as they are now.");
383
+ }
384
+ try {
385
+ const result = await callStable(ctx, "POST", "/api/v1/agent-graph/import", "importing packages", {
386
+ body: { ...stored.request, preview_id: stored.preview_id },
387
+ timeoutMs: 300_000,
388
+ });
389
+ for (const other of await listPreviews(project.root))
390
+ await deletePreview(project.root, other.preview_id);
391
+ const summary = (result.summary ?? {});
392
+ const flags = stored.env ? ` --env ${shellWord(stored.env)}` : targetFlags(session);
393
+ const still = setCommands(stored.preview, flags);
394
+ const text = keyValues([
395
+ ["applied", `preview ${stored.preview_id}${stored.harness ? ` to ${stored.harness.slug}` : ""}${stored.env ? ` (env ${stored.env})` : ""}`],
396
+ ["created", counts(summary?.creates) || undefined],
397
+ ["updated", counts(summary?.updates) || undefined],
398
+ ["deleted", counts(summary?.deletes) || undefined],
399
+ ["warnings", Array.isArray(result.warnings) && result.warnings.length ? result.warnings.map((w) => `\n - ${clip(w, 300)}`).join("") : undefined],
400
+ ["set secrets", still.secrets.length ? indented(still.secrets) + "\n (a person runs these; never the agent)" : undefined],
401
+ ["set variables", still.variables.length ? indented(still.variables) : undefined],
402
+ ]);
403
+ const data = { applied: true, preview_id: stored.preview_id, env: stored.env, harness: stored.harness, result };
404
+ if (still.secrets.length || still.variables.length)
405
+ data.set_commands = still;
406
+ return { data, text };
407
+ }
408
+ catch (error) {
409
+ if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && error.blockers?.length) {
410
+ await deletePreview(project.root, stored.preview_id);
411
+ throw requirementsChanged(error, stored, await catalogFor(ctx, false));
412
+ }
413
+ if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
414
+ await deletePreview(project.root, stored.preview_id);
415
+ throw new CavelonError(ExitCode.conflict, {
416
+ code: error.code === "conflict" ? "import_preview_stale" : error.code,
417
+ status: 409,
418
+ message: `The target changed since preview ${stored.preview_id}; nothing was imported.`,
419
+ hint: `Run \`${cavelonCommand("apply", ...previewTarget(stored))}\` again, show the new preview, and confirm its id.`,
420
+ docs: error.docs,
421
+ });
422
+ }
423
+ throw error;
424
+ }
425
+ }
426
+ const REQUIREMENTS_CHANGED = "package_requirements_changed";
427
+ function requirementsChanged(error, stored, catalog) {
428
+ const blockers = error.blockers ?? [];
429
+ const known = new Map();
430
+ for (const blocker of blockers) {
431
+ const pair = pairOrderHint(catalog, [blocker]);
432
+ if (pair && !known.has(pair.code))
433
+ known.set(pair.code, pair.hint);
434
+ }
435
+ return new CavelonError(ExitCode.conflict, {
436
+ code: error.code,
437
+ status: error.status,
438
+ message: `The import's requirements changed since preview ${stored.preview_id}; nothing was imported; preview again.`,
439
+ hint: [...known.values(), `Run \`${cavelonCommand("apply", ...previewTarget(stored))}\` again, show the new preview, and confirm its id.`].join(" "),
440
+ docs: error.docs,
441
+ blockers,
442
+ });
443
+ }
444
+ function previewTarget(stored) {
445
+ if (stored.env)
446
+ return ["--env", stored.env];
447
+ return stored.harness ? ["--harness", stored.harness.slug] : [];
448
+ }
449
+ async function applyTarget(ctx, session, input, pkg) {
450
+ const { ref, source } = harnessRef(session, input);
451
+ if (!ref)
452
+ return undefined;
453
+ const found = await findHarness(ctx, ref);
454
+ if (found)
455
+ return { ...found, created: false };
456
+ if (!source?.startsWith("env/") || isUuid(ref))
457
+ throw harnessNotFound(ref, source);
458
+ const name = packageHarnessName(pkg, ref) ?? ref;
459
+ const created = await callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", { body: { slug: ref, name } });
460
+ ctx.warn(`Created the draft solution ${created.name} (${created.slug}) that ${source} names.`);
461
+ return { ...created, created: true };
462
+ }
463
+ function packageHarnessName(pkg, slug) {
464
+ const entries = (Array.isArray(pkg.harnesses) ? pkg.harnesses : []).filter((h) => Boolean(h) && typeof h === "object" && !Array.isArray(h));
465
+ const entry = entries.find((h) => h.slug === slug) ?? (entries.length === 1 ? entries[0] : undefined);
466
+ const name = typeof entry?.name === "string" ? entry.name.trim() : "";
467
+ return name ? name.slice(0, 255) : undefined;
468
+ }
469
+ function personReason(preview, harness, mode, env) {
470
+ if (preview.impact?.active_harnesses?.length || harness?.status === "active")
471
+ return "reaches an active solution";
472
+ if (counts(preview.summary?.deletes) || mode === "replace")
473
+ return "deletes";
474
+ if (env === "prod")
475
+ return "goes to env/prod";
476
+ return undefined;
477
+ }
478
+ export const apply = {
479
+ name: "apply",
480
+ summary: "Preview the package files against the instance and print a preview id; --confirm <id> imports exactly that preview.",
481
+ description: "Without --confirm nothing is imported: the preview shows what changes, which active solutions it reaches, what the target\n" +
482
+ "still needs (secrets and variables with the command that sets each, grants, runtime bindings, trigger identities), loop\n" +
483
+ "budgets and ignored sections, and is stored in .cavelon/. When the env file names a solution that does not exist yet,\n" +
484
+ "apply creates it as a draft first. A person sets the secrets (`cavelon secrets set <name>`), never the agent.\n" +
485
+ "Show a preview that reaches an active solution or env/prod to a person before confirming. A stale preview exits 4;\n" +
486
+ "so does an import its own check refuses when it applies, naming each blocker.",
487
+ readOnly: false,
488
+ destructive: true,
489
+ mcpTool: "apply",
490
+ options: {
491
+ env: ENV_OPTION,
492
+ harness: HARNESS_OPTION,
493
+ confirm: { type: "string", value: "<preview-id>", description: "Import exactly this stored preview." },
494
+ mode: { type: "string", value: "<mode>", description: "overwrite (default) or replace (deletes what the package does not hold)." },
495
+ },
496
+ examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json"],
497
+ async run(ctx, input) {
498
+ const session = await ctx.session();
499
+ const project = requireSolution(session);
500
+ const url = requireInstance(session);
501
+ const confirm = previewIdOption(input);
502
+ if (confirm)
503
+ return confirmPreview(ctx, project, confirm);
504
+ const envFile = session.envFile;
505
+ if (envFile && !envFile.exists) {
506
+ throw usageError(`No ${path.relative(project.root, envFile.file).split(path.sep).join("/")}.`, "`cavelon init` writes env/test.yaml and env/prod.yaml.");
507
+ }
508
+ if (envFile?.tenant && session.tenantSource !== `env/${envFile.name}.yaml`) {
509
+ ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over ${envFile.name}.yaml's "${envFile.tenant}".`);
510
+ }
511
+ const mode = (stringOption(input, "mode") ?? envFile?.mode ?? "overwrite");
512
+ if (mode !== "overwrite" && mode !== "replace")
513
+ throw usageError(`--mode must be overwrite or replace, got "${mode}".`);
514
+ const { disk, findings } = await validatePackage(ctx, project, false);
515
+ if (disk.empty)
516
+ throw usageError(`No package files in ${project.layout.package}/.`, "Run `cavelon pull --harness <slug>` first, or write the package files.");
517
+ const errors = findings.filter((f) => f.severity === "error");
518
+ if (errors.length) {
519
+ return {
520
+ data: { previewed: false, errors: errors.length, findings: errors.slice(0, 50) },
521
+ text: [...errors.slice(0, 20).map(findingLine), `${errors.length} error(s); fix them first (\`cavelon validate\`).`].join("\n"),
522
+ exitCode: ExitCode.validation,
523
+ };
524
+ }
525
+ const harness = await applyTarget(ctx, session, input, disk.package);
526
+ const scope = disk.package.manifest?.scope ?? "agent_graph";
527
+ if (harness && scope === "full_config")
528
+ ctx.warn("The package is a full configuration; the instance imports it tenant-wide, whatever the solution.");
529
+ const request = { package: disk.package, mode };
530
+ if (harness)
531
+ request.harness_id = harness.id;
532
+ if (envFile && Object.keys(envFile.runtimeBindings).length)
533
+ request.runtime_bindings = envFile.runtimeBindings;
534
+ const client = await ctx.client();
535
+ const preview = await callStable(ctx, "POST", "/api/v1/agent-graph/import/preview", "previewing imports", {
536
+ body: request,
537
+ timeoutMs: 120_000,
538
+ });
539
+ const target = harness ? { id: harness.id, slug: harness.slug, created: harness.created } : null;
540
+ const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target };
541
+ const flags = targetFlags(session);
542
+ const commands = setCommands(preview, flags);
543
+ if (commands.secrets.length || commands.variables.length)
544
+ data.set_commands = commands;
545
+ if (!preview.preview_id) {
546
+ ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
547
+ }
548
+ if (!preview.ready) {
549
+ const pair = pairOrderHint(await catalogFor(ctx, false), preview.blockers ?? []);
550
+ if (pair)
551
+ data.hint = pair.hint;
552
+ return {
553
+ data,
554
+ text: [
555
+ previewText(preview, flags),
556
+ "",
557
+ ...(pair ? [`hint: ${pair.hint}`] : []),
558
+ "The preview has blockers; fix them and run `cavelon apply` again.",
559
+ ].join("\n"),
560
+ exitCode: ExitCode.validation,
561
+ };
562
+ }
563
+ if (preview.preview_id) {
564
+ const stored = {
565
+ preview_id: preview.preview_id,
566
+ created_at: ctx.io.now().toISOString(),
567
+ instance: url,
568
+ tenant_id: client.target.tenantId ?? null,
569
+ env: envFile?.name ?? null,
570
+ harness: target,
571
+ package_digest: digest(disk.package),
572
+ request,
573
+ preview,
574
+ };
575
+ await savePreview(project.root, stored);
576
+ }
577
+ const reason = personReason(preview, harness, mode, envFile?.name);
578
+ data.show_to_person = Boolean(reason);
579
+ const envFlags = envFile ? ["--env", envFile.name] : [];
580
+ const confirmLine = preview.preview_id ? cavelonCommand("apply", "--confirm", preview.preview_id, ...envFlags) : undefined;
581
+ const text = [
582
+ `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
583
+ previewText(preview, flags),
584
+ "",
585
+ ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
586
+ ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
587
+ ...(confirmLine ? [`Import exactly this: ${confirmLine}`] : []),
588
+ ].join("\n");
589
+ return { data, text };
590
+ },
591
+ };
592
+ const PROCESSING_STEP_CAP_CODE = "PROCESSING_STEP_CAP_REACHED";
593
+ function looseEntry(catalog, code) {
594
+ const wanted = code.toLowerCase();
595
+ const all = [...(catalog?.rule_codes ?? []), ...(catalog?.api_error_codes ?? [])].map((e) => e.code);
596
+ const same = all.filter((c) => c.toLowerCase() === wanted);
597
+ const prefixed = all.filter((c) => c.toLowerCase().startsWith(`${wanted}_`));
598
+ const hit = same.length === 1 ? same[0] : same.length === 0 && prefixed.length === 1 ? prefixed[0] : undefined;
599
+ return hit ? catalogEntry(catalog, hit) : undefined;
600
+ }
601
+ function processingStepCapHint(limits) {
602
+ const cap = limits?.tenantQuotas?.values.find((v) => v.key === "monthly_processing_step_cap");
603
+ const raise = "A Tenant Owner raises or removes it with `cavelon limits set monthly_processing_step_cap <n|none> --confirm` (settings.manage), or in the Admin; started work finishes.";
604
+ if (!cap)
605
+ return `New work starts again when the billing month resets. ${raise}`;
606
+ const value = cap.value === null ? "no cap" : `${cap.value} Processing Steps`;
607
+ const used = cap.used === null ? "" : `, ${cap.used} used${cap.period ? ` in ${cap.period.key}` : ""}`;
608
+ const resets = cap.period ? ` It resets at ${cap.period.resets_at}.` : "";
609
+ return `monthly_processing_step_cap is ${value}${used} (state: ${cap.state}).${resets} ${raise}`;
610
+ }
611
+ export const explain = {
612
+ name: "explain",
613
+ summary: "Look a code up in the instance's error catalog: what it means and how to fix it.",
614
+ description: "Rule codes come from the package and graph checks, API error codes from failed requests. Uses the cached catalog first.",
615
+ readOnly: true,
616
+ idempotent: true,
617
+ mcpTool: "explain",
618
+ positionals: [{ name: "code", description: "The code, e.g. from `cavelon validate` or an error's code.", required: true }],
619
+ async run(ctx, input) {
620
+ const code = positional(input, "code").trim();
621
+ let catalog = await catalogFor(ctx, false);
622
+ let entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code);
623
+ if (!entry || entry.kind === "kit") {
624
+ catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
625
+ entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code) ?? entry;
626
+ }
627
+ if (!catalog && !entry) {
628
+ throw new CavelonError(ExitCode.failure, {
629
+ code: "error_catalog_unavailable",
630
+ message: "This instance does not publish its error catalog (/api/v1/meta/error-catalog).",
631
+ hint: "Try `cavelon docs search <code>`.",
632
+ });
633
+ }
634
+ if (!entry) {
635
+ const all = [...(catalog?.rule_codes ?? []), ...(catalog?.api_error_codes ?? []), ...KIT_CODES].map((e) => e.code);
636
+ const words = code.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2);
637
+ const similar = all.filter((c) => words.some((w) => c.toLowerCase().includes(w))).slice(0, 8);
638
+ throw new CavelonError(ExitCode.failure, {
639
+ code: "code_unknown",
640
+ message: `"${code}" is not in this instance's error catalog.`,
641
+ hint: similar.length ? `Similar codes: ${similar.join(", ")}.` : `Try \`cavelon docs search ${code}\`.`,
642
+ });
643
+ }
644
+ const docs = entry.docs?.startsWith("/") ? `${requireInstance(await ctx.session())}${entry.docs}` : entry.docs;
645
+ const capacity = capacityCodeIn(entry.code);
646
+ const stepCap = entry.code.toUpperCase() === PROCESSING_STEP_CAP_CODE;
647
+ const ceiling = entry.code === LIMIT_ABOVE_CEILING;
648
+ const kitHint = capacity
649
+ ? capacityHint(capacity, await readLimits(ctx).catch(() => undefined))
650
+ : stepCap
651
+ ? processingStepCapHint(await readLimits(ctx).catch(() => undefined))
652
+ : ceiling
653
+ ? ceilingHint(await readLimits(ctx).catch(() => undefined))
654
+ : pairOrderPointer(entry.code);
655
+ const pages = capacity === MODEL_ENDPOINT_BUSY ? [CAPACITY_TUTORIAL_PAGE, CAPACITY_CONCEPT_PAGE] : [CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE];
656
+ const read = capacity ? (await listedPages(ctx, pages)).map((page) => ({ page, command: cavelonCommand("docs", "get", page) })) : [];
657
+ const data = { ...entry, docs, ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
658
+ return {
659
+ data,
660
+ text: keyValues([
661
+ ["code", entry.code],
662
+ [
663
+ "kind",
664
+ entry.kind === "rule"
665
+ ? `rule code${entry.rule ? ` (rule ${entry.rule})` : ""}`
666
+ : entry.kind === "kit"
667
+ ? "cavelon validate code"
668
+ : `API error code${entry.area ? ` (${entry.area})` : ""}`,
669
+ ],
670
+ ["meaning", entry.message],
671
+ ["fix", entry.hint ?? undefined],
672
+ [capacity || stepCap || ceiling ? "raise" : "order", kitHint],
673
+ ["why", entry.explanation ? clip(entry.explanation.replace(/\s+/g, " "), 600) : undefined],
674
+ ["docs", docs],
675
+ ["read", read.length ? read.map((r) => r.command).join("; ") : undefined],
676
+ ]),
677
+ };
678
+ },
679
+ };
680
+ function checkLine(c) {
681
+ return clip([c.label ?? c.key, c.message ?? c.detail].filter(Boolean).join(": "), 300);
682
+ }
683
+ function readinessChecks(readiness) {
684
+ const fallback = [
685
+ ...(readiness.blockers ?? []).map((c) => ({ ...c, state: c.state ?? "blocker" })),
686
+ ...(readiness.warnings ?? []).map((c) => ({ ...c, state: c.state ?? "warning" })),
687
+ ];
688
+ return (readiness.checks ?? fallback).map((c) => ({
689
+ key: c.key ?? null,
690
+ label: c.label ?? null,
691
+ state: c.state ?? "unknown",
692
+ detail: c.detail ?? c.message ?? null,
693
+ }));
694
+ }
695
+ function readinessText(checks, warnings) {
696
+ const width = Math.max(0, ...checks.map((c) => c.state.length));
697
+ return [
698
+ ...(checks.length ? ["Readiness checks:", ...checks.map((c) => ` ${c.state.padEnd(width)} ${checkLine(c)}`)] : []),
699
+ ...(warnings.length ? ["Warnings:", ...warnings.map((w) => ` - ${w}`)] : []),
700
+ ];
701
+ }
702
+ export const activate = {
703
+ name: "activate",
704
+ summary: "Activate a solution through the readiness gate (never by force).",
705
+ description: "Only when every readiness check passes, and with a personal access token only when it was created with \"may activate\".\n" +
706
+ "Activating without the evidence stays a person's decision in the Admin.",
707
+ readOnly: false,
708
+ idempotent: true,
709
+ mcpTool: "activate",
710
+ options: { harness: HARNESS_OPTION, env: ENV_OPTION },
711
+ async run(ctx, input) {
712
+ const session = await ctx.session();
713
+ const { ref, source } = harnessRef(session, input);
714
+ if (!ref)
715
+ throw usageError("Which solution?", "Pass --harness <slug>, or set harness in cavelon.yaml or the env file.");
716
+ const client = await ctx.client();
717
+ const principal = await readPrincipal(client);
718
+ if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
719
+ throw new CavelonError(ExitCode.unauthorized, {
720
+ code: "token_activation_refused",
721
+ message: `The personal access token "${principal.token.name}" was not created with "may activate", so it cannot activate solutions.`,
722
+ hint: "A person activates the solution in the Admin, or creates a token with \"may activate\" on /account/access-tokens.",
723
+ });
724
+ }
725
+ const harness = await findHarness(ctx, ref);
726
+ if (!harness)
727
+ throw harnessNotFound(ref, source);
728
+ if (harness.status === "active") {
729
+ return { data: { activated: false, already_active: true, harness }, text: `${harness.name} (${harness.slug}) is already active.` };
730
+ }
731
+ const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
732
+ params: { harness_id: [harness.id] },
733
+ });
734
+ const checks = readinessChecks(readiness);
735
+ const warnings = (readiness.warnings ?? []).map(checkLine);
736
+ if (!readiness.ready_to_activate) {
737
+ const blockers = readiness.blockers ?? [];
738
+ const pair = pairOrderHint(await catalogFor(ctx, false), blockers.flatMap((b) => [b.message ?? undefined, b.detail ?? undefined]));
739
+ return {
740
+ data: { activated: false, harness, checks, warnings, readiness, ...(pair ? { hint: pair.hint } : {}) },
741
+ text: [
742
+ `${harness.name} (${harness.slug}) is not ready to activate:`,
743
+ ...blockers.map((b) => ` - ${checkLine(b)}`),
744
+ ...readinessText(checks, warnings),
745
+ ...(pair ? [`hint: ${pair.hint}`] : []),
746
+ "Resolve these (often: a passing test run), then activate again. Forcing past the gate is a person's decision in the Admin.",
747
+ ].join("\n"),
748
+ exitCode: ExitCode.validation,
749
+ };
750
+ }
751
+ const activated = await callStable(ctx, "POST", "/api/v1/harnesses/{harness_id}/activate", "activating solutions", {
752
+ params: { harness_id: [harness.id] },
753
+ body: { force: false },
754
+ });
755
+ return {
756
+ data: { activated: true, harness: activated, checks, warnings, readiness },
757
+ text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings)].join("\n"),
758
+ };
759
+ },
760
+ };