@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,744 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
+ import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../capacity.js";
5
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
6
+ import { clip, keyValues, moreHint, table } from "../format.js";
7
+ import { callStable } from "../invoke.js";
8
+ import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
9
+ import { getOperation } from "../operations.js";
10
+ import { caseCounts, caseLabel, failedCase, NOT_PASSED } from "../results.js";
11
+ import { isUuid } from "../session.js";
12
+ import { cavelonCommand, shellWord } from "../shell.js";
13
+ import { readZipSummary, ZipError } from "../zip.js";
14
+ import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
15
+ import { stageErrors, stageErrorText } from "./loops.js";
16
+ import { resolveHarnessId } from "./tenants.js";
17
+ const WAIT_OPTION = { type: "boolean", description: "Wait for the work to finish (see `cavelon wait`).", cliOnly: true };
18
+ async function resolveKbId(ctx, ref) {
19
+ if (isUuid(ref))
20
+ return { id: ref };
21
+ const page = await callStable(ctx, "GET", "/api/v1/knowledge-bases", "knowledge bases", {
22
+ query: { search: ref, page_size: 100 },
23
+ });
24
+ const wanted = ref.toLowerCase();
25
+ const hits = (page.items ?? []).filter((kb) => kb.name.toLowerCase() === wanted);
26
+ if (hits.length === 1)
27
+ return { id: hits[0].id, name: hits[0].name };
28
+ throw new CavelonError(ExitCode.failure, {
29
+ code: hits.length ? "kb_ambiguous" : "kb_not_found",
30
+ message: hits.length ? `${hits.length} knowledge bases are named "${ref}".` : `No knowledge base named "${ref}".`,
31
+ hint: "Pass its id; `cavelon api list_knowledge_bases` lists them.",
32
+ });
33
+ }
34
+ async function collectFiles(dir, recursive, extensions) {
35
+ const out = [];
36
+ const walk = async (current) => {
37
+ const entries = (await fs.readdir(current, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
38
+ for (const entry of entries) {
39
+ if (entry.name.startsWith("."))
40
+ continue;
41
+ const full = path.join(current, entry.name);
42
+ if (entry.isDirectory()) {
43
+ if (recursive)
44
+ await walk(full);
45
+ }
46
+ else if (entry.isFile()) {
47
+ const ext = path.extname(entry.name).slice(1).toLowerCase();
48
+ if (extensions.length === 0 || extensions.includes(ext))
49
+ out.push(full);
50
+ }
51
+ }
52
+ };
53
+ await walk(dir);
54
+ return out;
55
+ }
56
+ const MB = 1024 * 1024;
57
+ const mb = (bytes) => (bytes / MB).toFixed(1);
58
+ const fileWith = (r, what) => `${r.file} (${what})`;
59
+ const limitNote = (limit) => `${limit.key}, source ${limit.source}; ${changedBy(limit)} changes ${limit.setting}`;
60
+ function archivesOff(limits) {
61
+ if (typeof limits.enabled?.value === "boolean")
62
+ return !limits.enabled.value;
63
+ return !(Array.isArray(limits.archives?.value) && limits.archives.value.length);
64
+ }
65
+ function archiveLimit(limits) {
66
+ return archivesOff(limits) && limits.enabled ? limits.enabled : (limits.archives ?? limits.enabled);
67
+ }
68
+ function formatsText(limits) {
69
+ if (archivesOff(limits))
70
+ return "has archive uploads turned off";
71
+ const formats = Array.isArray(limits.archives?.value) ? limits.archives.value : [];
72
+ return formats.length ? `expands only ${formats.join(", ")}` : "expands no archive type";
73
+ }
74
+ function disabledCode(limits) {
75
+ return archivesOff(limits) ? "archive_uploads_disabled" : "archive_format_disabled";
76
+ }
77
+ const REASONS = {
78
+ too_large: {
79
+ limit: (l) => l.size,
80
+ code: () => "upload_file_too_large",
81
+ item: (r) => fileWith(r, `${mb(r.size_bytes)} MB`),
82
+ verb: ["is", "are"],
83
+ rest: (l) => `larger than ${String(l.value)} MB (${limitNote(l)})`,
84
+ },
85
+ type_not_allowed: {
86
+ limit: (l) => l.types,
87
+ code: () => "upload_file_type_unsupported",
88
+ item: (r) => fileWith(r, r.extension ? `.${r.extension}` : "no extension"),
89
+ verb: ["has a type", "have types"],
90
+ rest: (l) => `this tenant does not accept (${limitNote(l)})`,
91
+ },
92
+ archive_not_expanded: {
93
+ limit: archiveLimit,
94
+ code: disabledCode,
95
+ item: (r) => r.file,
96
+ verb: ["is a zip archive,", "are zip archives,"],
97
+ rest: (l, limits) => `and this tenant ${formatsText(limits)} (${limitNote(l)})`,
98
+ },
99
+ not_a_zip: {
100
+ limit: archiveLimit,
101
+ code: () => "archive_magic_invalid",
102
+ item: (r) => r.file,
103
+ verb: ["is", "are"],
104
+ rest: () => "not a zip archive, though named .zip",
105
+ },
106
+ archive_too_many_files: {
107
+ limit: (l) => l.entries,
108
+ code: () => "archive_entry_limit_exceeded",
109
+ item: (r) => fileWith(r, `${r.archive?.files} files`),
110
+ verb: ["holds", "hold"],
111
+ rest: (l) => `more files than ${String(l.value)} (${limitNote(l)})`,
112
+ },
113
+ archive_too_large_unpacked: {
114
+ limit: (l) => l.unpacked,
115
+ code: () => "archive_uncompressed_size_exceeded",
116
+ item: (r) => fileWith(r, `${mb(r.archive?.unpacked_bytes ?? 0)} MB unpacked`),
117
+ verb: ["unpacks", "unpack"],
118
+ rest: (l) => `to more than ${String(l.value)} MB (${limitNote(l)})`,
119
+ },
120
+ archive_ratio_too_high: {
121
+ limit: (l) => l.ratio,
122
+ code: () => "archive_compression_ratio_exceeded",
123
+ item: (r) => fileWith(r, `${r.archive?.max_ratio_entry ?? "a file"} at ${r.archive?.max_ratio ?? "∞"}:1`),
124
+ verb: ["compresses", "compress"],
125
+ rest: (l) => `a file more than ${String(l.value)}:1 (${limitNote(l)})`,
126
+ },
127
+ };
128
+ function uploadLimits(limits) {
129
+ const binding = (key) => {
130
+ const limit = limits.byKey.get(key);
131
+ return limit && bindsNow(limit, limits) ? limit : undefined;
132
+ };
133
+ return {
134
+ size: binding("kb_upload_max_file_size_mb"),
135
+ types: binding("kb_upload_allowed_extensions"),
136
+ enabled: binding("kb_upload_archive_enabled"),
137
+ archives: binding("kb_upload_archive_formats"),
138
+ entries: binding("kb_upload_archive_max_entries"),
139
+ unpacked: binding("kb_upload_archive_max_total_uncompressed_mb"),
140
+ ratio: binding("kb_upload_archive_max_compression_ratio"),
141
+ };
142
+ }
143
+ const numeric = (limit) => (typeof limit?.value === "number" ? limit.value : undefined);
144
+ async function archiveRefusal(file, limits, warn) {
145
+ if (archivesOff(limits))
146
+ return { reason: "archive_not_expanded" };
147
+ const formats = Array.isArray(limits.archives?.value) ? new Set(limits.archives.value.map((f) => f.toLowerCase().replace(/^\./, ""))) : undefined;
148
+ if (formats && !formats.has("zip"))
149
+ return { reason: "archive_not_expanded" };
150
+ let summary;
151
+ try {
152
+ summary = await readZipSummary(file);
153
+ }
154
+ catch (error) {
155
+ if (error instanceof ZipError && error.notZip)
156
+ return { reason: "not_a_zip" };
157
+ warn(`Could not read the zip directory of ${path.basename(file)} (${error instanceof Error ? error.message : String(error)}); the instance checks it.`);
158
+ return undefined;
159
+ }
160
+ const archive = {
161
+ files: summary.files,
162
+ unpacked_bytes: summary.uncompressedBytes,
163
+ max_ratio: Number.isFinite(summary.maxRatio) ? Math.round(summary.maxRatio * 10) / 10 : null,
164
+ max_ratio_entry: summary.maxRatioEntry,
165
+ };
166
+ const entries = numeric(limits.entries);
167
+ const unpacked = numeric(limits.unpacked);
168
+ const ratio = numeric(limits.ratio);
169
+ if (entries !== undefined && summary.files > entries)
170
+ return { reason: "archive_too_many_files", archive };
171
+ if (unpacked !== undefined && summary.uncompressedBytes > unpacked * MB)
172
+ return { reason: "archive_too_large_unpacked", archive };
173
+ if (ratio !== undefined && summary.maxRatio > ratio)
174
+ return { reason: "archive_ratio_too_high", archive };
175
+ return undefined;
176
+ }
177
+ async function uploadRefusals(files, cwd, published, warn) {
178
+ const limits = uploadLimits(published);
179
+ const size = numeric(limits.size);
180
+ const check = {
181
+ maxBytes: size === undefined ? undefined : size * MB,
182
+ allowed: Array.isArray(limits.types?.value) ? new Set(limits.types.value.map((e) => e.toLowerCase().replace(/^\./, ""))) : undefined,
183
+ };
184
+ const refusals = [];
185
+ for (const file of files) {
186
+ const refused = await refusalFor(file, cwd, limits, check, warn);
187
+ if (refused)
188
+ refusals.push(refused);
189
+ }
190
+ return { refusals, limits };
191
+ }
192
+ async function refusalFor(file, cwd, limits, check, warn) {
193
+ const name = path.basename(file);
194
+ const dot = name.lastIndexOf(".");
195
+ const extension = dot >= 0 ? name.slice(dot + 1).toLowerCase() : "";
196
+ const bytes = (await fs.stat(file)).size;
197
+ const base = { file: path.relative(cwd, file) || file, size_bytes: bytes, extension };
198
+ if (check.maxBytes !== undefined && bytes > check.maxBytes)
199
+ return { ...base, reason: "too_large" };
200
+ if (extension === "zip") {
201
+ const refused = limits.archives || limits.enabled ? await archiveRefusal(file, limits, warn) : undefined;
202
+ return refused ? { ...base, ...refused } : undefined;
203
+ }
204
+ if (check.allowed && !check.allowed.has(extension))
205
+ return { ...base, reason: "type_not_allowed" };
206
+ return undefined;
207
+ }
208
+ function clause(reason, list, limit, limits) {
209
+ const { item, verb, rest } = REASONS[reason];
210
+ const more = list.length > 5 ? ` and ${list.length - 5} more` : "";
211
+ return `${list.slice(0, 5).map(item).join(", ")}${more} ${verb[list.length === 1 ? 0 : 1]} ${rest(limit, limits)}`;
212
+ }
213
+ function refusalError(found, total) {
214
+ const { refusals, limits } = found;
215
+ const reasons = Object.keys(REASONS).filter((reason) => refusals.some((r) => r.reason === reason));
216
+ const parts = [];
217
+ const involved = [];
218
+ for (const reason of reasons) {
219
+ const limit = REASONS[reason].limit(limits);
220
+ parts.push(clause(reason, refusals.filter((r) => r.reason === reason), limit, limits));
221
+ if (!involved.includes(limit))
222
+ involved.push(limit);
223
+ }
224
+ return limitError({
225
+ code: REASONS[reasons[0]].code(limits),
226
+ message: `${refusals.length} of ${total} files break this instance's upload limits, so nothing was sent: ${parts.join("; ")}.`,
227
+ limits: involved,
228
+ details: { refused: refusals },
229
+ hint: "Leave those files out (--ext narrows the upload), or ask who can change the limit; a knowledge base may set lower limits of its own." +
230
+ (reasons.includes("archive_not_expanded") && archivesOff(limits) && limits.enabled?.change
231
+ ? ` A tenant admin turns archive uploads on with ${cavelonCommand("limits", "set", limits.enabled.key, "true")} (shows the change; --confirm sends it).`
232
+ : ""),
233
+ });
234
+ }
235
+ const BATCH_FILES = 20;
236
+ const BATCH_BYTES = 50 * 1024 * 1024;
237
+ export const kbUpload = {
238
+ name: "kb upload",
239
+ summary: "Upload a folder's documents into a knowledge base; returns operation ids.",
240
+ description: "Hidden files are skipped. Ingestion runs on the instance; `cavelon wait` follows it.\n" +
241
+ "Files are checked against the instance's published upload limits first. A .zip goes only to a tenant that expands\n" +
242
+ "archives, and only within its caps on file count, unpacked size and compression ratio.",
243
+ readOnly: false,
244
+ mcpTool: "kb_upload",
245
+ positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
246
+ options: {
247
+ kb: { type: "string", value: "<kb>", description: "Knowledge base name or id (required)." },
248
+ recursive: { type: "boolean", short: "r", description: "Include subfolders." },
249
+ ext: { type: "string", multiple: true, value: "<ext>", description: "Only these file extensions (pdf, md, …)." },
250
+ "dry-run": { type: "boolean", description: "List what would be uploaded, upload nothing." },
251
+ wait: WAIT_OPTION,
252
+ timeout: TIMEOUT_OPTION,
253
+ },
254
+ examples: ["cavelon kb upload ./docs --kb FAQ", "cavelon kb upload ./manuals --kb FAQ -r --ext pdf --wait --timeout 5m"],
255
+ async run(ctx, input) {
256
+ const dir = path.resolve(ctx.io.cwd, positional(input, "dir"));
257
+ const kbRef = stringOption(input, "kb");
258
+ if (!kbRef)
259
+ throw usageError("Which knowledge base?", "Pass --kb <name-or-id>.");
260
+ const extensions = listOption(input, "ext").flatMap((e) => e.split(",")).map((e) => e.replace(/^\./, "").toLowerCase()).filter(Boolean);
261
+ let stat;
262
+ try {
263
+ stat = await fs.stat(dir);
264
+ }
265
+ catch {
266
+ throw usageError(`${dir} does not exist.`);
267
+ }
268
+ const files = stat.isFile() ? [dir] : await collectFiles(dir, boolOption(input, "recursive"), extensions);
269
+ if (files.length === 0)
270
+ throw usageError(`No files to upload in ${dir}.`, extensions.length ? `Only ${extensions.join(", ")} files were considered.` : undefined);
271
+ const published = await limitsOrWarn(ctx);
272
+ if (published?.published) {
273
+ const found = await uploadRefusals(files, ctx.io.cwd, published, (message) => ctx.warn(message));
274
+ if (found.refusals.length)
275
+ throw refusalError(found, files.length);
276
+ }
277
+ if (boolOption(input, "dry-run")) {
278
+ const rel = files.map((f) => path.relative(ctx.io.cwd, f) || f);
279
+ return { data: { kb: kbRef, files: rel, count: rel.length, dry_run: true }, text: `Would upload ${rel.length} files:\n${rel.join("\n")}` };
280
+ }
281
+ const kb = await resolveKbId(ctx, kbRef);
282
+ const batches = [];
283
+ let current = [];
284
+ let bytes = 0;
285
+ for (const file of files) {
286
+ const size = (await fs.stat(file)).size;
287
+ if (current.length && (current.length >= BATCH_FILES || bytes + size > BATCH_BYTES)) {
288
+ batches.push(current);
289
+ current = [];
290
+ bytes = 0;
291
+ }
292
+ current.push(file);
293
+ bytes += size;
294
+ }
295
+ if (current.length)
296
+ batches.push(current);
297
+ const documents = [];
298
+ let failure;
299
+ for (const [index, batch] of batches.entries()) {
300
+ try {
301
+ const uploaded = await callStable(ctx, "POST", "/api/v1/knowledge-bases/{kb_id}/documents/upload", "document upload", {
302
+ params: { kb_id: [kb.id] },
303
+ files: batch.map((f) => ({ field: "files", path: f })),
304
+ timeoutMs: 300_000,
305
+ });
306
+ documents.push(...uploaded);
307
+ }
308
+ catch (error) {
309
+ if (!(error instanceof CavelonError) || documents.length === 0)
310
+ throw error;
311
+ failure = { error, notUploaded: batches.slice(index).flat().map((f) => path.relative(ctx.io.cwd, f) || f) };
312
+ break;
313
+ }
314
+ }
315
+ const operationIds = documents.map((d) => d.operation_id).filter((id) => Boolean(id));
316
+ const summary = {
317
+ kb: { id: kb.id, name: kb.name ?? null },
318
+ documents: documents.map((d) => ({ id: d.id, filename: d.filename, status: d.status, operation_id: d.operation_id ?? null })),
319
+ operation_ids: operationIds,
320
+ };
321
+ if (operationIds.length < documents.length)
322
+ ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
323
+ if (failure) {
324
+ return {
325
+ data: { ...summary, error: failure.error.toJSON(), not_uploaded: failure.notUploaded },
326
+ text: `Uploaded ${documents.length} files, then: ${failure.error.message}\n` +
327
+ `Not uploaded (${failure.notUploaded.length}): ${failure.notUploaded.join(", ")}\n` +
328
+ (operationIds.length ? `Wait for the uploaded ones with: cavelon wait ${operationIds.join(" ")}` : ""),
329
+ exitCode: failure.error.exitCode,
330
+ };
331
+ }
332
+ if (boolOption(input, "wait") && ctx.mode === "cli" && operationIds.length) {
333
+ const waited = await waitAndReport(ctx, operationIds, timeoutMs(ctx, stringOption(input, "timeout")));
334
+ return { data: { ...summary, ...waited.data }, text: `Uploaded ${documents.length} files.\n${waited.text}`, exitCode: waited.exitCode };
335
+ }
336
+ return {
337
+ data: summary,
338
+ text: `Uploaded ${documents.length} files to ${kb.name ?? kb.id}.` +
339
+ (operationIds.length ? `\nOperations: ${operationIds.length}\nWait with: cavelon wait ${operationIds.join(" ")}` : ""),
340
+ };
341
+ },
342
+ };
343
+ function summaryText(summary) {
344
+ return ["passed", "failed", "errors", "pass_rate"]
345
+ .filter((k) => k in summary)
346
+ .map((k) => k + " " + String(summary[k]))
347
+ .join(" ");
348
+ }
349
+ function resumeCommand(pending, timeout) {
350
+ return cavelonCommand("wait", ...pending, ...(timeout ? ["--timeout", timeout] : []));
351
+ }
352
+ export const testRun = {
353
+ name: "test run",
354
+ summary: "Start test-suite runs; returns operation ids.",
355
+ description: "Without --suite, runs every suite of the solution (--harness, or cavelon.yaml's harness).\n" +
356
+ "With --wait, exits 1 when a case failed, 5 when answers wait for a manual verdict.",
357
+ readOnly: false,
358
+ mcpTool: "test_run",
359
+ options: {
360
+ suite: { type: "string", multiple: true, value: "<suite>", description: "Suite name or id." },
361
+ harness: { type: "string", value: "<harness>", description: "Solution slug or id to run against." },
362
+ wait: WAIT_OPTION,
363
+ timeout: TIMEOUT_OPTION,
364
+ "idempotency-key": { type: "string", value: "<key>", description: "Send an Idempotency-Key with each start." },
365
+ },
366
+ examples: ["cavelon test run --suite smoke --wait --timeout 10m", "cavelon test run --harness support --json"],
367
+ async run(ctx, input) {
368
+ const session = await ctx.session();
369
+ const harnessRef = stringOption(input, "harness") ?? session.project?.harness;
370
+ const harnessId = harnessRef ? await resolveHarnessId(ctx, harnessRef) : undefined;
371
+ const suites = await callStable(ctx, "GET", "/api/v1/test-suites", "test suites", {
372
+ query: { harness_id: harnessId },
373
+ });
374
+ const wanted = listOption(input, "suite");
375
+ let chosen;
376
+ if (wanted.length) {
377
+ chosen = wanted.map((ref) => {
378
+ const hit = suites.find((s) => s.id === ref) ?? suites.filter((s) => s.name.toLowerCase() === ref.toLowerCase());
379
+ if (Array.isArray(hit)) {
380
+ if (hit.length === 1)
381
+ return hit[0];
382
+ throw new CavelonError(ExitCode.failure, {
383
+ code: hit.length ? "suite_ambiguous" : "suite_not_found",
384
+ message: hit.length ? `${hit.length} suites are named "${ref}"; pass its id.` : `No test suite "${ref}"${harnessRef ? ` for ${harnessRef}` : ""}.`,
385
+ hint: "`cavelon api list_suites` lists the suites.",
386
+ });
387
+ }
388
+ return hit;
389
+ });
390
+ }
391
+ else {
392
+ chosen = suites.filter((s) => !s.archived_at);
393
+ if (chosen.length === 0) {
394
+ throw new CavelonError(ExitCode.failure, {
395
+ code: "no_suites",
396
+ message: harnessRef ? `${harnessRef} has no test suites.` : "This tenant has no test suites.",
397
+ });
398
+ }
399
+ }
400
+ const key = stringOption(input, "idempotency-key");
401
+ const runs = [];
402
+ for (const suite of chosen) {
403
+ const body = {};
404
+ if (harnessId)
405
+ body.harness_id = harnessId;
406
+ runs.push(await callStable(ctx, "POST", "/api/v1/test-suites/{suite_id}/runs", "test runs", {
407
+ params: { suite_id: [suite.id] },
408
+ body,
409
+ headers: key ? { "Idempotency-Key": `${key}:${suite.id}` } : undefined,
410
+ }));
411
+ }
412
+ const operationIds = runs.map((r) => r.operation_id).filter((id) => Boolean(id));
413
+ const started = runs.map((r) => ({ run_id: r.id, suite: r.suite_name ?? r.suite_id, status: r.status, operation_id: r.operation_id ?? null }));
414
+ if (boolOption(input, "wait") && ctx.mode === "cli" && operationIds.length) {
415
+ const rawTimeout = stringOption(input, "timeout");
416
+ const waited = await waitAndReport(ctx, operationIds, timeoutMs(ctx, rawTimeout));
417
+ const results = [];
418
+ let failedCases = 0;
419
+ for (const run of runs) {
420
+ const latest = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}", "test runs", { params: { run_id: [run.id] } });
421
+ const { failed, errors } = caseCounts(latest.summary);
422
+ failedCases += failed + errors;
423
+ results.push({ run_id: latest.id, suite: latest.suite_name ?? latest.suite_id, status: latest.status, summary: latest.summary ?? {} });
424
+ }
425
+ let exitCode = waited.exitCode;
426
+ if (exitCode === ExitCode.ok && failedCases > 0)
427
+ exitCode = ExitCode.failure;
428
+ const resume = waited.pending.length ? resumeCommand(waited.pending, rawTimeout) : undefined;
429
+ const text = [
430
+ waited.body,
431
+ "",
432
+ ...results.map((r) => `${r.suite}: ${r.status} ${summaryText(r.summary)}`),
433
+ ...(resume ? ["", `${waited.why} after the timeout; the runs go on. Resume: ${resume}`] : []),
434
+ ].join("\n");
435
+ return { data: { runs: results, failed_cases: failedCases, ...waited.data, ...(resume ? { resume } : {}) }, text, exitCode };
436
+ }
437
+ return {
438
+ data: { runs: started, operation_ids: operationIds },
439
+ text: table(started, ["suite", "run_id", "status", "operation_id"]) +
440
+ (operationIds.length ? `\n\nWait with: cavelon wait ${operationIds.join(" ")}` : ""),
441
+ };
442
+ },
443
+ };
444
+ const KIND_ID = {
445
+ trigger: "a trigger run id (a test case's run_id)",
446
+ test: "a test run id (from `cavelon test run`)",
447
+ conversation: "a conversation id (a test case's conversation_id, or a trace's)",
448
+ };
449
+ function caseTraceCommand(r) {
450
+ if (r.conversation_id)
451
+ return { label: "by its conversation id", command: cavelonCommand("trace", r.conversation_id, "--kind", "conversation") };
452
+ if (r.agent_run_id)
453
+ return { label: "by its trigger run id", command: cavelonCommand("trace", r.agent_run_id, "--kind", "trigger") };
454
+ return undefined;
455
+ }
456
+ function spansCommand(owner, kind, traceId) {
457
+ return cavelonCommand("trace", owner, "--kind", kind, "--trace", traceId);
458
+ }
459
+ function traceNotFound(id, kind, traceId, error) {
460
+ const tried = kind ? `${kind === "trigger" ? "trigger run" : "conversation"} ${id}` : `trigger run or conversation ${id}`;
461
+ return new CavelonError(ExitCode.failure, {
462
+ code: "trace_not_found",
463
+ message: `No trace ${traceId} under ${tried} (${error.message}).`,
464
+ hint: "<run> must be the id the trace was listed under: a trigger run id with --kind trigger, or a conversation id with --kind conversation " +
465
+ "(a test case's traces are under its conversation_id; a test run id or an agent's run id does not work here). " +
466
+ `--trace takes a trace_id from that list. List them with: ${cavelonCommand("trace", id)}`,
467
+ });
468
+ }
469
+ function summarizeTrace(t) {
470
+ return {
471
+ trace_id: t.id,
472
+ workflow: t.workflow_name ?? null,
473
+ status: t.status,
474
+ duration_ms: t.duration_ms ?? null,
475
+ spans: t.total_spans ?? null,
476
+ llm_calls: t.total_llm_calls ?? null,
477
+ tool_calls: t.total_tool_calls ?? null,
478
+ tokens: (t.total_input_tokens ?? 0) + (t.total_output_tokens ?? 0),
479
+ error: t.error_summary ?? null,
480
+ conversation_id: t.conversation_id ?? null,
481
+ };
482
+ }
483
+ function summarizeSpan(s) {
484
+ const error = s.error_json ? clip(typeof s.error_json === "string" ? s.error_json : JSON.stringify(s.error_json), 200) : null;
485
+ return {
486
+ span_id: s.id,
487
+ seq: s.sequence ?? null,
488
+ type: s.span_type ?? null,
489
+ name: s.tool_name ?? s.name ?? null,
490
+ agent: s.agent_slug ?? null,
491
+ status: s.status ?? null,
492
+ duration_ms: s.duration_ms ?? null,
493
+ error,
494
+ };
495
+ }
496
+ function detailOf(value, full) {
497
+ if (full || value === null || value === undefined)
498
+ return value ?? null;
499
+ const text = typeof value === "string" ? value : JSON.stringify(value);
500
+ return text.length > 2000 ? clip(text, 2000) : value;
501
+ }
502
+ async function tryTraces(ctx, kind, id) {
503
+ const template = kind === "trigger" ? "/api/v1/triggers/runs/{run_id}/traces" : "/api/v1/conversations/{conversation_id}/traces";
504
+ const param = kind === "trigger" ? "run_id" : "conversation_id";
505
+ try {
506
+ return await callStable(ctx, "GET", template, "traces", { params: { [param]: [id] } });
507
+ }
508
+ catch (error) {
509
+ if (error instanceof CavelonError && (error.status === 404 || error.status === 422))
510
+ return undefined;
511
+ throw error;
512
+ }
513
+ }
514
+ const NOT_STARTED = new Set(["queued", "pending"]);
515
+ async function untracedRun(ctx, id) {
516
+ if (!isUuid(id))
517
+ return undefined;
518
+ let run;
519
+ try {
520
+ run = await callStable(ctx, "GET", "/api/v1/triggers/runs/{run_id}", "trigger runs", { params: { run_id: [id] } });
521
+ }
522
+ catch (error) {
523
+ if (error instanceof CavelonError && (error.status === 404 || error.status === 422))
524
+ return undefined;
525
+ throw error;
526
+ }
527
+ const note = await runCapacityNote(ctx, run);
528
+ const stages = NOT_STARTED.has(run.status) ? [] : await stageErrors(ctx, id);
529
+ return { run, note, stages };
530
+ }
531
+ function untracedText(id, untraced) {
532
+ const { run, note, stages } = untraced;
533
+ const why = [run.error_summary, ...stages.map(stageErrorText)].filter(Boolean).map((line) => `\n ${line}`);
534
+ return `Run ${id} is ${run.status} and has no traces${NOT_STARTED.has(run.status) || run.status === "running" ? " yet" : ""}.${noteLines(note)}${why.join("")}`;
535
+ }
536
+ async function capacityFooter(ctx, errors) {
537
+ const code = capacityCodeIn(...errors);
538
+ if (!code)
539
+ return "";
540
+ return `\n\n${code}: ${capacityHint(code, await readLimits(ctx).catch(() => undefined))}`;
541
+ }
542
+ function notPassedLines(r, max) {
543
+ const c = failedCase(r, max);
544
+ const lines = [` ${caseLabel(c)} ${c.status}`];
545
+ if (c.reason)
546
+ lines.push(` ${c.reason}`);
547
+ if (r.llm_judge_reasoning && r.llm_judge_reasoning !== r.error_message)
548
+ lines.push(` Judge: ${clip(r.llm_judge_reasoning, max)}`);
549
+ const open = caseTraceCommand(r);
550
+ if (open)
551
+ lines.push(` Its traces (${open.label}): ${open.command}`);
552
+ return lines;
553
+ }
554
+ function judgedLines(r, max) {
555
+ const score = r.llm_judge_score === null || r.llm_judge_score === undefined ? "" : ` score ${r.llm_judge_score}`;
556
+ return [` ${caseLabel(failedCase(r))} ${r.status}${score}`, ` Judge: ${clip(r.llm_judge_reasoning, max)}`];
557
+ }
558
+ async function testRunView(ctx, id, results, options) {
559
+ const max = options.full ? Number.MAX_SAFE_INTEGER : 1000;
560
+ const page = pageOf(results, options.limit, options.cursor);
561
+ const items = page.items.map((r) => ({
562
+ case: r.test_case_name ?? r.id,
563
+ step: r.step_order ?? null,
564
+ status: r.status,
565
+ score: r.llm_judge_score ?? null,
566
+ conversation_id: r.conversation_id ?? null,
567
+ run_id: r.agent_run_id ?? null,
568
+ error: r.error_message ? clip(r.error_message, 200) : null,
569
+ judge_reasoning: r.llm_judge_reasoning ? clip(r.llm_judge_reasoning, max) : null,
570
+ trace_command: caseTraceCommand(r)?.command ?? null,
571
+ ...(NOT_PASSED.has(r.status) ? { reason: failedCase(r, max).reason, judge_breakdown: detailOf(r.judge_breakdown, options.full) } : {}),
572
+ }));
573
+ const notPassed = page.items.filter((r) => NOT_PASSED.has(r.status));
574
+ const judged = page.items.filter((r) => !NOT_PASSED.has(r.status) && r.llm_judge_reasoning);
575
+ const byConversation = page.items.find((r) => r.conversation_id);
576
+ const byRun = page.items.find((r) => !r.conversation_id && r.agent_run_id);
577
+ const where = [
578
+ byConversation ? `A case's traces, by the conversation_id in its row: ${caseTraceCommand(byConversation).command}` : "",
579
+ byRun ? `A trigger case's traces, by the run_id in its row: ${caseTraceCommand(byRun).command}` : "",
580
+ ].filter(Boolean);
581
+ return {
582
+ data: { kind: "test", run_id: id, results: { ...page, items } },
583
+ text: table(items, ["case", "step", "status", "score", ...(items.some((r) => r.run_id) ? ["run_id"] : []), "conversation_id"]) +
584
+ moreHint(page.next_cursor, cavelonCommand("trace", id, "--kind", "test")) +
585
+ (notPassed.length ? `\n\nDid not pass:\n${notPassed.flatMap((r) => notPassedLines(r, max)).join("\n")}` : "") +
586
+ (judged.length ? `\n\nJudge's reasoning:\n${judged.flatMap((r) => judgedLines(r, options.full ? max : 300)).join("\n")}` : "") +
587
+ `\n\n${where.length ? where.join("\n") : "The instance recorded no conversation or run for these results, so they have no trace to open."}` +
588
+ (await capacityFooter(ctx, items.map((r) => r.error))),
589
+ };
590
+ }
591
+ export const trace = {
592
+ name: "trace",
593
+ summary: "Summarise the traces of a run, with a command for each span's detail.",
594
+ description: "<run> is a trigger run id, a test run id, a conversation id or an operation id (op_…).\n" +
595
+ "Without --trace: one line per trace (or per test result). With --trace: its spans. With --span: one span in full.",
596
+ readOnly: true,
597
+ idempotent: true,
598
+ mcpTool: "trace",
599
+ positionals: [{ name: "run", description: "Run, conversation or operation id.", required: true }],
600
+ options: {
601
+ kind: { type: "string", value: "<kind>", description: "trigger, test or conversation (default: found out)." },
602
+ trace: { type: "string", value: "<trace_id>", description: "Show this trace's spans." },
603
+ span: { type: "string", value: "<span_id>", description: "Show one span's input, output and error (needs --trace)." },
604
+ full: { type: "boolean", description: "Do not shorten span input and output." },
605
+ limit: LIMIT_OPTION,
606
+ cursor: CURSOR_OPTION,
607
+ },
608
+ examples: ["cavelon trace op_test_run_…", "cavelon trace <run> --trace <trace_id>", "cavelon trace <run> --trace <trace_id> --span <span_id>"],
609
+ async run(ctx, input) {
610
+ let id = positional(input, "run");
611
+ let kind = stringOption(input, "kind");
612
+ if (kind && !["trigger", "test", "conversation"].includes(kind))
613
+ throw usageError("--kind must be trigger, test or conversation.");
614
+ const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 20 });
615
+ const cursor = stringOption(input, "cursor");
616
+ if (id.startsWith("op_")) {
617
+ const op = await getOperation(await ctx.client(), id);
618
+ if (!op.result_ref)
619
+ throw new CavelonError(ExitCode.failure, { code: "no_result", message: `${id} has no result yet (${op.status}).` });
620
+ if (op.result_ref.type !== "test_run") {
621
+ throw new CavelonError(ExitCode.failure, {
622
+ code: "no_trace",
623
+ message: `${id} is a ${op.kind}; its result is a ${op.result_ref.type}, which has no trace.`,
624
+ });
625
+ }
626
+ id = op.result_ref.id;
627
+ kind = "test";
628
+ }
629
+ const traceId = stringOption(input, "trace");
630
+ const spanId = stringOption(input, "span");
631
+ if (spanId && !traceId)
632
+ throw usageError("--span needs --trace <trace_id>.");
633
+ if (traceId) {
634
+ const detailKind = kind ?? "trigger";
635
+ if (detailKind === "test")
636
+ throw usageError("A test run's traces belong to its conversations: pass --kind conversation <conversation_id>.");
637
+ const template = detailKind === "trigger" ? "/api/v1/triggers/runs/{run_id}/traces/{trace_id}" : "/api/v1/conversations/{conversation_id}/traces/{trace_id}";
638
+ const owner = detailKind === "trigger" ? "run_id" : "conversation_id";
639
+ const notFound = (error) => error instanceof CavelonError && (error.status === 404 || error.status === 422);
640
+ let detail;
641
+ try {
642
+ detail = await callStable(ctx, "GET", template, "traces", { params: { [owner]: [id], trace_id: [traceId] } });
643
+ }
644
+ catch (error) {
645
+ if (!notFound(error))
646
+ throw error;
647
+ if (kind)
648
+ throw traceNotFound(id, kind, traceId, error);
649
+ try {
650
+ detail = await callStable(ctx, "GET", "/api/v1/conversations/{conversation_id}/traces/{trace_id}", "traces", {
651
+ params: { conversation_id: [id], trace_id: [traceId] },
652
+ });
653
+ }
654
+ catch (second) {
655
+ throw notFound(second) ? traceNotFound(id, undefined, traceId, second) : second;
656
+ }
657
+ }
658
+ const spans = (detail.spans ?? []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
659
+ if (spanId) {
660
+ const span = spans.find((s) => s.id === spanId);
661
+ if (!span)
662
+ throw new CavelonError(ExitCode.failure, { code: "span_not_found", message: `No span ${spanId} in trace ${traceId}.` });
663
+ const full = boolOption(input, "full");
664
+ const data = {
665
+ ...summarizeSpan(span),
666
+ model: span.model ?? null,
667
+ parent_span_id: span.parent_span_id ?? null,
668
+ input: detailOf(span.input_json, full),
669
+ output: detailOf(span.output_json, full),
670
+ attributes: detailOf(span.attributes_json, full),
671
+ tokens: span.token_usage_json ?? null,
672
+ error: span.error_json ?? null,
673
+ };
674
+ return { data, text: JSON.stringify(data, null, 2) };
675
+ }
676
+ const page = pageOf(spans.map(summarizeSpan), limit, cursor);
677
+ const base = cavelonCommand("trace", id, ...(kind ? ["--kind", kind] : []), "--trace", traceId);
678
+ return {
679
+ data: { trace: summarizeTrace(detail), spans: page },
680
+ text: `${keyValues(Object.entries(summarizeTrace(detail)))}\n\n` +
681
+ table(page.items, ["seq", "type", "name", "status", "duration_ms", "span_id"]) +
682
+ moreHint(page.next_cursor, base) +
683
+ (page.items.length ? `\n\nOne span in full, by the span_id in its row: ${base} --span ${shellWord(page.items[0].span_id)}` : ""),
684
+ };
685
+ }
686
+ const order = kind ? [kind] : ["trigger", "test", "conversation"];
687
+ for (const candidate of order) {
688
+ if (candidate === "test") {
689
+ let results;
690
+ try {
691
+ results = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}/results", "test results", { params: { run_id: [id] } });
692
+ }
693
+ catch (error) {
694
+ if (!(error instanceof CavelonError && (error.status === 404 || error.status === 422)))
695
+ throw error;
696
+ }
697
+ if (!results || (!kind && results.length === 0))
698
+ continue;
699
+ return testRunView(ctx, id, results, { limit, cursor, full: boolOption(input, "full") });
700
+ }
701
+ const traces = await tryTraces(ctx, candidate, id);
702
+ if (candidate === "trigger" && !traces?.length) {
703
+ const untraced = await untracedRun(ctx, id);
704
+ if (untraced) {
705
+ const { run, note, stages } = untraced;
706
+ return {
707
+ data: {
708
+ kind: "trigger",
709
+ id,
710
+ run: { status: run.status, error: run.error_summary ?? null, ...note, ...(stages.length ? { stage_errors: stages } : {}) },
711
+ traces: { items: [], next_cursor: null },
712
+ },
713
+ text: untracedText(id, untraced),
714
+ };
715
+ }
716
+ }
717
+ if (!traces || (!kind && traces.length === 0))
718
+ continue;
719
+ const page = pageOf(traces.map((t) => ({ ...summarizeTrace(t), spans_command: spansCommand(id, candidate, t.id) })), limit, cursor);
720
+ return {
721
+ data: { kind: candidate, id, traces: page },
722
+ text: (table(page.items, ["trace_id", "workflow", "status", "duration_ms", "spans", "error"]) || "No traces recorded.") +
723
+ moreHint(page.next_cursor, cavelonCommand("trace", id, "--kind", candidate)) +
724
+ (page.items.length
725
+ ? `\n\nSpans of a trace, by the ${candidate === "trigger" ? "trigger run" : "conversation"} id and the trace_id in its row: ${page.items[0].spans_command}`
726
+ : "") +
727
+ (await capacityFooter(ctx, page.items.map((t) => t.error))),
728
+ };
729
+ }
730
+ if (kind) {
731
+ throw new CavelonError(ExitCode.failure, {
732
+ code: "run_not_found",
733
+ message: `No ${kind === "trigger" ? "trigger run" : kind === "test" ? "test run" : "conversation"} ${id} in this tenant.`,
734
+ hint: `--kind ${kind} takes ${KIND_ID[kind]}. Without --kind, \`${cavelonCommand("trace", id)}\` finds out what the id is.`,
735
+ });
736
+ }
737
+ throw new CavelonError(ExitCode.failure, {
738
+ code: "run_not_found",
739
+ message: `No trigger run, test run or conversation ${id} with results or traces in this tenant.`,
740
+ hint: `<run> takes ${KIND_ID.trigger}, ${KIND_ID.test} or ${KIND_ID.conversation}; a trace id goes after --trace. ` +
741
+ "Name the kind with --kind trigger|test|conversation to see an empty one.",
742
+ });
743
+ },
744
+ };