@cavelon/cli 0.0.0 → 0.1.2
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.
- package/README.md +713 -3
- package/dist/LICENSE +201 -0
- package/dist/agents.js +107 -0
- package/dist/branches.js +61 -0
- package/dist/capacity.js +162 -0
- package/dist/cli.js +4 -0
- package/dist/command.js +62 -0
- package/dist/commands/api.js +313 -0
- package/dist/commands/async.js +207 -0
- package/dist/commands/docs.js +158 -0
- package/dist/commands/index.js +112 -0
- package/dist/commands/init.js +481 -0
- package/dist/commands/inventory.js +56 -0
- package/dist/commands/limits-set.js +633 -0
- package/dist/commands/limits.js +156 -0
- package/dist/commands/loops.js +798 -0
- package/dist/commands/models.js +197 -0
- package/dist/commands/sandboxes.js +674 -0
- package/dist/commands/session.js +480 -0
- package/dist/commands/solution.js +830 -0
- package/dist/commands/tenants.js +266 -0
- package/dist/commands/values.js +386 -0
- package/dist/commands/work.js +761 -0
- package/dist/context.js +60 -0
- package/dist/contracts.js +234 -0
- package/dist/credentials.js +134 -0
- package/dist/errors.js +64 -0
- package/dist/features.js +52 -0
- package/dist/format.js +36 -0
- package/dist/fsutil.js +43 -0
- package/dist/git.js +41 -0
- package/dist/http.js +304 -0
- package/dist/invoke.js +165 -0
- package/dist/io.js +49 -0
- package/dist/limits.js +307 -0
- package/dist/local-state.js +78 -0
- package/dist/main.js +227 -0
- package/dist/markers.js +113 -0
- package/dist/mcp.js +137 -0
- package/dist/openapi.js +233 -0
- package/dist/operations.js +107 -0
- package/dist/package-check.js +342 -0
- package/dist/package-files.js +394 -0
- package/dist/pair-order.js +39 -0
- package/dist/paths.js +77 -0
- package/dist/principal.js +33 -0
- package/dist/project.js +157 -0
- package/dist/prompt.js +34 -0
- package/dist/results.js +104 -0
- package/dist/session.js +190 -0
- package/dist/shell.js +41 -0
- package/dist/skills/cavelon-authoring/SKILL.md +224 -0
- package/dist/skills/cavelon-long-running/SKILL.md +185 -0
- package/dist/skills/cavelon-loop/SKILL.md +159 -0
- package/dist/skills/cavelon-testing/SKILL.md +97 -0
- package/dist/sse.js +44 -0
- package/dist/tar.js +172 -0
- package/dist/user-config.js +36 -0
- package/dist/version.js +17 -0
- package/dist/zip.js +132 -0
- package/package.json +40 -4
|
@@ -0,0 +1,798 @@
|
|
|
1
|
+
import { noteLines, runCapacityNote } from "../capacity.js";
|
|
2
|
+
import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, positional, stringOption, } from "../command.js";
|
|
3
|
+
import { CavelonError, ExitCode, usageError } from "../errors.js";
|
|
4
|
+
import { idempotencyKey, requireFeature, UUID_KEY_OPTION, withRetryKey } from "../features.js";
|
|
5
|
+
import { clip, keyValues, moreHint, table } from "../format.js";
|
|
6
|
+
import { callStable } from "../invoke.js";
|
|
7
|
+
import { catalogEntry } from "../package-check.js";
|
|
8
|
+
import { readPrincipal } from "../principal.js";
|
|
9
|
+
import { isUuid } from "../session.js";
|
|
10
|
+
import { cavelonCommand } from "../shell.js";
|
|
11
|
+
import { readBody } from "./api.js";
|
|
12
|
+
import { TIMEOUT_OPTION, timeoutMs, waitAndReport } from "./async.js";
|
|
13
|
+
import { catalogFor } from "./solution.js";
|
|
14
|
+
const WAIT_OPTION = { type: "boolean", description: "Wait for the run to finish (see `cavelon wait`).", cliOnly: true };
|
|
15
|
+
const LOOP_OPTION = { type: "string", value: "<loop_id>", description: "The loop, when the run has more than one." };
|
|
16
|
+
const MAX_ITERATION_CURSOR = 100;
|
|
17
|
+
const LOOP_TERMINAL = new Set(["completed", "failed", "cancelled", "stopped"]);
|
|
18
|
+
const LOOP_SETTLED = new Set([...LOOP_TERMINAL, "paused"]);
|
|
19
|
+
const RUN_TERMINAL = new Set(["completed", "failed", "blocked", "rejected", "skipped_budget", "expired", "cancelled", "debug_stopped"]);
|
|
20
|
+
export async function resolveTrigger(ctx, ref) {
|
|
21
|
+
if (isUuid(ref)) {
|
|
22
|
+
return callStable(ctx, "GET", "/api/v1/triggers/{trigger_id}", "triggers", { params: { trigger_id: [ref] } });
|
|
23
|
+
}
|
|
24
|
+
const triggers = await callStable(ctx, "GET", "/api/v1/triggers", "triggers");
|
|
25
|
+
let hits = triggers.filter((t) => t.slug === ref);
|
|
26
|
+
if (hits.length === 0)
|
|
27
|
+
hits = triggers.filter((t) => t.name.toLowerCase() === ref.toLowerCase());
|
|
28
|
+
if (hits.length === 1)
|
|
29
|
+
return hits[0];
|
|
30
|
+
throw new CavelonError(ExitCode.failure, {
|
|
31
|
+
code: hits.length ? "trigger_ambiguous" : "trigger_not_found",
|
|
32
|
+
message: hits.length ? `${hits.length} triggers are named "${ref}"; pass its id.` : `No trigger "${ref}" in this tenant.`,
|
|
33
|
+
hint: "`cavelon api list_triggers` lists them with their ids and slugs.",
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
async function getRun(ctx, runId) {
|
|
37
|
+
if (!isUuid(runId))
|
|
38
|
+
throw usageError(`"${runId}" is not a run id.`, "`cavelon loop start` prints the run id.");
|
|
39
|
+
return callStable(ctx, "GET", "/api/v1/triggers/runs/{run_id}", "trigger runs", { params: { run_id: [runId] } });
|
|
40
|
+
}
|
|
41
|
+
const MAX_LOOP_PAGES = 5;
|
|
42
|
+
async function loopsOf(ctx, runId) {
|
|
43
|
+
const loops = [];
|
|
44
|
+
let cursor;
|
|
45
|
+
for (let page = 0; page < MAX_LOOP_PAGES; page++) {
|
|
46
|
+
const result = await callStable(ctx, "GET", "/api/v1/triggers/runs/{run_id}/loops", "loops", {
|
|
47
|
+
params: { run_id: [runId] },
|
|
48
|
+
query: { limit: 20, cursor },
|
|
49
|
+
});
|
|
50
|
+
loops.push(...result.items);
|
|
51
|
+
if (!result.next_cursor)
|
|
52
|
+
break;
|
|
53
|
+
cursor = result.next_cursor;
|
|
54
|
+
}
|
|
55
|
+
return loops;
|
|
56
|
+
}
|
|
57
|
+
async function getLoop(ctx, runId, loopId) {
|
|
58
|
+
return callStable(ctx, "GET", "/api/v1/triggers/runs/{run_id}/loops/{loop_id}", "loops", {
|
|
59
|
+
params: { run_id: [runId], loop_id: [loopId] },
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function currentLoop(loops) {
|
|
63
|
+
return [...loops].reverse().find((l) => !LOOP_TERMINAL.has(l.state)) ?? loops.at(-1);
|
|
64
|
+
}
|
|
65
|
+
async function pickLoop(ctx, runId, loopId, fits, what) {
|
|
66
|
+
if (loopId)
|
|
67
|
+
return getLoop(ctx, runId, loopId);
|
|
68
|
+
const loops = await loopsOf(ctx, runId);
|
|
69
|
+
if (loops.length === 0) {
|
|
70
|
+
throw new CavelonError(ExitCode.failure, {
|
|
71
|
+
code: "loop_not_found",
|
|
72
|
+
message: `Run ${runId} has no loop (yet).`,
|
|
73
|
+
hint: `A loop starts when the run reaches its Masterloop node; \`cavelon loop watch ${runId}\` waits for it.`,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const candidates = loops.filter(fits);
|
|
77
|
+
if (candidates.length === 1)
|
|
78
|
+
return candidates[0];
|
|
79
|
+
if (candidates.length === 0) {
|
|
80
|
+
throw new CavelonError(ExitCode.conflict, {
|
|
81
|
+
code: "loop_state_conflict",
|
|
82
|
+
message: `No loop of run ${runId} ${what}: ${loops.map((l) => l.id + " is " + l.state).join(", ")}.`,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
throw usageError(`Run ${runId} has ${candidates.length} loops that ${what}; name one with --loop.`, `Loops: ${candidates.map((l) => l.id).join(", ")}`);
|
|
86
|
+
}
|
|
87
|
+
function loopSummary(loop) {
|
|
88
|
+
return {
|
|
89
|
+
loop_id: loop.id,
|
|
90
|
+
run_id: loop.owner_run_id,
|
|
91
|
+
node: loop.node_name ?? loop.node_ref,
|
|
92
|
+
state: loop.state,
|
|
93
|
+
reason: loop.reason ?? loop.blocked_reason ?? null,
|
|
94
|
+
iteration: loop.iteration_number,
|
|
95
|
+
max_iterations: loop.limits.max_iterations ?? null,
|
|
96
|
+
usage: loop.charged_usage,
|
|
97
|
+
deadline_at: loop.deadline_at,
|
|
98
|
+
sandbox_id: loop.sandbox_id,
|
|
99
|
+
pause_requested: loop.pause_requested,
|
|
100
|
+
progress: loop.progress_summary ?? null,
|
|
101
|
+
operation_id: loop.operation_id,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function runSummary(run, note) {
|
|
105
|
+
return {
|
|
106
|
+
run_id: run.id,
|
|
107
|
+
workflow: run.workflow_name,
|
|
108
|
+
status: run.status,
|
|
109
|
+
error: run.error_summary ?? null,
|
|
110
|
+
acting_as: run.acting_as ? (run.acting_as.name ?? run.acting_as.key_prefix ?? run.acting_as.kind) : null,
|
|
111
|
+
operation_id: run.operation_id ?? null,
|
|
112
|
+
...note,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function verdictOf(it, decided) {
|
|
116
|
+
if (it.accepted_at !== null)
|
|
117
|
+
return "accepted";
|
|
118
|
+
if (it.ended_at === null)
|
|
119
|
+
return "running";
|
|
120
|
+
if (!decided)
|
|
121
|
+
return "ended";
|
|
122
|
+
return it.child_status === "completed" ? "rejected" : "failed";
|
|
123
|
+
}
|
|
124
|
+
function iterationEnvelope(it, decided, context) {
|
|
125
|
+
const result = it.accepted_result;
|
|
126
|
+
let shown = result;
|
|
127
|
+
if (result) {
|
|
128
|
+
const text = JSON.stringify(result);
|
|
129
|
+
if (text.length > 2000)
|
|
130
|
+
shown = clip(text, 2000);
|
|
131
|
+
}
|
|
132
|
+
const verdict = verdictOf(it, decided);
|
|
133
|
+
const notAccepted = verdict === "rejected" || verdict === "failed";
|
|
134
|
+
return {
|
|
135
|
+
iteration: it.iteration_number,
|
|
136
|
+
child_run_id: it.child_run_id,
|
|
137
|
+
child_status: it.child_status,
|
|
138
|
+
verdict,
|
|
139
|
+
accepted: it.accepted_at !== null,
|
|
140
|
+
outcome: result && typeof result.outcome === "string" ? result.outcome : null,
|
|
141
|
+
reason: notAccepted && context ? [context.reason, context.blocked_reason].filter(Boolean).join(": ") || null : null,
|
|
142
|
+
duration_ms: it.duration_ms,
|
|
143
|
+
usage: it.actual_usage,
|
|
144
|
+
reserved_usage: it.reserved_usage,
|
|
145
|
+
result: shown,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
const tokens = (usage) => usage.input_tokens + usage.output_tokens;
|
|
149
|
+
function iterationLine(env) {
|
|
150
|
+
const child = env.child_status === "completed" ? "" : ` (child ${env.child_status})`;
|
|
151
|
+
const usage = env.usage
|
|
152
|
+
? `requests ${env.usage.model_requests} tokens ${tokens(env.usage)}`
|
|
153
|
+
: `usage not reported yet; reserved requests ${env.reserved_usage.model_requests}, tokens ${tokens(env.reserved_usage)}`;
|
|
154
|
+
const outcome = env.outcome ? " → " + env.outcome : "";
|
|
155
|
+
const reason = env.reason ? " (" + env.reason + ")" : "";
|
|
156
|
+
return `iteration ${env.iteration} ${env.verdict}${child}${outcome} ${env.duration_ms ?? "-"} ms ${usage}${reason}`;
|
|
157
|
+
}
|
|
158
|
+
function usageText(usage) {
|
|
159
|
+
return `requests ${usage.model_requests}, tokens in ${usage.input_tokens}, out ${usage.output_tokens}`;
|
|
160
|
+
}
|
|
161
|
+
function loopExitCode(state) {
|
|
162
|
+
if (state === "completed")
|
|
163
|
+
return ExitCode.ok;
|
|
164
|
+
if (state === "failed" || state === "cancelled" || state === "stopped")
|
|
165
|
+
return ExitCode.failure;
|
|
166
|
+
if (state === "paused")
|
|
167
|
+
return ExitCode.needsAction;
|
|
168
|
+
return ExitCode.timeout;
|
|
169
|
+
}
|
|
170
|
+
export const loopStart = {
|
|
171
|
+
name: "loop start",
|
|
172
|
+
summary: "Start a loop through its trigger, as you; returns the run and operation ids.",
|
|
173
|
+
description: "Calls the trigger's run-now route. The run (and its loop) acts as the caller: with a personal access token, the person.\n" +
|
|
174
|
+
"Follow it with `loop watch <run>`, or `wait <operation>`; `loop cancel <run>` stops it.",
|
|
175
|
+
readOnly: false,
|
|
176
|
+
mcpTool: "loop_start",
|
|
177
|
+
positionals: [{ name: "trigger", description: "Trigger slug, name or id.", required: true }],
|
|
178
|
+
options: {
|
|
179
|
+
input: { type: "string", value: "<json|@file|->", description: "The run's payload: JSON, @file.json or - for stdin." },
|
|
180
|
+
wait: WAIT_OPTION,
|
|
181
|
+
timeout: TIMEOUT_OPTION,
|
|
182
|
+
"idempotency-key": UUID_KEY_OPTION,
|
|
183
|
+
},
|
|
184
|
+
examples: ["cavelon loop start counter", "cavelon loop start orders --input @orders-request.json --json"],
|
|
185
|
+
async run(ctx, input) {
|
|
186
|
+
await requireFeature(ctx, "masterloop_enabled", "masterloop_feature_disabled", "Masterloop");
|
|
187
|
+
const trigger = await resolveTrigger(ctx, positional(input, "trigger"));
|
|
188
|
+
const raw = stringOption(input, "input");
|
|
189
|
+
const payload = raw === undefined ? {} : await readBody(ctx, raw);
|
|
190
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
191
|
+
throw usageError("--input must be a JSON object.");
|
|
192
|
+
const key = idempotencyKey(input);
|
|
193
|
+
const run = await callStable(ctx, "POST", "/api/v1/triggers/{trigger_id}/run", "starting triggers", {
|
|
194
|
+
params: { trigger_id: [trigger.id] },
|
|
195
|
+
headers: { "Idempotency-Key": key },
|
|
196
|
+
body: { payload },
|
|
197
|
+
}).catch((error) => {
|
|
198
|
+
throw withRetryKey(error, key);
|
|
199
|
+
});
|
|
200
|
+
if (!trigger.is_active)
|
|
201
|
+
ctx.warn(`Trigger "${trigger.slug}" is not active: its schedule and webhook start no runs, though this manual start did.`);
|
|
202
|
+
const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run), idempotency_key: key };
|
|
203
|
+
if (boolOption(input, "wait") && ctx.mode === "cli" && run.operation_id) {
|
|
204
|
+
const waited = await waitAndReport(ctx, [run.operation_id], timeoutMs(ctx, stringOption(input, "timeout")));
|
|
205
|
+
const text = `Started run ${run.id} of ${trigger.slug}.\n${waited.text}`;
|
|
206
|
+
const missing = await endedWithoutLoop(ctx, run.id);
|
|
207
|
+
if (missing) {
|
|
208
|
+
return {
|
|
209
|
+
data: { ...started, ...waited.data, without_loop: missing },
|
|
210
|
+
text: `${text}\nThe run ended (${missing.status}) without a loop.${missing.why ? " " + missing.why : ""}\nLook closer: ${cavelonCommand("trace", run.id)}`,
|
|
211
|
+
exitCode: waited.exitCode === ExitCode.ok ? ExitCode.failure : waited.exitCode,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
return { data: { ...started, ...waited.data }, text, exitCode: waited.exitCode };
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
data: started,
|
|
218
|
+
text: `Started run ${run.id} of ${trigger.slug} (${run.status}).\n` +
|
|
219
|
+
`Follow: cavelon loop watch ${run.id}\n` +
|
|
220
|
+
(run.operation_id ? `Wait: cavelon wait ${run.operation_id}\n` : "") +
|
|
221
|
+
`Stop: cavelon loop cancel ${run.id} --confirm`,
|
|
222
|
+
};
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
export const loopCancel = {
|
|
226
|
+
name: "loop cancel",
|
|
227
|
+
summary: "Stop a trigger run and its loops (needs --confirm).",
|
|
228
|
+
description: "Without --confirm, shows what would stop and stops nothing. Stopping the run stops every loop of it.",
|
|
229
|
+
readOnly: false,
|
|
230
|
+
destructive: true,
|
|
231
|
+
idempotent: true,
|
|
232
|
+
mcpTool: "loop_cancel",
|
|
233
|
+
positionals: [{ name: "run", description: "The trigger run id (from `loop start`).", required: true }],
|
|
234
|
+
options: {
|
|
235
|
+
confirm: { type: "boolean", description: "Stop the run; without it nothing is stopped." },
|
|
236
|
+
},
|
|
237
|
+
examples: ["cavelon loop cancel <run>", "cavelon loop cancel <run> --confirm"],
|
|
238
|
+
async run(ctx, input) {
|
|
239
|
+
const runId = positional(input, "run");
|
|
240
|
+
const run = await getRun(ctx, runId);
|
|
241
|
+
const note = await runCapacityNote(ctx, run);
|
|
242
|
+
if (RUN_TERMINAL.has(run.status)) {
|
|
243
|
+
return { data: { cancelled: false, run: runSummary(run, note) }, text: `Run ${run.id} is already ${run.status}; nothing to stop.${noteLines(note)}` };
|
|
244
|
+
}
|
|
245
|
+
const loops = (await loopsOf(ctx, run.id)).map(loopSummary);
|
|
246
|
+
if (!boolOption(input, "confirm")) {
|
|
247
|
+
const confirm = `cavelon loop cancel ${run.id} --confirm`;
|
|
248
|
+
return {
|
|
249
|
+
data: { cancelled: false, run: runSummary(run, note), loops, confirm },
|
|
250
|
+
text: `Run ${run.id} (${run.workflow_name}) is ${run.status}` +
|
|
251
|
+
(loops.length ? `, with loops:\n${table(loops, ["loop_id", "node", "state", "iteration"])}\n` : ".\n") +
|
|
252
|
+
(note ? `${noteLines(note).slice(1)}\n` : "") +
|
|
253
|
+
`Nothing was stopped. Stop it with: ${confirm}`,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
const cancelled = await callStable(ctx, "POST", "/api/v1/triggers/runs/{run_id}/cancel", "cancelling runs", { params: { run_id: [run.id] } });
|
|
257
|
+
return {
|
|
258
|
+
data: { cancelled: true, run: runSummary(cancelled), loops },
|
|
259
|
+
text: `Run ${cancelled.id} is ${cancelled.status}; its loops stop at their next safe point.` + (cancelled.operation_id ? `\nWait: cavelon wait ${cancelled.operation_id}` : ""),
|
|
260
|
+
};
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
export const loopIterations = {
|
|
264
|
+
name: "loop iterations",
|
|
265
|
+
summary: "A loop's state, budget and iterations, a page at a time.",
|
|
266
|
+
description: "Each iteration's verdict: accepted, rejected or failed (the child failed), ended (not yet accepted) or running;\n" +
|
|
267
|
+
"the outcome of its accepted result (continue, wait, done, blocked), and its usage once the instance reports it.",
|
|
268
|
+
readOnly: true,
|
|
269
|
+
idempotent: true,
|
|
270
|
+
mcpTool: "loop_iterations",
|
|
271
|
+
positionals: [{ name: "run", description: "The trigger run id.", required: true }],
|
|
272
|
+
options: {
|
|
273
|
+
loop: LOOP_OPTION,
|
|
274
|
+
limit: { ...LIMIT_OPTION, description: "Return at most n iterations (at most 20)." },
|
|
275
|
+
cursor: CURSOR_OPTION,
|
|
276
|
+
},
|
|
277
|
+
examples: ["cavelon loop iterations <run>", "cavelon loop iterations <run> --cursor 20 --json"],
|
|
278
|
+
async run(ctx, input) {
|
|
279
|
+
const runId = positional(input, "run");
|
|
280
|
+
const limit = intOption(input, "limit", { min: 1, max: 20, fallback: 20 });
|
|
281
|
+
const cursor = intOption(input, "cursor", { min: 0 });
|
|
282
|
+
const loopId = stringOption(input, "loop");
|
|
283
|
+
const loop = loopId ? await getLoop(ctx, runId, loopId) : currentLoop(await loopsOf(ctx, runId));
|
|
284
|
+
if (!loop)
|
|
285
|
+
throw new CavelonError(ExitCode.failure, { code: "loop_not_found", message: `Run ${runId} has no loop (yet).` });
|
|
286
|
+
const page = await iterationPage(ctx, loop, limit, cursor ?? 0);
|
|
287
|
+
const newest = newestIteration(loop, page.items);
|
|
288
|
+
const items = page.items.map((it) => envelopeIn(it, loop, newest));
|
|
289
|
+
const next = page.next_cursor === null ? null : String(page.next_cursor);
|
|
290
|
+
const summary = loopSummary(loop);
|
|
291
|
+
return {
|
|
292
|
+
data: { loop: summary, iterations: { items, next_cursor: next }, content_visible: page.content_visible },
|
|
293
|
+
text: `${keyValues(Object.entries({ ...summary, usage: usageText(summary.usage) }))}\n\n` +
|
|
294
|
+
(table(items, ["iteration", "child_status", "verdict", "outcome", "duration_ms", "child_run_id"]) || "No iterations yet.") +
|
|
295
|
+
moreHint(next, cavelonCommand("loop", "iterations", loop.owner_run_id, "--loop", loop.id)) +
|
|
296
|
+
(page.content_visible ? "" : "\nIteration results are hidden from this credential.") +
|
|
297
|
+
(items.length ? `\nOne iteration's run: ${cavelonCommand("trace")} <child_run_id>` : ""),
|
|
298
|
+
};
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
function iterationPage(ctx, loop, limit, cursor) {
|
|
302
|
+
return callStable(ctx, "GET", "/api/v1/triggers/runs/{run_id}/loops/{loop_id}/iterations", "loop iterations", {
|
|
303
|
+
params: { run_id: [loop.owner_run_id], loop_id: [loop.id] },
|
|
304
|
+
query: { limit, cursor },
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
function newestIteration(loop, items) {
|
|
308
|
+
return Math.max(loop.iteration_number, ...items.map((i) => i.iteration_number));
|
|
309
|
+
}
|
|
310
|
+
function envelopeIn(it, loop, newest) {
|
|
311
|
+
const settled = LOOP_SETTLED.has(loop.state);
|
|
312
|
+
const later = newest > it.iteration_number;
|
|
313
|
+
return iterationEnvelope(it, later || settled, settled && !later ? loop : undefined);
|
|
314
|
+
}
|
|
315
|
+
export const loopWatch = {
|
|
316
|
+
name: "loop watch",
|
|
317
|
+
summary: "Follow a loop: one line per decided iteration and per state change, then the loop's outcome.",
|
|
318
|
+
description: "Prints each iteration once the loop accepted it, rejected it or its child failed, with its outcome and usage\n" +
|
|
319
|
+
"(one JSON object per line with --json), and the loop's outcome when it ends or pauses. Exit 0 when the loop\n" +
|
|
320
|
+
"completed, 1 when it failed or was cancelled, 5 at once when it pauses (a person reviews and resumes it),\n" +
|
|
321
|
+
"6 when the timeout passed first.",
|
|
322
|
+
readOnly: true,
|
|
323
|
+
idempotent: true,
|
|
324
|
+
mcpTool: false,
|
|
325
|
+
positionals: [{ name: "run", description: "The trigger run id.", required: true }],
|
|
326
|
+
options: {
|
|
327
|
+
loop: LOOP_OPTION,
|
|
328
|
+
timeout: { ...TIMEOUT_OPTION, description: "Stop watching after this long (default 10m)." },
|
|
329
|
+
},
|
|
330
|
+
examples: ["cavelon loop watch <run>", "cavelon loop watch <run> --json --timeout 5m"],
|
|
331
|
+
async run(ctx, input) {
|
|
332
|
+
const runId = positional(input, "run");
|
|
333
|
+
const loopId = stringOption(input, "loop");
|
|
334
|
+
const deadline = Date.now() + timeoutMs(ctx, stringOption(input, "timeout"), "10m");
|
|
335
|
+
const fromEnv = Number(ctx.io.env.CAVELON_POLL_INTERVAL_MS);
|
|
336
|
+
const interval = Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 2000;
|
|
337
|
+
const emit = (line, text) => ctx.io.stdout.write(ctx.json ? `${JSON.stringify(line)}\n` : `${text}\n`);
|
|
338
|
+
const watched = { shown: new Set(), offset: 0, lastState: "", lastOutcome: null };
|
|
339
|
+
let waiting;
|
|
340
|
+
for (;;) {
|
|
341
|
+
const next = loopId ? await getLoop(ctx, runId, loopId) : currentLoop(await loopsOf(ctx, runId));
|
|
342
|
+
if (next && next.id !== watched.loop?.id) {
|
|
343
|
+
watched.offset = 0;
|
|
344
|
+
watched.lastOutcome = null;
|
|
345
|
+
}
|
|
346
|
+
watched.loop = next;
|
|
347
|
+
if (next) {
|
|
348
|
+
for (const envelope of await decidedIterations(ctx, next, watched)) {
|
|
349
|
+
if (envelope.outcome)
|
|
350
|
+
watched.lastOutcome = envelope.outcome;
|
|
351
|
+
emit({ type: "iteration", loop_id: next.id, ...envelope }, iterationLine(envelope));
|
|
352
|
+
}
|
|
353
|
+
const state = `${next.id}:${next.state}:${next.pause_requested}`;
|
|
354
|
+
if (state !== watched.lastState) {
|
|
355
|
+
emit({ type: "loop", loop: loopSummary(next) }, stateLine(next));
|
|
356
|
+
watched.lastState = state;
|
|
357
|
+
}
|
|
358
|
+
if (LOOP_SETTLED.has(next.state)) {
|
|
359
|
+
const outcome = await loopOutcome(ctx, next, watched.lastOutcome);
|
|
360
|
+
emit({ type: "outcome", ...outcome }, outcomeText(outcome));
|
|
361
|
+
return { data: undefined, text: "", exitCode: loopExitCode(next.state) };
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
const { run, note } = await requireRunGoesOn(ctx, runId);
|
|
366
|
+
if (note?.capacity_wait && !waiting)
|
|
367
|
+
emit({ type: "run", run: runSummary(run, note) }, `run ${run.id} ${run.status} ${note.capacity_wait.note}`);
|
|
368
|
+
waiting = note?.capacity_wait;
|
|
369
|
+
}
|
|
370
|
+
const left = deadline - Date.now();
|
|
371
|
+
if (left <= 0)
|
|
372
|
+
break;
|
|
373
|
+
await ctx.io.sleep(Math.min(interval, left));
|
|
374
|
+
}
|
|
375
|
+
const state = watched.loop?.state ?? (waiting ? "not started: its run is waiting for run capacity" : "not started");
|
|
376
|
+
const resume = cavelonCommand("loop", "watch", runId, ...(loopId ? ["--loop", loopId] : []));
|
|
377
|
+
ctx.io.stderr.write(`Stopped watching; the loop is still ${state}. Resume: ${resume}\n`);
|
|
378
|
+
return { data: undefined, text: "", exitCode: ExitCode.timeout };
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
async function decidedIterations(ctx, loop, watched) {
|
|
382
|
+
const found = [];
|
|
383
|
+
let cursor = Math.min(watched.offset, MAX_ITERATION_CURSOR);
|
|
384
|
+
while (cursor !== null) {
|
|
385
|
+
const page = await iterationPage(ctx, loop, 20, cursor);
|
|
386
|
+
const newest = newestIteration(loop, page.items);
|
|
387
|
+
for (const it of page.items.filter((i) => !watched.shown.has(i.id))) {
|
|
388
|
+
const envelope = envelopeIn(it, loop, newest);
|
|
389
|
+
if (envelope.verdict === "ended" || envelope.verdict === "running")
|
|
390
|
+
continue;
|
|
391
|
+
watched.shown.add(it.id);
|
|
392
|
+
found.push(envelope);
|
|
393
|
+
}
|
|
394
|
+
const prefix = page.items.findIndex((i) => !watched.shown.has(i.id));
|
|
395
|
+
if (prefix === -1 && page.next_cursor !== null)
|
|
396
|
+
cursor = page.next_cursor;
|
|
397
|
+
else {
|
|
398
|
+
watched.offset = cursor + (prefix === -1 ? page.items.length : prefix);
|
|
399
|
+
cursor = null;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return found;
|
|
403
|
+
}
|
|
404
|
+
function stateLine(loop) {
|
|
405
|
+
const reason = loop.reason ?? loop.blocked_reason;
|
|
406
|
+
const because = reason ? " (" + reason + ")" : "";
|
|
407
|
+
const requested = loop.pause_requested && loop.state !== "paused" ? " pause requested" : "";
|
|
408
|
+
return `loop ${loop.id} ${loop.state}${because}${requested}`;
|
|
409
|
+
}
|
|
410
|
+
async function loopOutcome(ctx, loop, lastOutcome) {
|
|
411
|
+
let detail = loop;
|
|
412
|
+
try {
|
|
413
|
+
detail = await getLoop(ctx, loop.owner_run_id, loop.id);
|
|
414
|
+
}
|
|
415
|
+
catch (error) {
|
|
416
|
+
if (!(error instanceof CavelonError))
|
|
417
|
+
throw error;
|
|
418
|
+
}
|
|
419
|
+
const terminal = detail.terminal_result ? JSON.stringify(detail.terminal_result) : null;
|
|
420
|
+
return {
|
|
421
|
+
loop_id: loop.id,
|
|
422
|
+
run_id: loop.owner_run_id,
|
|
423
|
+
state: loop.state,
|
|
424
|
+
reason: detail.reason ?? loop.reason ?? null,
|
|
425
|
+
blocked_reason: detail.blocked_reason ?? null,
|
|
426
|
+
iterations: detail.iteration_number,
|
|
427
|
+
last_outcome: lastOutcome,
|
|
428
|
+
charged_usage: detail.charged_usage,
|
|
429
|
+
progress: detail.progress_summary ? clip(detail.progress_summary, 500) : null,
|
|
430
|
+
terminal_result: terminal && terminal.length > 2000 ? clip(terminal, 2000) : (detail.terminal_result ?? null),
|
|
431
|
+
...(loop.state === "paused" ? { go_on: await howToGoOn(ctx, detail) } : {}),
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
function outcomeText(outcome) {
|
|
435
|
+
const because = [outcome.reason, outcome.blocked_reason].filter(Boolean).join(": ");
|
|
436
|
+
const counted = `after ${outcome.iterations} iteration${outcome.iterations === 1 ? "" : "s"}`;
|
|
437
|
+
const last = outcome.last_outcome ? ` (last outcome: ${outcome.last_outcome})` : "";
|
|
438
|
+
const state = outcome.state === "paused" ? "is paused" : outcome.state;
|
|
439
|
+
const why = because ? " (" + because + ")" : "";
|
|
440
|
+
const lines = [`Loop ${outcome.loop_id} ${state} ${counted}${why}${last}.`, `Charged: ${usageText(outcome.charged_usage)}.`];
|
|
441
|
+
if (outcome.progress)
|
|
442
|
+
lines.push(`Progress: ${outcome.progress}`);
|
|
443
|
+
if (outcome.go_on)
|
|
444
|
+
lines.push(goOnText(outcome.go_on));
|
|
445
|
+
return lines.join("\n");
|
|
446
|
+
}
|
|
447
|
+
async function requireRunGoesOn(ctx, runId) {
|
|
448
|
+
const run = await getRun(ctx, runId);
|
|
449
|
+
const note = await runCapacityNote(ctx, run);
|
|
450
|
+
if (RUN_TERMINAL.has(run.status)) {
|
|
451
|
+
const why = await whyNoLoop(ctx, run);
|
|
452
|
+
throw new CavelonError(ExitCode.failure, {
|
|
453
|
+
code: "loop_not_found",
|
|
454
|
+
message: `Run ${runId} ended (${run.status}) without a loop.${why.text ? " " + why.text : ""}`,
|
|
455
|
+
hint: note?.capacity_refusal ? `${note.capacity_refusal.code}: ${note.capacity_refusal.hint}` : `\`${cavelonCommand("trace", run.id)}\` shows its traces.`,
|
|
456
|
+
details: note?.capacity_refusal || why.stage_errors.length
|
|
457
|
+
? { ...(note?.capacity_refusal ? { capacity_refusal: note.capacity_refusal } : {}), ...(why.stage_errors.length ? { stage_errors: why.stage_errors } : {}) }
|
|
458
|
+
: undefined,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
return { run, note };
|
|
462
|
+
}
|
|
463
|
+
const MAX_STAGE_ERRORS = 5;
|
|
464
|
+
export async function stageErrors(ctx, runId) {
|
|
465
|
+
let state;
|
|
466
|
+
try {
|
|
467
|
+
state = await callStable(ctx, "GET", "/api/v1/triggers/runs/{run_id}/orchestration-state", "run stages", { params: { run_id: [runId] } });
|
|
468
|
+
}
|
|
469
|
+
catch (error) {
|
|
470
|
+
if (error instanceof CavelonError)
|
|
471
|
+
return [];
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
return (state.stages ?? [])
|
|
475
|
+
.filter((stage) => stage.error && Object.keys(stage.error).length > 0)
|
|
476
|
+
.slice(0, MAX_STAGE_ERRORS)
|
|
477
|
+
.map((stage) => ({
|
|
478
|
+
stage: stage.key,
|
|
479
|
+
index: stage.stage_index ?? null,
|
|
480
|
+
status: stage.status ?? null,
|
|
481
|
+
message: clip(typeof stage.error.message === "string" ? stage.error.message : JSON.stringify(stage.error), 500),
|
|
482
|
+
}));
|
|
483
|
+
}
|
|
484
|
+
export function stageErrorText(stage) {
|
|
485
|
+
return `Stage ${stage.index ?? "?"} (${stage.stage}) ${stage.status ?? "errored"}: ${stage.message}`;
|
|
486
|
+
}
|
|
487
|
+
async function endedWithoutLoop(ctx, runId) {
|
|
488
|
+
const run = await getRun(ctx, runId);
|
|
489
|
+
if (!RUN_TERMINAL.has(run.status) || (await loopsOf(ctx, runId)).length > 0)
|
|
490
|
+
return undefined;
|
|
491
|
+
const why = await whyNoLoop(ctx, run);
|
|
492
|
+
return { status: run.status, why: why.text, stage_errors: why.stage_errors };
|
|
493
|
+
}
|
|
494
|
+
async function whyNoLoop(ctx, run) {
|
|
495
|
+
const stages = await stageErrors(ctx, run.id);
|
|
496
|
+
const text = [run.error_summary, ...stages.map(stageErrorText)].filter(Boolean).join(" ");
|
|
497
|
+
return { text, stage_errors: stages };
|
|
498
|
+
}
|
|
499
|
+
const RESUME_KINDS = new Set(["plain", "review_required", "none"]);
|
|
500
|
+
async function catalogOrNone(ctx) {
|
|
501
|
+
return catalogFor(ctx, false).catch(() => null);
|
|
502
|
+
}
|
|
503
|
+
function publishedResume(loop) {
|
|
504
|
+
return typeof loop.resume === "string" && RESUME_KINDS.has(loop.resume) ? loop.resume : undefined;
|
|
505
|
+
}
|
|
506
|
+
function resumeBlocker(loop, now) {
|
|
507
|
+
if (loop.cancel_requested || loop.cleanup_pending || loop.parent_completion_consumed_at)
|
|
508
|
+
return { why: "its run is being stopped", final: true };
|
|
509
|
+
if (Date.parse(loop.deadline_at) <= now)
|
|
510
|
+
return { why: `its deadline passed (${loop.deadline_at})`, final: true };
|
|
511
|
+
if (loop.resume_enabled === false)
|
|
512
|
+
return { why: "Masterloop or Sandboxes are switched off on this instance", final: true };
|
|
513
|
+
const unknown = loop.operation_counts?.unknown ?? 0;
|
|
514
|
+
if (unknown > 0) {
|
|
515
|
+
const what = unknown === 1 ? "one of its Sandbox operations has" : `${unknown} of its Sandbox operations have`;
|
|
516
|
+
return { why: `the instance refuses a resume while ${what} an unknown outcome; wait until the Sandbox reconciles it`, final: false };
|
|
517
|
+
}
|
|
518
|
+
return undefined;
|
|
519
|
+
}
|
|
520
|
+
function resumeCommand(loop, reason) {
|
|
521
|
+
return cavelonCommand("loop", "resume", loop.owner_run_id, "--loop", loop.id, ...(reason ? ["--reason", reason] : []));
|
|
522
|
+
}
|
|
523
|
+
async function startAgain(ctx, loop) {
|
|
524
|
+
let start = "cavelon loop start <trigger>";
|
|
525
|
+
try {
|
|
526
|
+
const run = await getRun(ctx, loop.owner_run_id);
|
|
527
|
+
if (run.trigger_definition_id)
|
|
528
|
+
start = cavelonCommand("loop", "start", (await resolveTrigger(ctx, run.trigger_definition_id)).slug);
|
|
529
|
+
}
|
|
530
|
+
catch (error) {
|
|
531
|
+
if (!(error instanceof CavelonError))
|
|
532
|
+
throw error;
|
|
533
|
+
}
|
|
534
|
+
return [...(loop.cancel_requested ? [] : [cavelonCommand("loop", "cancel", loop.owner_run_id, "--confirm")]), start];
|
|
535
|
+
}
|
|
536
|
+
async function howToGoOn(ctx, loop) {
|
|
537
|
+
const entry = loop.reason ? catalogEntry(await catalogOrNone(ctx), loop.reason) : undefined;
|
|
538
|
+
const published = publishedResume(loop);
|
|
539
|
+
const blocker = published ? undefined : resumeBlocker(loop, Date.now());
|
|
540
|
+
const resume = published ?? (blocker?.final ? "none" : null);
|
|
541
|
+
const base = {
|
|
542
|
+
resume,
|
|
543
|
+
decided_by: published ? "instance" : "loop_state",
|
|
544
|
+
reason_text: entry ? [entry.message, entry.hint].filter(Boolean).join(" ") : null,
|
|
545
|
+
why_not: blocker?.why ?? null,
|
|
546
|
+
if_review_required: null,
|
|
547
|
+
};
|
|
548
|
+
if (resume === "none")
|
|
549
|
+
return { ...base, commands: await startAgain(ctx, loop) };
|
|
550
|
+
if (resume === "review_required" && loop.reason)
|
|
551
|
+
return { ...base, commands: [resumeCommand(loop, loop.reason)] };
|
|
552
|
+
if (resume === "plain")
|
|
553
|
+
return { ...base, commands: [resumeCommand(loop)] };
|
|
554
|
+
return { ...base, commands: [resumeCommand(loop)], if_review_required: loop.reason ? resumeCommand(loop, loop.reason) : null };
|
|
555
|
+
}
|
|
556
|
+
function goOnText(go) {
|
|
557
|
+
const commands = go.commands.map((c) => " " + c);
|
|
558
|
+
const lines = go.reason_text ? [go.reason_text] : [];
|
|
559
|
+
if (go.resume === "none") {
|
|
560
|
+
const why = go.why_not ? `: ${go.why_not}` : "";
|
|
561
|
+
lines.push(`It cannot be resumed${why}. Instead, stop the run, fix the cause and start a new run:`, ...commands);
|
|
562
|
+
}
|
|
563
|
+
else if (go.resume === "review_required") {
|
|
564
|
+
lines.push("It waits for a person. The pause is a verdict on the task: check the cause and fix it, then resume and name the pause reason as reviewed:", ...commands);
|
|
565
|
+
}
|
|
566
|
+
else {
|
|
567
|
+
lines.push("It waits for a person: fix the cause, then resume it:", ...commands);
|
|
568
|
+
if (go.why_not)
|
|
569
|
+
lines.push(`Not yet: ${go.why_not}.`);
|
|
570
|
+
if (go.if_review_required) {
|
|
571
|
+
lines.push("If the instance answers loop_resume_review_required, the pause is a verdict on the task; after your review:", ` ${go.if_review_required}`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return lines.join("\n");
|
|
575
|
+
}
|
|
576
|
+
function controlCommand(action) {
|
|
577
|
+
const pausing = action === "pause";
|
|
578
|
+
return {
|
|
579
|
+
name: `loop ${action}`,
|
|
580
|
+
summary: pausing ? "Ask a loop to pause at its next safe point." : "Resume a paused loop.",
|
|
581
|
+
description: pausing
|
|
582
|
+
? "The current iteration finishes first. A paused loop waits for `loop resume`; `wait` on its run exits 5 meanwhile."
|
|
583
|
+
: "The instance checks the loop's budget, deadline and Sandbox again before it goes on. A pause that is a verdict on\n" +
|
|
584
|
+
"the task needs --reason with the pause reason a person reviewed, exactly as the loop names it (`loop watch` prints\n" +
|
|
585
|
+
"the command); any other pause resumes without it. A pause that cannot be resumed is refused with what to do instead.",
|
|
586
|
+
readOnly: false,
|
|
587
|
+
mcpTool: `loop_${action}`,
|
|
588
|
+
positionals: [{ name: "run", description: "The trigger run id.", required: true }],
|
|
589
|
+
options: {
|
|
590
|
+
loop: LOOP_OPTION,
|
|
591
|
+
...(pausing ? {} : { reason: REVIEWED_REASON_OPTION }),
|
|
592
|
+
"idempotency-key": UUID_KEY_OPTION,
|
|
593
|
+
},
|
|
594
|
+
examples: pausing
|
|
595
|
+
? ["cavelon loop pause <run>", "cavelon loop pause <run> --loop <loop_id>"]
|
|
596
|
+
: ["cavelon loop resume <run>", "cavelon loop resume <run> --loop <loop_id> --reason task_blocked"],
|
|
597
|
+
async run(ctx, input) {
|
|
598
|
+
const runId = positional(input, "run");
|
|
599
|
+
const key = idempotencyKey(input);
|
|
600
|
+
let loop = await pickLoop(ctx, runId, stringOption(input, "loop"), pausing ? (l) => !LOOP_TERMINAL.has(l.state) && l.state !== "paused" : (l) => l.state === "paused", pausing ? "is running" : "is paused");
|
|
601
|
+
const reason = pausing ? undefined : stringOption(input, "reason");
|
|
602
|
+
if (!pausing) {
|
|
603
|
+
loop = await getLoop(ctx, loop.owner_run_id, loop.id);
|
|
604
|
+
await checkResume(ctx, loop, reason);
|
|
605
|
+
}
|
|
606
|
+
let receipt;
|
|
607
|
+
try {
|
|
608
|
+
receipt = await callStable(ctx, "POST", `/api/v1/triggers/runs/{run_id}/loops/{loop_id}/${action}`, `${action} loops`, {
|
|
609
|
+
params: { run_id: [loop.owner_run_id], loop_id: [loop.id] },
|
|
610
|
+
headers: { "Idempotency-Key": key },
|
|
611
|
+
body: { expected_version: loop.version, ...(reason ? { reviewed_reason: reason } : {}) },
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
catch (error) {
|
|
615
|
+
if (pausing || !(error instanceof CavelonError) || error.exitCode === ExitCode.server)
|
|
616
|
+
throw withRetryKey(error, key);
|
|
617
|
+
throw await resumeRefused(ctx, error, loop, reason);
|
|
618
|
+
}
|
|
619
|
+
const text = pausing
|
|
620
|
+
? `Pause requested for loop ${receipt.loop_id} (${receipt.state}); it pauses after the current iteration.`
|
|
621
|
+
: `Loop ${receipt.loop_id} resumes (${receipt.state}).`;
|
|
622
|
+
return { data: { ...receipt, run_id: loop.owner_run_id, operation_id: loop.operation_id }, text: `${text}\nFollow: cavelon loop watch ${loop.owner_run_id}` };
|
|
623
|
+
},
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
const REVIEWED_REASON_OPTION = {
|
|
627
|
+
type: "string",
|
|
628
|
+
value: "<pause_reason>",
|
|
629
|
+
description: "The pause reason a person reviewed, exactly as the loop names it (task_blocked, not free text); only a verdict on the task needs it.",
|
|
630
|
+
};
|
|
631
|
+
function reviewRequired(loop, message, hint) {
|
|
632
|
+
const check = `${cavelonCommand("loop", "iterations", loop.owner_run_id, "--loop", loop.id)} and ${cavelonCommand("trace")} <child_run_id>`;
|
|
633
|
+
return new CavelonError(ExitCode.needsAction, {
|
|
634
|
+
code: "loop_resume_review_required",
|
|
635
|
+
message,
|
|
636
|
+
hint: [hint, `A person checks the cause (${check}) and fixes it, then: ${resumeCommand(loop, loop.reason ?? "<pause_reason>")}`].filter(Boolean).join(" "),
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
async function checkResume(ctx, loop, reason) {
|
|
640
|
+
if (reason !== undefined && reason !== loop.reason) {
|
|
641
|
+
throw usageError(`--reason names the pause reason you reviewed, exactly as the loop names it: loop ${loop.id} is paused for ${loop.reason ?? "no reason"}, not "${reason}".`, loop.reason ? `After a review of ${loop.reason}: ${resumeCommand(loop, loop.reason)}` : `Resume it without --reason: ${resumeCommand(loop)}`);
|
|
642
|
+
}
|
|
643
|
+
const published = publishedResume(loop);
|
|
644
|
+
if (published === "none") {
|
|
645
|
+
const go = await howToGoOn(ctx, loop);
|
|
646
|
+
throw new CavelonError(ExitCode.conflict, {
|
|
647
|
+
code: "loop_not_resumable",
|
|
648
|
+
message: `Loop ${loop.id} (paused for ${loop.reason ?? "no reason"}) cannot be resumed.${go.reason_text ? " " + go.reason_text : ""}`,
|
|
649
|
+
hint: `Instead, stop the run, fix the cause and start a new run: ${go.commands.join(", then ")}`,
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
if (published === "review_required" && reason === undefined) {
|
|
653
|
+
throw reviewRequired(loop, `The pause (${loop.reason}) is a verdict on the task: a resume names it as reviewed.`);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
async function resumeRefused(ctx, error, loop, reason) {
|
|
657
|
+
const entry = catalogEntry(await catalogOrNone(ctx), error.code);
|
|
658
|
+
const said = [error.hint, entry?.hint].filter((h, i, all) => Boolean(h) && all.indexOf(h) === i).join(" ") || undefined;
|
|
659
|
+
if (error.code === "loop_resume_review_required" && loop.reason)
|
|
660
|
+
return reviewRequired(loop, error.message, said);
|
|
661
|
+
let next;
|
|
662
|
+
if (error.code === "loop_control_invalid" && reason !== undefined)
|
|
663
|
+
next = `This pause (${loop.reason}) takes no review; resume it without --reason: ${resumeCommand(loop)}`;
|
|
664
|
+
if (error.code === "loop_review_reason_mismatch")
|
|
665
|
+
next = `The loop's pause reason changed since it was read; ${cavelonCommand("loop", "watch", loop.owner_run_id, "--loop", loop.id)} shows it.`;
|
|
666
|
+
if (error.code === "loop_operation_unknown")
|
|
667
|
+
next = "A Sandbox operation of the loop has an unknown outcome; resume it once the Sandbox has reconciled the operation.";
|
|
668
|
+
if (error.code === "loop_control_unavailable")
|
|
669
|
+
next = `The loop cannot go on. Instead, stop the run, fix the cause and start a new run: ${(await startAgain(ctx, loop)).join(", then ")}`;
|
|
670
|
+
if (!next && !entry)
|
|
671
|
+
return error;
|
|
672
|
+
return new CavelonError(error.exitCode, {
|
|
673
|
+
code: error.code,
|
|
674
|
+
message: error.message,
|
|
675
|
+
hint: [said, next].filter(Boolean).join(" "),
|
|
676
|
+
docs: error.docs ?? entry?.docs,
|
|
677
|
+
status: error.status,
|
|
678
|
+
details: error.details,
|
|
679
|
+
blockers: error.blockers,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
export const loopPause = controlCommand("pause");
|
|
683
|
+
export const loopResume = controlCommand("resume");
|
|
684
|
+
const SECRET_PREFIXES = ["cbp_", "cvpat_"];
|
|
685
|
+
async function resolveApiKey(ctx, ref) {
|
|
686
|
+
if (SECRET_PREFIXES.some((p) => ref.startsWith(p))) {
|
|
687
|
+
throw usageError("That looks like a key or token value. Name the API key by its name or id; a secret never goes into an argument.", "A personal access token is never an execution identity; scheduled and webhook runs act as an API key.");
|
|
688
|
+
}
|
|
689
|
+
if (isUuid(ref))
|
|
690
|
+
return { id: ref };
|
|
691
|
+
const client = await ctx.client();
|
|
692
|
+
const tenantId = client.target.tenantId ?? (await readPrincipal(client))?.tenant_id ?? undefined;
|
|
693
|
+
if (!tenantId)
|
|
694
|
+
throw usageError("Which tenant's API keys? Choose one with `cavelon use <tenant>` or --tenant, or pass the key's id.");
|
|
695
|
+
const keys = [];
|
|
696
|
+
for (let offset = 0; offset < 1000; offset += 100) {
|
|
697
|
+
const page = await callStable(ctx, "GET", "/api/v1/tenants/{tenant_id}/api-keys", "API keys", {
|
|
698
|
+
params: { tenant_id: [tenantId] },
|
|
699
|
+
query: { limit: 100, offset },
|
|
700
|
+
});
|
|
701
|
+
keys.push(...page.items);
|
|
702
|
+
if (keys.length >= page.total || page.items.length === 0)
|
|
703
|
+
break;
|
|
704
|
+
}
|
|
705
|
+
const hits = keys.filter((k) => k.name === ref || k.name.toLowerCase() === ref.toLowerCase());
|
|
706
|
+
if (hits.length === 1) {
|
|
707
|
+
if (!hits[0].is_active)
|
|
708
|
+
throw new CavelonError(ExitCode.failure, { code: "api_key_inactive", message: `API key "${hits[0].name}" is revoked or inactive.` });
|
|
709
|
+
return hits[0];
|
|
710
|
+
}
|
|
711
|
+
throw new CavelonError(ExitCode.failure, {
|
|
712
|
+
code: hits.length ? "api_key_ambiguous" : "api_key_not_found",
|
|
713
|
+
message: hits.length ? `${hits.length} API keys are named "${ref}"; pass its id.` : `No API key "${ref}" in this tenant.`,
|
|
714
|
+
hint: "A person creates API keys in Settings → API keys; the kit only binds one.",
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
function identityView(identity) {
|
|
718
|
+
const key = identity.selected_key;
|
|
719
|
+
return {
|
|
720
|
+
trigger_id: identity.trigger_id,
|
|
721
|
+
api_key_id: identity.api_key_id,
|
|
722
|
+
key: key ? (key.name ?? key.key_prefix ?? key.id) : null,
|
|
723
|
+
version: identity.version,
|
|
724
|
+
problem: key?.problem ?? null,
|
|
725
|
+
required_solutions: (identity.required_solutions ?? []).map((s) => s.name),
|
|
726
|
+
uncovered_solutions: (key?.uncovered_solutions ?? []).map((s) => s.name),
|
|
727
|
+
sandboxes_missing_key: (identity.sandboxes_missing_key ?? []).map((s) => s.name),
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
function identityText(trigger, view) {
|
|
731
|
+
const who = view.key ? `runs as API key "${view.key}"` : "no execution identity (scheduled and webhook runs cannot start)";
|
|
732
|
+
const lines = [`Trigger ${trigger.slug}: ${who}`];
|
|
733
|
+
if (view.required_solutions.length)
|
|
734
|
+
lines.push(`The key must reach: ${view.required_solutions.join(", ")}`);
|
|
735
|
+
if (view.problem)
|
|
736
|
+
lines.push(`Problem: ${view.problem}`);
|
|
737
|
+
if (view.uncovered_solutions.length)
|
|
738
|
+
lines.push(`Not covered by the key: ${view.uncovered_solutions.join(", ")}`);
|
|
739
|
+
if (view.sandboxes_missing_key.length)
|
|
740
|
+
lines.push(`Sandboxes whose Access does not list the key: ${view.sandboxes_missing_key.join(", ")} (a person adds it in the Admin)`);
|
|
741
|
+
return lines.join("\n");
|
|
742
|
+
}
|
|
743
|
+
export const triggerIdentity = {
|
|
744
|
+
name: "trigger identity",
|
|
745
|
+
summary: "Show, bind or clear the API key a trigger's unattended runs act as (binding needs --confirm).",
|
|
746
|
+
description: "Without <key> or --clear, shows the binding. Binding gives the trigger standing authority, so it is never part of\n" +
|
|
747
|
+
"`apply`: show the person, then run it with --confirm. It needs settings.manage and triggers.manage. Creating keys\n" +
|
|
748
|
+
"and Sandbox Access stay in the Admin. A personal access token is never an execution identity.",
|
|
749
|
+
readOnly: false,
|
|
750
|
+
destructive: true,
|
|
751
|
+
idempotent: true,
|
|
752
|
+
mcpTool: "trigger_identity",
|
|
753
|
+
positionals: [
|
|
754
|
+
{ name: "trigger", description: "Trigger slug, name or id.", required: true },
|
|
755
|
+
{ name: "key", description: "The API key's name or id (never its value)." },
|
|
756
|
+
],
|
|
757
|
+
options: {
|
|
758
|
+
clear: { type: "boolean", description: "Remove the binding; scheduled and webhook runs then cannot start." },
|
|
759
|
+
confirm: { type: "boolean", description: "Make the change; without it nothing changes." },
|
|
760
|
+
},
|
|
761
|
+
examples: ["cavelon trigger identity orders", "cavelon trigger identity orders loop-runner --confirm", "cavelon trigger identity orders --clear --confirm"],
|
|
762
|
+
async run(ctx, input) {
|
|
763
|
+
const keyRef = positional(input, "key");
|
|
764
|
+
const clear = boolOption(input, "clear");
|
|
765
|
+
if (keyRef && clear)
|
|
766
|
+
throw usageError("Pass a key or --clear, not both.");
|
|
767
|
+
const trigger = await resolveTrigger(ctx, positional(input, "trigger"));
|
|
768
|
+
const route = "/api/v1/triggers/{trigger_id}/execution-identity";
|
|
769
|
+
const current = await callStable(ctx, "GET", route, "execution identities", { params: { trigger_id: [trigger.id] } });
|
|
770
|
+
const view = identityView(current);
|
|
771
|
+
if (!keyRef && !clear)
|
|
772
|
+
return { data: { trigger: trigger.slug, ...view }, text: identityText(trigger, view) };
|
|
773
|
+
const key = keyRef ? await resolveApiKey(ctx, keyRef) : undefined;
|
|
774
|
+
const wanted = key?.id ?? null;
|
|
775
|
+
if (wanted === current.api_key_id) {
|
|
776
|
+
return { data: { trigger: trigger.slug, changed: false, ...view }, text: `Nothing to change.\n${identityText(trigger, view)}` };
|
|
777
|
+
}
|
|
778
|
+
const keyName = key && "name" in key ? key.name : wanted;
|
|
779
|
+
const change = wanted ? `bind API key "${keyName}"` : "clear the binding";
|
|
780
|
+
if (!boolOption(input, "confirm")) {
|
|
781
|
+
const confirm = cavelonCommand("trigger", "identity", trigger.slug, keyRef ?? "--clear", "--confirm");
|
|
782
|
+
return {
|
|
783
|
+
data: { trigger: trigger.slug, changed: false, would: change, current: view, confirm },
|
|
784
|
+
text: `${identityText(trigger, view)}\n\nNothing changed. To ${change}: ${confirm}`,
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
const updated = await callStable(ctx, "PUT", route, "execution identities", {
|
|
788
|
+
params: { trigger_id: [trigger.id] },
|
|
789
|
+
body: { api_key_id: wanted, expected_version: current.version },
|
|
790
|
+
});
|
|
791
|
+
const after = identityView(updated);
|
|
792
|
+
if (after.problem)
|
|
793
|
+
ctx.warn(`The key cannot start this trigger's runs yet: ${after.problem}`);
|
|
794
|
+
if (after.sandboxes_missing_key.length)
|
|
795
|
+
ctx.warn(`Sandbox Access does not list the key for: ${after.sandboxes_missing_key.join(", ")}. A person adds it in the Admin.`);
|
|
796
|
+
return { data: { trigger: trigger.slug, changed: true, ...after }, text: `Done: ${change}.\n${identityText(trigger, after)}` };
|
|
797
|
+
},
|
|
798
|
+
};
|