@h-rig/cli 0.0.6-alpha.15 → 0.0.6-alpha.150

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 (49) hide show
  1. package/README.md +6 -28
  2. package/bin/rig.js +16 -0
  3. package/package.json +14 -27
  4. package/dist/bin/build-rig-binaries.js +0 -107
  5. package/dist/bin/rig.js +0 -10076
  6. package/dist/src/commands/_authority-runs.js +0 -111
  7. package/dist/src/commands/_connection-state.js +0 -123
  8. package/dist/src/commands/_doctor-checks.js +0 -506
  9. package/dist/src/commands/_operator-surface.js +0 -157
  10. package/dist/src/commands/_operator-view.js +0 -449
  11. package/dist/src/commands/_parsers.js +0 -107
  12. package/dist/src/commands/_paths.js +0 -50
  13. package/dist/src/commands/_pi-install.js +0 -184
  14. package/dist/src/commands/_policy.js +0 -79
  15. package/dist/src/commands/_preflight.js +0 -482
  16. package/dist/src/commands/_probes.js +0 -13
  17. package/dist/src/commands/_run-driver-helpers.js +0 -289
  18. package/dist/src/commands/_server-client.js +0 -426
  19. package/dist/src/commands/_snapshot-upload.js +0 -318
  20. package/dist/src/commands/_task-picker.js +0 -56
  21. package/dist/src/commands/agent.js +0 -499
  22. package/dist/src/commands/browser.js +0 -890
  23. package/dist/src/commands/connect.js +0 -180
  24. package/dist/src/commands/dist.js +0 -402
  25. package/dist/src/commands/doctor.js +0 -516
  26. package/dist/src/commands/github.js +0 -281
  27. package/dist/src/commands/inbox.js +0 -160
  28. package/dist/src/commands/init.js +0 -1511
  29. package/dist/src/commands/inspect.js +0 -174
  30. package/dist/src/commands/inspector.js +0 -256
  31. package/dist/src/commands/plugin.js +0 -167
  32. package/dist/src/commands/profile-and-review.js +0 -178
  33. package/dist/src/commands/queue.js +0 -198
  34. package/dist/src/commands/remote.js +0 -507
  35. package/dist/src/commands/repo-git-harness.js +0 -221
  36. package/dist/src/commands/run.js +0 -893
  37. package/dist/src/commands/server.js +0 -373
  38. package/dist/src/commands/setup.js +0 -686
  39. package/dist/src/commands/task-report-bug.js +0 -1083
  40. package/dist/src/commands/task-run-driver.js +0 -2442
  41. package/dist/src/commands/task.js +0 -1476
  42. package/dist/src/commands/test.js +0 -39
  43. package/dist/src/commands/workspace.js +0 -123
  44. package/dist/src/commands.js +0 -9755
  45. package/dist/src/index.js +0 -10094
  46. package/dist/src/launcher.js +0 -133
  47. package/dist/src/report-bug.js +0 -260
  48. package/dist/src/runner.js +0 -273
  49. package/dist/src/withMutedConsole.js +0 -42
