@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,243 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
3
+ import { usageError, validationError } from "../errors.js";
4
+ import { clip, moreHint, table } from "../format.js";
5
+ import { readAll } from "../io.js";
6
+ import { callOperation } from "../invoke.js";
7
+ import { describeSchema, findOperation, jsonBodySchema, operations, schemaTypes } from "../openapi.js";
8
+ import { cavelonCommand } from "../shell.js";
9
+ export function splitJsonBody(args) {
10
+ const out = [];
11
+ for (let i = 0; i < args.length; i++) {
12
+ const arg = args[i];
13
+ if (arg.startsWith("--json=")) {
14
+ out.push(`--body=${arg.slice("--json=".length)}`);
15
+ continue;
16
+ }
17
+ const next = args[i + 1];
18
+ if (arg === "--json" && next !== undefined && looksLikeBody(next)) {
19
+ out.push("--body", next);
20
+ i++;
21
+ continue;
22
+ }
23
+ out.push(arg);
24
+ }
25
+ return out;
26
+ }
27
+ function looksLikeBody(value) {
28
+ if (value === "-" || value.startsWith("@") || /^\s*[[{"]/.test(value))
29
+ return true;
30
+ try {
31
+ JSON.parse(value);
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ export async function readBody(ctx, raw) {
39
+ let text = raw;
40
+ if (raw === "-" && ctx.mode === "mcp") {
41
+ throw usageError("A body from standard input is not available over MCP; pass the JSON itself.");
42
+ }
43
+ if (raw === "-")
44
+ text = await readAll(ctx.io.stdin);
45
+ else if (raw.startsWith("@"))
46
+ text = await fs.readFile(raw.slice(1), "utf8");
47
+ try {
48
+ return JSON.parse(text);
49
+ }
50
+ catch (error) {
51
+ throw usageError(`The body is not JSON: ${error instanceof Error ? error.message : String(error)}`, "Pass --json '{\"key\": \"value\"}', @file.json or - for stdin.");
52
+ }
53
+ }
54
+ function parseParams(input) {
55
+ const params = {};
56
+ const pairs = [...listOption(input, "param"), ...(input.positionals.params ?? [])];
57
+ for (const pair of pairs) {
58
+ const at = pair.indexOf("=");
59
+ if (at <= 0)
60
+ throw usageError(`"${pair}" is not name=value.`, "Pass parameters as -p name=value.");
61
+ const name = pair.slice(0, at);
62
+ (params[name] ??= []).push(pair.slice(at + 1));
63
+ }
64
+ return params;
65
+ }
66
+ function truncate(data, limit) {
67
+ if (limit <= 0)
68
+ return { data };
69
+ if (Array.isArray(data) && data.length > limit)
70
+ return { data: data.slice(0, limit), total: data.length };
71
+ if (data && typeof data === "object" && Array.isArray(data.items)) {
72
+ const items = data.items;
73
+ if (items.length > limit)
74
+ return { data: { ...data, items: items.slice(0, limit) }, total: items.length };
75
+ }
76
+ return { data };
77
+ }
78
+ export const api = {
79
+ name: "api",
80
+ summary: "Call any operation the instance publishes in its OpenAPI.",
81
+ description: "The operation is its operationId or the short name before FastAPI's path suffix (list_harnesses).\n" +
82
+ "Parameters: -p name=value or name=value. Body: --json '<json>', --json @file.json or --json - (stdin).\n" +
83
+ "The body is checked against the operation's schema before it is sent.",
84
+ readOnly: false,
85
+ destructive: true,
86
+ mcpTool: "api",
87
+ positionals: [
88
+ { name: "operation", description: "operationId or its short name.", required: true },
89
+ { name: "params", description: "Parameters as name=value.", variadic: true },
90
+ ],
91
+ options: {
92
+ param: { type: "string", short: "p", multiple: true, value: "<name=value>", description: "A path, query or header parameter." },
93
+ body: { type: "string", value: "<json|@file|->", description: "The request body (also accepted as --json <body>)." },
94
+ file: { type: "string", multiple: true, value: "<field=path>", description: "Attach a file to a multipart body." },
95
+ output: { type: "string", value: "<file>", description: "Write the response body to a file instead of printing it.", cliOnly: true },
96
+ limit: { type: "string", value: "<n>", description: "Show at most n items of a list response (default 50, 0 for all)." },
97
+ },
98
+ examples: [
99
+ "cavelon api list_harnesses",
100
+ "cavelon api get_harness_by_slug slug=support",
101
+ "cavelon api create_knowledge_base --json '{\"name\": \"FAQ\"}'",
102
+ ],
103
+ preprocess: splitJsonBody,
104
+ async run(ctx, input) {
105
+ const name = positional(input, "operation");
106
+ const doc = await (await ctx.contracts()).openapi();
107
+ const op = findOperation(doc, name);
108
+ const args = { params: parseParams(input) };
109
+ const rawBody = stringOption(input, "body");
110
+ if (rawBody !== undefined)
111
+ args.body = await readBody(ctx, rawBody);
112
+ for (const spec of listOption(input, "file")) {
113
+ const at = spec.indexOf("=");
114
+ if (at <= 0)
115
+ throw usageError(`--file "${spec}" is not field=path.`);
116
+ args.files = [...(args.files ?? []), { field: spec.slice(0, at), path: spec.slice(at + 1) }];
117
+ }
118
+ const client = await ctx.client();
119
+ const result = await callOperation(ctx, client, doc, op, args);
120
+ const output = stringOption(input, "output");
121
+ if (output) {
122
+ const content = result.bytes ?? (typeof result.data === "string" ? result.data : JSON.stringify(result.data, null, 2));
123
+ await fs.writeFile(output, content);
124
+ const size = typeof content === "string" ? Buffer.byteLength(content) : content.length;
125
+ return { data: { status: result.status, written: output, bytes: size }, text: `Wrote ${size} bytes to ${output}.` };
126
+ }
127
+ if (result.bytes) {
128
+ throw validationError(`${op.alias} answered ${result.contentType} (${result.bytes.length} bytes).`, undefined, "Save it with --output <file>.");
129
+ }
130
+ const limit = intOption(input, "limit", { min: 0, fallback: 50 });
131
+ const { data, total } = truncate(result.data, limit);
132
+ if (total !== undefined)
133
+ ctx.warn(`Showing ${limit} of ${total} items; pass --limit 0 for all, or --output <file>.`);
134
+ const text = typeof data === "string" ? data : data === null ? `${result.status} (no content)` : JSON.stringify(data, null, 2);
135
+ return { data, text };
136
+ },
137
+ };
138
+ export const apiList = {
139
+ name: "api list",
140
+ summary: "List the operations the instance publishes.",
141
+ readOnly: true,
142
+ idempotent: true,
143
+ mcpTool: "api_list",
144
+ options: {
145
+ tag: { type: "string", value: "<tag>", description: "Only operations with this OpenAPI tag." },
146
+ search: { type: "string", value: "<text>", description: "Only operations whose name, path or summary contains the text." },
147
+ method: { type: "string", value: "<method>", description: "Only this HTTP method (GET, POST, …)." },
148
+ tags: { type: "boolean", description: "List the tags with their operation counts instead." },
149
+ limit: LIMIT_OPTION,
150
+ cursor: CURSOR_OPTION,
151
+ },
152
+ async run(ctx, input) {
153
+ const doc = await (await ctx.contracts()).openapi();
154
+ let ops = operations(doc);
155
+ if (input.options.tags === true) {
156
+ const counts = new Map();
157
+ for (const op of ops)
158
+ for (const tag of op.tags.length ? op.tags : ["(none)"])
159
+ counts.set(tag, (counts.get(tag) ?? 0) + 1);
160
+ const items = [...counts.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([tag, count]) => ({ tag, operations: count }));
161
+ return { data: { items }, text: table(items, ["tag", "operations"]) };
162
+ }
163
+ const tag = stringOption(input, "tag");
164
+ if (tag) {
165
+ ops = ops.filter((o) => o.tags.includes(tag));
166
+ if (ops.length === 0)
167
+ throw usageError(`No operations tagged "${tag}".`, "`cavelon api list --tags` shows the tags.");
168
+ }
169
+ const method = stringOption(input, "method")?.toUpperCase();
170
+ if (method)
171
+ ops = ops.filter((o) => o.method === method);
172
+ const search = stringOption(input, "search")?.toLowerCase();
173
+ if (search) {
174
+ ops = ops.filter((o) => [o.operationId, o.path, o.summary ?? ""].some((s) => s.toLowerCase().includes(search)));
175
+ }
176
+ const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
177
+ const page = pageOf(ops.map((o) => ({
178
+ operation: o.alias,
179
+ operation_id: o.operationId,
180
+ method: o.method,
181
+ path: o.path,
182
+ summary: o.summary ?? null,
183
+ tags: o.tags,
184
+ read_only: o.readOnly,
185
+ })), limit, stringOption(input, "cursor"));
186
+ const flags = [tag ? ["--tag", tag] : [], method ? ["--method", method] : [], search ? ["--search", search] : []].flat();
187
+ return {
188
+ data: page,
189
+ text: table(page.items, ["operation", "method", "path", "summary"]) +
190
+ `\n${page.items.length} of ${page.total}` +
191
+ moreHint(page.next_cursor, cavelonCommand("api", "list", ...flags)),
192
+ };
193
+ },
194
+ };
195
+ export const apiDescribe = {
196
+ name: "api describe",
197
+ summary: "Show one operation's parameters, body and responses.",
198
+ readOnly: true,
199
+ idempotent: true,
200
+ mcpTool: "api_describe",
201
+ positionals: [{ name: "operation", description: "operationId or its short name.", required: true }],
202
+ async run(ctx, input) {
203
+ const doc = await (await ctx.contracts()).openapi();
204
+ const op = findOperation(doc, positional(input, "operation"));
205
+ const bodyTypes = Object.keys(op.requestBody?.content ?? {});
206
+ const bodySchema = jsonBodySchema(op) ?? op.requestBody?.content?.[bodyTypes[0] ?? ""]?.schema;
207
+ const responses = Object.fromEntries(Object.entries(op.responses)
208
+ .filter(([code]) => code.startsWith("2"))
209
+ .map(([code, r]) => [code, describeSchema(doc, r.content?.["application/json"]?.schema)]));
210
+ const data = {
211
+ operation: op.alias,
212
+ operation_id: op.operationId,
213
+ method: op.method,
214
+ path: op.path,
215
+ read_only: op.readOnly,
216
+ tags: op.tags,
217
+ summary: op.summary ?? null,
218
+ description: op.description ? clip(op.description, 1500) : null,
219
+ parameters: op.parameters.map((p) => ({
220
+ name: p.name,
221
+ in: p.in,
222
+ required: Boolean(p.required),
223
+ type: schemaTypes(p.schema).filter((t) => t !== "null").join("|") || "string",
224
+ description: p.description ?? p.schema?.description ?? null,
225
+ })),
226
+ body: op.requestBody
227
+ ? { required: Boolean(op.requestBody.required), content_types: bodyTypes, schema: describeSchema(doc, bodySchema) }
228
+ : null,
229
+ responses,
230
+ };
231
+ const lines = [`${op.method} ${op.path} (${op.readOnly ? "read-only" : "changing"})`, op.summary ?? ""];
232
+ if (data.description && data.description !== op.summary)
233
+ lines.push("", data.description);
234
+ if (data.parameters.length) {
235
+ lines.push("", "Parameters:", table(data.parameters, ["name", "in", "required", "type", "description"]));
236
+ }
237
+ if (data.body)
238
+ lines.push("", `Body (${bodyTypes.join(", ")}${data.body.required ? ", required" : ""}):`, JSON.stringify(data.body.schema, null, 2));
239
+ if (Object.keys(responses).length)
240
+ lines.push("", "Responses:", JSON.stringify(responses, null, 2));
241
+ return { data, text: lines.join("\n") };
242
+ },
243
+ };
@@ -0,0 +1,207 @@
1
+ import { capacityNotes } from "../capacity.js";
2
+ import { stringOption, parseDuration } from "../command.js";
3
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
4
+ import { combinedExitCode, describe, exitCodeFor, getOperation, isSettled, TERMINAL, waitFor } from "../operations.js";
5
+ import { failureLines, resultFailure } from "../results.js";
6
+ import { readEvents } from "../sse.js";
7
+ export const DEFAULT_WAIT = "90s";
8
+ const MCP_TIMEOUT_MS = 0;
9
+ export const TIMEOUT_OPTION = {
10
+ type: "string",
11
+ value: "<duration>",
12
+ description: `Stop waiting after this long (90s, 5m; default ${DEFAULT_WAIT}). The work goes on; run wait again to resume.`,
13
+ };
14
+ export function timeoutMs(ctx, raw, fallback = DEFAULT_WAIT) {
15
+ if (ctx.mode === "mcp")
16
+ return MCP_TIMEOUT_MS;
17
+ return parseDuration(raw ?? fallback);
18
+ }
19
+ function intervalMs(ctx) {
20
+ const fromEnv = Number(ctx.io.env.CAVELON_POLL_INTERVAL_MS);
21
+ return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 1000;
22
+ }
23
+ export async function waitAndReport(ctx, ids, timeout) {
24
+ const client = await ctx.client();
25
+ const progress = !ctx.json && ctx.io.stderr.isTTY && ctx.mode === "cli";
26
+ const { operations, timedOut } = await waitFor(ctx, client, ids, {
27
+ timeoutMs: timeout,
28
+ intervalMs: intervalMs(ctx),
29
+ onChange: progress ? (op) => ctx.io.stderr.write(`${ctx.style.dim(describe(op).split("\n")[0])}\n`) : undefined,
30
+ });
31
+ const pending = operations.filter((o) => !isSettled(o)).map((o) => o.id);
32
+ const note = capacityNotes(ctx, client);
33
+ const notes = await Promise.all(operations.map(async (op) => withResult(await note(op), await resultFailure(ctx, op))));
34
+ const exitCode = combinedExitCode(operations, notes);
35
+ const waits = notes.flatMap((n, i) => (n?.capacity_wait ? [{ operation_id: operations[i].id, ...n.capacity_wait }] : []));
36
+ const refusals = notes.flatMap((n, i) => (n?.capacity_refusal ? [{ operation_id: operations[i].id, ...n.capacity_refusal }] : []));
37
+ const failedResults = notes.flatMap((n, i) => (n?.result_failure ? [{ operation_id: operations[i].id, ...n.result_failure }] : []));
38
+ const data = {
39
+ operations,
40
+ settled: pending.length === 0,
41
+ timed_out: timedOut,
42
+ ...(pending.length ? { resume: `cavelon wait ${pending.join(" ")}` } : {}),
43
+ ...(waits.length ? { capacity_waits: waits } : {}),
44
+ ...(refusals.length ? { capacity_refusals: refusals } : {}),
45
+ ...(failedResults.length ? { failed_results: failedResults } : {}),
46
+ };
47
+ const lines = operations.map((op, i) => describe(op, notes[i]));
48
+ const body = lines.join("\n");
49
+ const why = waits.length === pending.length ? "Waiting for run capacity" : "Still running";
50
+ if (pending.length) {
51
+ lines.push(timeout === 0 ? `${why}. Wait with: cavelon wait ${pending.join(" ")}` : `${why} after the timeout; resume with: cavelon wait ${pending.join(" ")}`);
52
+ }
53
+ return { data, text: lines.join("\n"), exitCode, body, pending, why };
54
+ }
55
+ function withResult(note, failure) {
56
+ return failure ? { ...note, result_failure: failure } : note;
57
+ }
58
+ export const wait = {
59
+ name: "wait",
60
+ summary: "Wait until operations finish, need a person, or the timeout passes.",
61
+ description: "Exit 0 when all succeeded, 1 when one failed or was cancelled, 5 when one needs a person,\n" +
62
+ "6 when the timeout passed first. A test run that finished with failed cases counts as failed, and its cases are named.\n" +
63
+ "The state is printed in every case, and a second `wait` resumes.",
64
+ readOnly: true,
65
+ idempotent: true,
66
+ mcpTool: "operation_status",
67
+ positionals: [{ name: "operation", description: "Operation ids (op_…).", required: true, variadic: true }],
68
+ options: {
69
+ timeout: TIMEOUT_OPTION,
70
+ },
71
+ examples: ["cavelon wait op_test_run_0f…", "cavelon wait op_a op_b --timeout 5m --json"],
72
+ async run(ctx, input) {
73
+ const ids = input.positionals.operation.filter(Boolean);
74
+ return waitAndReport(ctx, [...new Set(ids)], timeoutMs(ctx, stringOption(input, "timeout")));
75
+ },
76
+ };
77
+ export const watch = {
78
+ name: "watch",
79
+ summary: "Stream an operation's changes until it ends (server-sent events).",
80
+ description: "Prints one line per change (one JSON object per line with --json). A needs_action state is shown and the stream goes on.",
81
+ readOnly: true,
82
+ idempotent: true,
83
+ mcpTool: false,
84
+ positionals: [{ name: "operation", description: "Operation id (op_…).", required: true }],
85
+ options: {
86
+ timeout: { ...TIMEOUT_OPTION, description: "Stop watching after this long (default 10m)." },
87
+ },
88
+ async run(ctx, input) {
89
+ const id = input.positionals.operation;
90
+ if (!id)
91
+ throw usageError("Missing <operation>.");
92
+ const client = await ctx.client();
93
+ const deadline = Date.now() + timeoutMs(ctx, stringOption(input, "timeout"), "10m");
94
+ const note = capacityNotes(ctx, client);
95
+ const emit = async (op) => {
96
+ const extra = await note(op);
97
+ if (ctx.json)
98
+ ctx.io.stdout.write(`${JSON.stringify({ type: "operation", operation: op, ...extra })}\n`);
99
+ else
100
+ ctx.io.stdout.write(`${describe(op, extra)}\n`);
101
+ };
102
+ let last;
103
+ let fallback = false;
104
+ let failures = 0;
105
+ while (Date.now() < deadline) {
106
+ if (failures > 0) {
107
+ if (failures > 5) {
108
+ throw new CavelonError(ExitCode.server, {
109
+ code: "stream_error",
110
+ message: `The event stream of ${id} kept dropping.`,
111
+ hint: `\`cavelon wait ${id}\` polls instead.`,
112
+ });
113
+ }
114
+ await ctx.io.sleep(Math.min(1000 * 2 ** (failures - 1), 10_000, Math.max(0, deadline - Date.now())));
115
+ if (Date.now() >= deadline)
116
+ break;
117
+ }
118
+ if (fallback) {
119
+ const op = await getOperation(client, id);
120
+ if (!last || last.status !== op.status || last.progress?.current !== op.progress?.current)
121
+ await emit(op);
122
+ last = op;
123
+ if (TERMINAL.has(op.status))
124
+ break;
125
+ await ctx.io.sleep(Math.min(intervalMs(ctx) * 2, Math.max(0, deadline - Date.now())));
126
+ continue;
127
+ }
128
+ const controller = new AbortController();
129
+ const timer = setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
130
+ let reason;
131
+ let changes = 0;
132
+ try {
133
+ const response = await client.fetchRaw("GET", `/api/v1/operations/${encodeURIComponent(id)}/events`, {
134
+ accept: "text/event-stream",
135
+ signal: controller.signal,
136
+ });
137
+ if (response.status === 404 || response.status === 406 || !response.body) {
138
+ await response.body?.cancel();
139
+ last = await getOperation(client, id);
140
+ await emit(last);
141
+ if (TERMINAL.has(last.status))
142
+ break;
143
+ fallback = true;
144
+ continue;
145
+ }
146
+ if (!response.ok) {
147
+ throw await client.refusal(response.status, await response.text(), `GET /api/v1/operations/${id}/events`);
148
+ }
149
+ for await (const event of readEvents(response.body)) {
150
+ let frame;
151
+ try {
152
+ frame = JSON.parse(event.data);
153
+ }
154
+ catch {
155
+ continue;
156
+ }
157
+ if (frame.type === "end") {
158
+ reason = frame.reason;
159
+ break;
160
+ }
161
+ const op = (frame.operation ?? frame);
162
+ if (op?.id) {
163
+ last = op;
164
+ changes++;
165
+ await emit(op);
166
+ }
167
+ }
168
+ }
169
+ catch (error) {
170
+ if (controller.signal.aborted)
171
+ break;
172
+ if (error instanceof CavelonError && error.status !== undefined)
173
+ throw error;
174
+ failures++;
175
+ continue;
176
+ }
177
+ finally {
178
+ clearTimeout(timer);
179
+ }
180
+ if (reason === "terminal" || (last && TERMINAL.has(last.status)))
181
+ break;
182
+ if (reason === "gone") {
183
+ throw new CavelonError(ExitCode.failure, { code: "operation_gone", message: `Operation ${id} no longer exists.` });
184
+ }
185
+ if (reason === "error") {
186
+ throw new CavelonError(ExitCode.server, { code: "stream_error", message: `The instance ended the stream of ${id} with an error.` });
187
+ }
188
+ failures = reason === "lifetime" && changes > 0 ? 0 : failures + 1;
189
+ }
190
+ if (!last)
191
+ last = await getOperation(client, id);
192
+ const settled = TERMINAL.has(last.status);
193
+ const failure = settled ? await resultFailure(ctx, last) : undefined;
194
+ if (failure) {
195
+ if (ctx.json)
196
+ ctx.io.stdout.write(`${JSON.stringify({ type: "result", operation_id: id, result_failure: failure })}\n`);
197
+ else
198
+ ctx.io.stdout.write(`${failureLines(failure)}\n`);
199
+ }
200
+ if (!settled) {
201
+ const wait = (await note(last))?.capacity_wait;
202
+ ctx.io.stderr.write(`Stopped watching; ${id} is still ${last.status}. Resume: cavelon watch ${id}\n${wait ? ` ${wait.note}\n` : ""}`);
203
+ }
204
+ const unsettled = last.status === "needs_action" ? ExitCode.needsAction : ExitCode.timeout;
205
+ return { data: undefined, text: "", exitCode: settled ? exitCodeFor(last, { result_failure: failure }) : unsettled };
206
+ },
207
+ };
@@ -0,0 +1,158 @@
1
+ import { intOption, positional } from "../command.js";
2
+ import { CavelonError, ExitCode } from "../errors.js";
3
+ import { table } from "../format.js";
4
+ import { NOT_HERE } from "../http.js";
5
+ import { cavelonCommand } from "../shell.js";
6
+ const INDEX_PATHS = ["/llms.txt", "/api/v1/docs/llms.txt"];
7
+ function unavailable(url) {
8
+ return new CavelonError(ExitCode.failure, {
9
+ code: "docs_unavailable",
10
+ message: `${url} does not serve its docs to agents (no /llms.txt).`,
11
+ hint: "The instance is older than the docs endpoints; read the docs in the Admin until it is updated.",
12
+ });
13
+ }
14
+ function looksLikeIndex(text) {
15
+ return /^\s*#\s/.test(text) && !/^\s*<(!doctype|html)/i.test(text);
16
+ }
17
+ async function fetchIndex(client) {
18
+ for (const candidate of INDEX_PATHS) {
19
+ const response = await client.get(candidate, { accept: "text/plain, text/markdown", allow: NOT_HERE.filter((s) => s !== 401 && s !== 403) });
20
+ if (response.status === 200 && typeof response.data === "string" && looksLikeIndex(response.text))
21
+ return response.text;
22
+ }
23
+ throw unavailable(client.url);
24
+ }
25
+ export function parseIndex(text, base) {
26
+ const entries = [];
27
+ let section = "";
28
+ for (const line of text.split(/\r?\n/)) {
29
+ const heading = /^##\s+(.+?)\s*$/.exec(line);
30
+ if (heading) {
31
+ section = heading[1];
32
+ continue;
33
+ }
34
+ const link = /^\s*[-*]\s+\[([^\]]+)\]\(([^)\s]+)\)(?::\s*(.*))?$/.exec(line);
35
+ if (!link)
36
+ continue;
37
+ const pathname = new URL(link[2], `${base}/`).pathname;
38
+ const url = `${new URL(base).origin}${pathname}`;
39
+ const page = pathname.replace(/^.*?\/docs\//, "").replace(/^\//, "").replace(/\.md$/, "");
40
+ entries.push({ page, title: link[1], description: (link[3] ?? "").trim(), section, url });
41
+ }
42
+ return entries;
43
+ }
44
+ async function loadIndex(ctx) {
45
+ const client = await ctx.optionalClient();
46
+ let text;
47
+ if (client.target.token) {
48
+ text = await (await ctx.contracts()).text("llms.txt", () => fetchIndex(client));
49
+ }
50
+ else {
51
+ text = await fetchIndex(client);
52
+ }
53
+ return { client, entries: parseIndex(text, client.url) };
54
+ }
55
+ export async function listedPages(ctx, pages) {
56
+ try {
57
+ const { entries } = await loadIndex(ctx);
58
+ return pages.filter((page) => entries.some((e) => e.page === page));
59
+ }
60
+ catch {
61
+ return [];
62
+ }
63
+ }
64
+ function terms(query) {
65
+ return query
66
+ .toLowerCase()
67
+ .split(/[^\p{L}\p{N}_]+/u)
68
+ .filter((t) => t.length > 1);
69
+ }
70
+ export function searchIndex(entries, query) {
71
+ const words = terms(query);
72
+ const phrase = query.trim().toLowerCase();
73
+ return entries
74
+ .map((entry) => {
75
+ const title = entry.title.toLowerCase();
76
+ const description = entry.description.toLowerCase();
77
+ const page = entry.page.toLowerCase();
78
+ const section = entry.section.toLowerCase();
79
+ let score = 0;
80
+ if (phrase && title.includes(phrase))
81
+ score += 10;
82
+ if (phrase && description.includes(phrase))
83
+ score += 4;
84
+ for (const word of words) {
85
+ if (title.includes(word))
86
+ score += 3;
87
+ if (page.includes(word))
88
+ score += 2;
89
+ if (description.includes(word))
90
+ score += 1;
91
+ if (section.includes(word))
92
+ score += 1;
93
+ }
94
+ return { ...entry, score };
95
+ })
96
+ .filter((e) => e.score > 0)
97
+ .sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));
98
+ }
99
+ export const docsSearch = {
100
+ name: "docs search",
101
+ summary: "Search this instance's docs (titles and summaries).",
102
+ readOnly: true,
103
+ idempotent: true,
104
+ mcpTool: "docs_search",
105
+ positionals: [{ name: "query", description: "What to look for.", required: true, variadic: true }],
106
+ options: { limit: { type: "string", value: "<n>", description: "Return at most n pages (default 10)." } },
107
+ async run(ctx, input) {
108
+ const query = (input.positionals.query ?? []).join(" ");
109
+ const limit = intOption(input, "limit", { min: 1, max: 100, fallback: 10 });
110
+ const { entries } = await loadIndex(ctx);
111
+ const hits = searchIndex(entries, query);
112
+ const items = hits.slice(0, limit).map(({ page, title, description, section }) => ({ page, title, section, description }));
113
+ return {
114
+ data: { query, items, total: hits.length },
115
+ text: items.length
116
+ ? `${table(items, ["page", "title", "description"], 70)}\n\nRead one: cavelon docs get <page>`
117
+ : `No page matches "${query}". The index has ${entries.length} pages.`,
118
+ };
119
+ },
120
+ };
121
+ export const docsGet = {
122
+ name: "docs get",
123
+ summary: "Print one docs page as markdown.",
124
+ readOnly: true,
125
+ idempotent: true,
126
+ mcpTool: "docs_get",
127
+ positionals: [{ name: "page", description: "section/slug from `docs search`, a title, or the page URL.", required: true }],
128
+ options: {
129
+ "max-chars": { type: "string", value: "<n>", description: "Print at most n characters (default 40000)." },
130
+ cursor: { type: "string", value: "<offset>", description: "Continue a long page where the previous output stopped." },
131
+ },
132
+ async run(ctx, input) {
133
+ const ref = positional(input, "page");
134
+ const { client, entries } = await loadIndex(ctx);
135
+ const wanted = ref.replace(/\.md$/, "").replace(/^\/+/, "");
136
+ const entry = entries.find((e) => e.page === wanted || e.url === ref) ??
137
+ entries.find((e) => e.title.toLowerCase() === ref.toLowerCase()) ??
138
+ entries.find((e) => e.page.endsWith(`/${wanted}`));
139
+ if (!entry) {
140
+ const near = searchIndex(entries, ref.replace(/[/-]/g, " ")).slice(0, 5).map((e) => e.page);
141
+ throw new CavelonError(ExitCode.failure, {
142
+ code: "doc_not_found",
143
+ message: `No docs page "${ref}" on this instance.`,
144
+ hint: near.length ? `Did you mean: ${near.join(", ")}?` : "Find it with `cavelon docs search <words>`.",
145
+ });
146
+ }
147
+ const response = await client.get(entry.url, { accept: "text/markdown, text/plain" });
148
+ const markdown = response.text;
149
+ const max = intOption(input, "max-chars", { min: 100, fallback: 40_000 });
150
+ const offset = intOption(input, "cursor", { min: 0, fallback: 0 });
151
+ const chunk = markdown.slice(offset, offset + max);
152
+ const next = offset + max < markdown.length ? String(offset + max) : null;
153
+ return {
154
+ data: { page: entry.page, title: entry.title, url: entry.url, markdown: chunk, next_cursor: next, length: markdown.length },
155
+ text: chunk + (next ? `\n\n… page continues: ${cavelonCommand("docs", "get", entry.page, "--cursor", next)}` : ""),
156
+ };
157
+ },
158
+ };