@@ -1,893 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/run.ts
3
- import { createInterface as createInterface2 } from "readline/promises";
4
-
5
- // packages/cli/src/runner.ts
6
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
7
- import { CliError } from "@rig/runtime/control-plane/errors";
8
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
9
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
10
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
11
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
12
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
13
- function takeFlag(args, flag) {
14
- const rest = [];
15
- let value = false;
16
- for (const arg of args) {
17
- if (arg === flag) {
18
- value = true;
19
- continue;
20
- }
21
- rest.push(arg);
22
- }
23
- return { value, rest };
24
- }
25
- function takeOption(args, option) {
26
- const rest = [];
27
- let value;
28
- for (let index = 0;index < args.length; index += 1) {
29
- const current = args[index];
30
- if (current === option) {
31
- const next = args[index + 1];
32
- if (!next || next.startsWith("-")) {
33
- throw new CliError(`Missing value for ${option}`);
34
- }
35
- value = next;
36
- index += 1;
37
- continue;
38
- }
39
- if (current !== undefined) {
40
- rest.push(current);
41
- }
42
- }
43
- return { value, rest };
44
- }
45
- function requireNoExtraArgs(args, usage) {
46
- if (args.length > 0) {
47
- throw new CliError(`Unexpected arguments: ${args.join(" ")}
48
- Usage: ${usage}`);
49
- }
50
- }
51
-
52
- // packages/cli/src/commands/run.ts
53
- import {
54
- listAuthorityRuns,
55
- readAuthorityRun
56
- } from "@rig/runtime/control-plane/authority-files";
57
- import {
58
- cleanupRunState,
59
- deleteRunState,
60
- listOpenEpics,
61
- resolveDefaultEpic,
62
- runResume,
63
- runRestart,
64
- runStatus,
65
- runStop,
66
- startRun,
67
- defaultStartRunOptions
68
- } from "@rig/runtime/control-plane/native/run-ops";
69
- import { loadRuntimeContextFromEnv as loadRuntimeContextFromEnv2 } from "@rig/runtime/control-plane/runtime/context";
70
-
71
- // packages/cli/src/commands/_parsers.ts
72
- function parsePositiveInt(value, option, fallback) {
73
- if (!value) {
74
- return fallback;
75
- }
76
- const parsed = Number.parseInt(value, 10);
77
- if (!Number.isFinite(parsed) || parsed <= 0) {
78
- throw new CliError2(`Invalid ${option} value: ${value}`);
79
- }
80
- return parsed;
81
- }
82
-
83
- // packages/cli/src/commands/_server-client.ts
84
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
85
- import { resolve as resolve2 } from "path";
86
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
87
-
88
- // packages/cli/src/commands/_connection-state.ts
89
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
90
- import { homedir } from "os";
91
- import { dirname, resolve } from "path";
92
- function resolveGlobalConnectionsPath(env = process.env) {
93
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
94
- if (explicit)
95
- return resolve(explicit);
96
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
97
- if (stateDir)
98
- return resolve(stateDir, "connections.json");
99
- return resolve(homedir(), ".rig", "connections.json");
100
- }
101
- function resolveRepoConnectionPath(projectRoot) {
102
- return resolve(projectRoot, ".rig", "state", "connection.json");
103
- }
104
- function readJsonFile(path) {
105
- if (!existsSync(path))
106
- return null;
107
- try {
108
- return JSON.parse(readFileSync(path, "utf8"));
109
- } catch (error) {
110
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
111
- }
112
- }
113
- function normalizeConnection(value) {
114
- if (!value || typeof value !== "object" || Array.isArray(value))
115
- return null;
116
- const record = value;
117
- if (record.kind === "local")
118
- return { kind: "local", mode: "auto" };
119
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
120
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
121
- return { kind: "remote", baseUrl };
122
- }
123
- return null;
124
- }
125
- function readGlobalConnections(options = {}) {
126
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
127
- const payload = readJsonFile(path);
128
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
129
- return { connections: {} };
130
- }
131
- const rawConnections = payload.connections;
132
- const connections = {};
133
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
134
- for (const [alias, raw] of Object.entries(rawConnections)) {
135
- const connection = normalizeConnection(raw);
136
- if (connection)
137
- connections[alias] = connection;
138
- }
139
- }
140
- return { connections };
141
- }
142
- function readRepoConnection(projectRoot) {
143
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
144
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
145
- return null;
146
- const record = payload;
147
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
148
- if (!selected)
149
- return null;
150
- return {
151
- selected,
152
- project: typeof record.project === "string" ? record.project : undefined,
153
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
154
- };
155
- }
156
- function resolveSelectedConnection(projectRoot, options = {}) {
157
- const repo = readRepoConnection(projectRoot);
158
- if (!repo)
159
- return null;
160
- if (repo.selected === "local")
161
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
162
- const global = readGlobalConnections(options);
163
- const connection = global.connections[repo.selected];
164
- if (!connection) {
165
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
166
- }
167
- return { alias: repo.selected, connection };
168
- }
169
-
170
- // packages/cli/src/commands/_server-client.ts
171
- var scopedGitHubBearerTokens = new Map;
172
- function cleanToken(value) {
173
- const trimmed = value?.trim();
174
- return trimmed ? trimmed : null;
175
- }
176
- function readPrivateRemoteSessionToken(projectRoot) {
177
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
178
- if (!existsSync2(path))
179
- return null;
180
- try {
181
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
182
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
183
- } catch {
184
- return null;
185
- }
186
- }
187
- function readGitHubBearerTokenForRemote(projectRoot) {
188
- const scopedKey = resolve2(projectRoot);
189
- if (scopedGitHubBearerTokens.has(scopedKey))
190
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
191
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
192
- if (privateSession)
193
- return privateSession;
194
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
195
- }
196
- async function ensureServerForCli(projectRoot) {
197
- try {
198
- const selected = resolveSelectedConnection(projectRoot);
199
- if (selected?.connection.kind === "remote") {
200
- return {
201
- baseUrl: selected.connection.baseUrl,
202
- authToken: readGitHubBearerTokenForRemote(projectRoot),
203
- connectionKind: "remote"
204
- };
205
- }
206
- const connection = await ensureLocalRigServerConnection(projectRoot);
207
- return {
208
- baseUrl: connection.baseUrl,
209
- authToken: connection.authToken,
210
- connectionKind: "local"
211
- };
212
- } catch (error) {
213
- if (error instanceof Error) {
214
- throw new CliError2(error.message, 1);
215
- }
216
- throw error;
217
- }
218
- }
219
- function mergeHeaders(headers, authToken) {
220
- const merged = new Headers(headers);
221
- if (authToken) {
222
- merged.set("authorization", `Bearer ${authToken}`);
223
- }
224
- return merged;
225
- }
226
- function diagnosticMessage(payload) {
227
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
228
- return null;
229
- const record = payload;
230
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
231
- const messages = diagnostics.flatMap((entry) => {
232
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
233
- return [];
234
- const diagnostic = entry;
235
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
236
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
237
- return message ? [`${kind}: ${message}`] : [];
238
- });
239
- return messages.length > 0 ? messages.join("; ") : null;
240
- }
241
- async function requestServerJson(context, pathname, init = {}) {
242
- const server = await ensureServerForCli(context.projectRoot);
243
- const response = await fetch(`${server.baseUrl}${pathname}`, {
244
- ...init,
245
- headers: mergeHeaders(init.headers, server.authToken)
246
- });
247
- const text = await response.text();
248
- const payload = text.trim().length > 0 ? (() => {
249
- try {
250
- return JSON.parse(text);
251
- } catch {
252
- return null;
253
- }
254
- })() : null;
255
- if (!response.ok) {
256
- const diagnostics = diagnosticMessage(payload);
257
- const detail = diagnostics ?? (text || response.statusText);
258
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
259
- }
260
- return payload;
261
- }
262
- async function getRunDetailsViaServer(context, runId) {
263
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
264
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
265
- }
266
- async function getRunLogsViaServer(context, runId, options = {}) {
267
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
268
- if (options.limit !== undefined)
269
- url.searchParams.set("limit", String(options.limit));
270
- if (options.cursor)
271
- url.searchParams.set("cursor", options.cursor);
272
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
273
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
274
- }
275
- async function getRunTimelineViaServer(context, runId, options = {}) {
276
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
277
- if (options.limit !== undefined)
278
- url.searchParams.set("limit", String(options.limit));
279
- if (options.cursor)
280
- url.searchParams.set("cursor", options.cursor);
281
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
282
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
283
- }
284
- async function stopRunViaServer(context, runId) {
285
- const payload = await requestServerJson(context, "/api/runs/stop", {
286
- method: "POST",
287
- headers: { "content-type": "application/json" },
288
- body: JSON.stringify({ runId })
289
- });
290
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
291
- }
292
- async function steerRunViaServer(context, runId, message) {
293
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
294
- method: "POST",
295
- headers: { "content-type": "application/json" },
296
- body: JSON.stringify({ message })
297
- });
298
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
299
- }
300
-
301
- // packages/cli/src/commands/_operator-surface.ts
302
- import { createInterface } from "readline";
303
- var CANONICAL_STAGES = [
304
- "Connect",
305
- "GitHub/task sync",
306
- "Prepare workspace",
307
- "Launch Pi",
308
- "Plan",
309
- "Implement",
310
- "Validate",
311
- "Commit",
312
- "Open PR",
313
- "Review/CI",
314
- "Merge",
315
- "Complete"
316
- ];
317
- function logDetail(log) {
318
- return typeof log.detail === "string" ? log.detail.trim() : "";
319
- }
320
- function entryId(entry, fallback) {
321
- return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
322
- }
323
- function renderOperatorSnapshot(snapshot) {
324
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
325
- const runId = String(run.runId ?? run.id ?? "run");
326
- const status = String(run.status ?? "unknown");
327
- const logs = snapshot.logs ?? [];
328
- const latestByStage = new Map;
329
- for (const log of logs) {
330
- const title = String(log.title ?? "").toLowerCase();
331
- const stageName = String(log.stage ?? "").toLowerCase();
332
- const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
333
- if (stage)
334
- latestByStage.set(stage, log);
335
- }
336
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
337
- const match = latestByStage.get(stage);
338
- return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
339
- });
340
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
341
- `);
342
- }
343
- function createPiRunStreamRenderer(output = process.stdout) {
344
- let lastSnapshot = "";
345
- const assistantTextById = new Map;
346
- const seenTimeline = new Set;
347
- const seenLogs = new Set;
348
- const writeLine = (line) => output.write(`${line}
349
- `);
350
- return {
351
- renderSnapshot(snapshot) {
352
- const rendered = renderOperatorSnapshot(snapshot);
353
- if (rendered && rendered !== lastSnapshot) {
354
- writeLine(rendered);
355
- lastSnapshot = rendered;
356
- }
357
- },
358
- renderTimeline(entries) {
359
- for (const [index, entry] of entries.entries()) {
360
- const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
361
- if (entry.type === "assistant_message" && typeof entry.text === "string") {
362
- const text = entry.text;
363
- const previousText = assistantTextById.get(id) ?? "";
364
- if (text.startsWith(previousText)) {
365
- const delta = text.slice(previousText.length);
366
- if (delta)
367
- output.write(delta);
368
- } else if (text.trim() && text !== previousText) {
369
- writeLine(`
370
- [Pi assistant]`);
371
- output.write(text);
372
- }
373
- assistantTextById.set(id, text);
374
- continue;
375
- }
376
- if (seenTimeline.has(id))
377
- continue;
378
- seenTimeline.add(id);
379
- if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
380
- writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
381
- continue;
382
- }
383
- if (entry.type === "timeline_warning") {
384
- writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
385
- }
386
- }
387
- },
388
- renderLogs(entries) {
389
- for (const [index, entry] of entries.entries()) {
390
- const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
391
- if (seenLogs.has(id))
392
- continue;
393
- seenLogs.add(id);
394
- const title = String(entry.title ?? "");
395
- if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
396
- continue;
397
- const detail = logDetail(entry);
398
- if (!detail)
399
- continue;
400
- writeLine(`[${title || "Rig log"}] ${detail}`);
401
- }
402
- }
403
- };
404
- }
405
- function createOperatorSurface(options = {}) {
406
- const input = options.input ?? process.stdin;
407
- const output = options.output ?? process.stdout;
408
- const errorOutput = options.errorOutput ?? process.stderr;
409
- const renderer = createPiRunStreamRenderer(output);
410
- const writeLine = (line) => output.write(`${line}
411
- `);
412
- return {
413
- mode: "pi-compatible-text",
414
- ...renderer,
415
- info: writeLine,
416
- error: (message) => errorOutput.write(`${message}
417
- `),
418
- attachCommandInput(handler) {
419
- if (options.interactive === false || !input.isTTY)
420
- return null;
421
- const rl = createInterface({ input, output: process.stdout, terminal: false });
422
- rl.on("line", (line) => {
423
- Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
424
- });
425
- return { close: () => rl.close() };
426
- }
427
- };
428
- }
429
-
430
- // packages/cli/src/commands/_operator-view.ts
431
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
432
- function runStatusFromPayload(payload) {
433
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
434
- return String(run.status ?? "unknown").toLowerCase();
435
- }
436
- async function applyOperatorCommand(context, input, deps = {}) {
437
- const line = input.line.trim();
438
- if (!line)
439
- return { action: "ignored" };
440
- if (line === "/detach" || line === "/quit" || line === "/q") {
441
- return { action: "detach", message: "Detached from run." };
442
- }
443
- if (line === "/stop") {
444
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
445
- return { action: "stopped", message: "Stop requested." };
446
- }
447
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
448
- if (!userMessage)
449
- return { action: "ignored" };
450
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
451
- return { action: "continue", message: "Steering message queued." };
452
- }
453
- async function readOperatorSnapshot(context, runId, options = {}) {
454
- const run = await getRunDetailsViaServer(context, runId);
455
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
456
- const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
457
- entries: [{
458
- id: `timeline-unavailable:${runId}`,
459
- type: "timeline_warning",
460
- detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
461
- createdAt: new Date().toISOString()
462
- }],
463
- nextCursor: options.timelineCursor ?? null
464
- }));
465
- const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
466
- const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
467
- const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
468
- return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
469
- }
470
- async function attachRunOperatorView(context, input) {
471
- let steered = false;
472
- if (input.message?.trim()) {
473
- await steerRunViaServer(context, input.runId, input.message.trim());
474
- steered = true;
475
- }
476
- const surface = createOperatorSurface({ interactive: input.interactive !== false });
477
- let snapshot = await readOperatorSnapshot(context, input.runId);
478
- if (context.outputMode === "text") {
479
- surface.renderSnapshot(snapshot);
480
- surface.renderTimeline(snapshot.timeline);
481
- surface.renderLogs(snapshot.logs);
482
- if (steered)
483
- surface.info("Steering message queued.");
484
- }
485
- let detached = false;
486
- let commandInput = null;
487
- if (input.follow && !input.once && context.outputMode === "text") {
488
- if (input.interactive !== false && process.stdin.isTTY) {
489
- surface.info("Controls: /user <message>, /stop, /detach");
490
- commandInput = surface.attachCommandInput(async (line) => {
491
- const result = await applyOperatorCommand(context, { runId: input.runId, line });
492
- if (result.message)
493
- surface.info(result.message);
494
- if (result.action === "detach" || result.action === "stopped") {
495
- detached = true;
496
- commandInput?.close();
497
- }
498
- });
499
- }
500
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
501
- let timelineCursor = snapshot.timelineCursor;
502
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
503
- await Bun.sleep(pollMs);
504
- snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
505
- timelineCursor = snapshot.timelineCursor;
506
- surface.renderSnapshot(snapshot);
507
- surface.renderTimeline(snapshot.timeline);
508
- surface.renderLogs(snapshot.logs);
509
- }
510
- commandInput?.close();
511
- }
512
- return { ...snapshot, steered, detached };
513
- }
514
-
515
- // packages/cli/src/commands/run.ts
516
- function normalizeRemoteRunDetails(payload) {
517
- const run = payload.run;
518
- if (!run || typeof run !== "object" || Array.isArray(run))
519
- return null;
520
- return {
521
- ...run,
522
- ...Array.isArray(payload.timeline) ? { timeline: payload.timeline } : {},
523
- ...Array.isArray(payload.approvals) ? { approvals: payload.approvals } : {},
524
- ...Array.isArray(payload.userInputs) ? { userInputs: payload.userInputs } : {}
525
- };
526
- }
527
- function shouldPromptForEpicSelection(context, command, promptEpic, noEpicPrompt) {
528
- if (noEpicPrompt) {
529
- return false;
530
- }
531
- if (promptEpic) {
532
- return true;
533
- }
534
- if (command !== "start-serial") {
535
- return false;
536
- }
537
- return context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY;
538
- }
539
- async function promptForEpicSelection(projectRoot, command) {
540
- const epics = listOpenEpics(projectRoot);
541
- const defaultEpic = await resolveDefaultEpic(projectRoot);
542
- const options = epics.map((epic) => epic.id);
543
- if (defaultEpic && !options.includes(defaultEpic)) {
544
- options.unshift(defaultEpic);
545
- }
546
- if (options.length === 0) {
547
- throw new CliError2("No open epic found. Pass --epic <id>.");
548
- }
549
- console.log(`Select epic for run ${command}:`);
550
- options.forEach((id, index) => {
551
- const metadata = epics.find((epic) => epic.id === id);
552
- const details = [
553
- metadata?.priority !== undefined ? `priority:${metadata.priority}` : "",
554
- metadata?.createdAt ? `created:${metadata.createdAt.slice(0, 10)}` : "",
555
- id === defaultEpic ? "default" : ""
556
- ].filter(Boolean).join(" ");
557
- const suffix = details ? ` (${details})` : "";
558
- console.log(` ${index + 1}. ${id}${suffix}`);
559
- });
560
- const fallback = defaultEpic || options[0];
561
- const rl = createInterface2({ input: process.stdin, output: process.stdout });
562
- try {
563
- while (true) {
564
- const answer = (await rl.question(`Epic [1-${options.length}] or id (Enter for ${fallback}, q to cancel): `)).trim();
565
- if (!answer) {
566
- return fallback ?? options[0];
567
- }
568
- if (answer === "q" || answer === "quit") {
569
- throw new CliError2("Run cancelled by user.");
570
- }
571
- if (/^\d+$/.test(answer)) {
572
- const index = Number.parseInt(answer, 10) - 1;
573
- if (index >= 0 && index < options.length) {
574
- return options[index];
575
- }
576
- }
577
- if (options.includes(answer)) {
578
- return answer;
579
- }
580
- console.log("Invalid selection. Choose a listed number, exact epic id, or q to cancel.");
581
- }
582
- } finally {
583
- rl.close();
584
- }
585
- }
586
- async function executeRun(context, args) {
587
- const [command = "status", ...rest] = args;
588
- const runtimeContext = loadRuntimeContextFromEnv2() ?? undefined;
589
- switch (command) {
590
- case "list": {
591
- requireNoExtraArgs(rest, "bun run rig run list");
592
- const runs = listAuthorityRuns(context.projectRoot);
593
- if (context.outputMode === "text") {
594
- if (runs.length === 0) {
595
- console.log("No runs recorded in .rig/runs.");
596
- } else {
597
- for (const run of runs) {
598
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.title}`);
599
- }
600
- }
601
- }
602
- return { ok: true, group: "run", command, details: { runs } };
603
- }
604
- case "delete": {
605
- let pending = rest;
606
- const run = takeOption(pending, "--run");
607
- pending = run.rest;
608
- const purgeArtifacts = takeFlag(pending, "--purge-artifacts");
609
- pending = purgeArtifacts.rest;
610
- requireNoExtraArgs(pending, "bun run rig run delete --run <id> [--purge-artifacts]");
611
- if (!run.value) {
612
- throw new CliError2("run delete requires --run <id>.");
613
- }
614
- const result = await deleteRunState(context.projectRoot, {
615
- runId: run.value,
616
- purgeRuntime: true,
617
- purgeTaskArtifacts: purgeArtifacts.value
618
- });
619
- if (context.outputMode === "text") {
620
- console.log(`Deleted run ${result.runId}`);
621
- if (result.runtimeIds.length > 0) {
622
- console.log(`Cleaned runtimes: ${result.runtimeIds.join(", ")}`);
623
- }
624
- if (result.taskArtifactsDeleted) {
625
- console.log(`Cleared task artifacts for ${result.taskId}`);
626
- }
627
- }
628
- return { ok: true, group: "run", command, details: result };
629
- }
630
- case "cleanup": {
631
- let pending = rest;
632
- const all = takeFlag(pending, "--all");
633
- pending = all.rest;
634
- const keepArtifacts = takeFlag(pending, "--keep-artifacts");
635
- pending = keepArtifacts.rest;
636
- const keepRuntimes = takeFlag(pending, "--keep-runtimes");
637
- pending = keepRuntimes.rest;
638
- const keepQueue = takeFlag(pending, "--keep-queue");
639
- pending = keepQueue.rest;
640
- requireNoExtraArgs(pending, "bun run rig run cleanup --all [--keep-artifacts] [--keep-runtimes] [--keep-queue]");
641
- if (!all.value) {
642
- throw new CliError2("run cleanup currently requires --all.");
643
- }
644
- const result = await cleanupRunState(context.projectRoot, {
645
- includeArtifacts: !keepArtifacts.value,
646
- includeRuntimes: !keepRuntimes.value,
647
- includeQueue: !keepQueue.value
648
- });
649
- if (context.outputMode === "text") {
650
- console.log(`Deleted runs: ${result.runIds.length}`);
651
- console.log(`Cleaned runtimes: ${result.runtimeIds.length}`);
652
- console.log(`Artifacts cleared: ${result.artifactsCleared ? "yes" : "no"}`);
653
- console.log(`Queue cleared: ${result.queueCleared ? "yes" : "no"}`);
654
- }
655
- return { ok: true, group: "run", command, details: result };
656
- }
657
- case "show": {
658
- let pending = rest;
659
- const run = takeOption(pending, "--run");
660
- pending = run.rest;
661
- requireNoExtraArgs(pending, "bun run rig run show --run <id>");
662
- if (!run.value) {
663
- throw new CliError2("run show requires --run <id>.");
664
- }
665
- const record = readAuthorityRun(context.projectRoot, run.value) ?? normalizeRemoteRunDetails(await getRunDetailsViaServer(context, run.value).catch(() => ({})));
666
- if (!record) {
667
- throw new CliError2(`Run not found: ${run.value}`, 2);
668
- }
669
- if (context.outputMode === "text") {
670
- console.log(JSON.stringify(record, null, 2));
671
- }
672
- return { ok: true, group: "run", command, details: record };
673
- }
674
- case "timeline": {
675
- let pending = rest;
676
- const run = takeOption(pending, "--run");
677
- pending = run.rest;
678
- const follow = takeFlag(pending, "--follow");
679
- pending = follow.rest;
680
- requireNoExtraArgs(pending, "bun run rig run timeline --run <id> [--follow]");
681
- if (!run.value) {
682
- throw new CliError2("run timeline requires --run <id>.");
683
- }
684
- const renderer = createPiRunStreamRenderer();
685
- let cursor = null;
686
- const page = await getRunTimelineViaServer(context, run.value, { limit: 500 });
687
- const events = Array.isArray(page.entries) ? page.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
688
- cursor = typeof page.nextCursor === "string" ? page.nextCursor : null;
689
- if (context.outputMode === "text") {
690
- renderer.renderTimeline(events);
691
- }
692
- if (follow.value && context.outputMode === "text") {
693
- while (true) {
694
- await Bun.sleep(1000);
695
- const nextPage = await getRunTimelineViaServer(context, run.value, { limit: 500, ...cursor ? { cursor } : {} });
696
- const nextEvents = Array.isArray(nextPage.entries) ? nextPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
697
- cursor = typeof nextPage.nextCursor === "string" ? nextPage.nextCursor : cursor;
698
- renderer.renderTimeline(nextEvents);
699
- }
700
- }
701
- return { ok: true, group: "run", command, details: { runId: run.value, events, cursor } };
702
- }
703
- case "attach": {
704
- let pending = rest;
705
- const runOption = takeOption(pending, "--run");
706
- pending = runOption.rest;
707
- const messageOption = takeOption(pending, "--message");
708
- pending = messageOption.rest;
709
- const once = takeFlag(pending, "--once");
710
- pending = once.rest;
711
- const follow = takeFlag(pending, "--follow");
712
- pending = follow.rest;
713
- const pollMs = takeOption(pending, "--poll-ms");
714
- pending = pollMs.rest;
715
- const positionalRunId = pending.length > 0 ? pending[0] : undefined;
716
- const extra = positionalRunId ? pending.slice(1) : pending;
717
- requireNoExtraArgs(extra, "bun run rig run attach <run-id>|--run <run-id> [--message <text>] [--once|--follow] [--poll-ms <ms>]");
718
- const runId = runOption.value ?? positionalRunId;
719
- if (!runId) {
720
- throw new CliError2("run attach requires a run id.", 2);
721
- }
722
- const attached = await attachRunOperatorView(context, {
723
- runId,
724
- message: messageOption.value ?? null,
725
- once: once.value,
726
- follow: follow.value,
727
- pollMs: parsePositiveInt(pollMs.value, "--poll-ms", 2000)
728
- });
729
- return { ok: true, group: "run", command, details: attached };
730
- }
731
- case "status": {
732
- requireNoExtraArgs(rest, "bun run rig run status");
733
- if (context.dryRun) {
734
- if (context.outputMode === "text") {
735
- console.log("[dry-run] rig run status");
736
- }
737
- return { ok: true, group: "run", command };
738
- }
739
- const summary = runStatus(context.projectRoot, runtimeContext);
740
- if (context.outputMode === "text") {
741
- console.log(`Active runs: ${summary.activeRuns.length}`);
742
- for (const run of summary.activeRuns) {
743
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.taskId ?? run.title}`);
744
- }
745
- if (summary.recentRuns.length > 0) {
746
- console.log("");
747
- console.log("Recent runs:");
748
- for (const run of summary.recentRuns) {
749
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.taskId ?? run.title}`);
750
- }
751
- }
752
- }
753
- return { ok: true, group: "run", command, details: summary };
754
- }
755
- case "start":
756
- case "start-serial":
757
- case "start-parallel": {
758
- let pending = rest;
759
- const epicResult = takeOption(pending, "--epic");
760
- pending = epicResult.rest;
761
- const promptEpicResult = takeFlag(pending, "--prompt-epic");
762
- pending = promptEpicResult.rest;
763
- const noEpicPromptResult = takeFlag(pending, "--no-epic-prompt");
764
- pending = noEpicPromptResult.rest;
765
- const wsPortResult = takeOption(pending, "--ws-port");
766
- pending = wsPortResult.rest;
767
- const serverHostResult = takeOption(pending, "--server-host");
768
- pending = serverHostResult.rest;
769
- const serverPortResult = takeOption(pending, "--server-port");
770
- pending = serverPortResult.rest;
771
- const pollResult = takeOption(pending, "--poll-ms");
772
- pending = pollResult.rest;
773
- const noServerResult = takeFlag(pending, "--no-server");
774
- pending = noServerResult.rest;
775
- requireNoExtraArgs(pending, "bun run rig run start [--epic <id>] [--prompt-epic|--no-epic-prompt] [--ws-port <n>] [--server-host <host>] [--server-port <n>] [--poll-ms <n>] [--no-server]");
776
- if (promptEpicResult.value && noEpicPromptResult.value) {
777
- throw new CliError2("Cannot use --prompt-epic and --no-epic-prompt together.");
778
- }
779
- if (promptEpicResult.value && (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY)) {
780
- throw new CliError2("--prompt-epic requires an interactive terminal (TTY) in text mode.");
781
- }
782
- let resolvedEpicId = epicResult.value || undefined;
783
- if (!resolvedEpicId && shouldPromptForEpicSelection(context, command, promptEpicResult.value, noEpicPromptResult.value)) {
784
- resolvedEpicId = await promptForEpicSelection(context.projectRoot, command);
785
- }
786
- const defaults = defaultStartRunOptions(command === "start-parallel" ? "parallel" : "serial");
787
- const result = await startRun(context.projectRoot, {
788
- mode: command === "start-parallel" ? "parallel" : "serial",
789
- workers: defaults.workers,
790
- epicId: resolvedEpicId,
791
- wsPort: parsePositiveInt(wsPortResult.value, "--ws-port", defaults.wsPort),
792
- startEventServer: noServerResult.value ? false : defaults.startEventServer,
793
- serverHost: serverHostResult.value || defaults.serverHost,
794
- serverPort: parsePositiveInt(serverPortResult.value, "--server-port", defaults.serverPort),
795
- serverPollMs: parsePositiveInt(pollResult.value, "--poll-ms", defaults.serverPollMs),
796
- dryRun: context.dryRun,
797
- runtimeContext
798
- });
799
- if (context.outputMode === "text") {
800
- console.log(`Epic: ${result.epicId}`);
801
- console.log(`Server: ${result.baseUrl}`);
802
- if (result.eventServerUrl) {
803
- console.log(`Events: ${result.eventServerUrl}`);
804
- }
805
- console.log(`Runs: ${result.runIds.join(", ")}`);
806
- }
807
- if (result.exitCode !== 0) {
808
- throw new CliError2(`run ${command} failed with exit code ${result.exitCode}.`, result.exitCode);
809
- }
810
- return {
811
- ok: true,
812
- group: "run",
813
- command,
814
- details: {
815
- epicId: result.epicId,
816
- baseUrl: result.baseUrl,
817
- runIds: result.runIds,
818
- eventServerUrl: result.eventServerUrl || null
819
- }
820
- };
821
- }
822
- case "resume": {
823
- requireNoExtraArgs(rest, "bun run rig run resume");
824
- if (context.dryRun) {
825
- if (context.outputMode === "text") {
826
- console.log("[dry-run] rig run resume");
827
- }
828
- return { ok: true, group: "run", command };
829
- }
830
- const resumed = await runResume(context.projectRoot, runtimeContext);
831
- if (context.outputMode === "text") {
832
- console.log(`Resumed run: ${resumed.runId}`);
833
- }
834
- return { ok: true, group: "run", command, details: resumed };
835
- }
836
- case "restart": {
837
- requireNoExtraArgs(rest, "bun run rig run restart");
838
- if (context.dryRun) {
839
- if (context.outputMode === "text") {
840
- console.log("[dry-run] rig run restart");
841
- }
842
- return { ok: true, group: "run", command };
843
- }
844
- const restarted = await runRestart(context.projectRoot, runtimeContext);
845
- if (context.outputMode === "text") {
846
- console.log(`Restarted run: ${restarted.runId}`);
847
- }
848
- return { ok: true, group: "run", command, details: restarted };
849
- }
850
- case "stop": {
851
- const runOption = takeOption(rest, "--run");
852
- const positionalRunId = runOption.rest.length > 0 ? runOption.rest[0] : undefined;
853
- const extra = positionalRunId ? runOption.rest.slice(1) : runOption.rest;
854
- requireNoExtraArgs(extra, "bun run rig run stop [<run-id>|--run <id>]");
855
- const runId = runOption.value ?? positionalRunId;
856
- if (context.dryRun) {
857
- return {
858
- ok: true,
859
- group: "run",
860
- command,
861
- details: runId ? { runId, accepted: true } : { stopped: 0, remaining: [] }
862
- };
863
- }
864
- if (runId) {
865
- const stopped = await stopRunViaServer(context, runId);
866
- if (context.outputMode === "text")
867
- console.log(`Stop requested: ${runId}`);
868
- return { ok: true, group: "run", command, details: stopped };
869
- }
870
- const result = await runStop(context.projectRoot);
871
- if (result.remaining.length > 0) {
872
- throw new CliError2(`Failed to stop run(s): ${result.remaining.join(", ")}`, 1);
873
- }
874
- if (context.outputMode === "text") {
875
- console.log(`Stopped process count: ${result.stopped}`);
876
- }
877
- return {
878
- ok: true,
879
- group: "run",
880
- command,
881
- details: {
882
- stopped: result.stopped,
883
- remaining: result.remaining
884
- }
885
- };
886
- }
887
- default:
888
- throw new CliError2(`Unknown run command: ${command}`);
889
- }
890
- }
891
- export {
892
- executeRun
893
- };