@h-rig/cli 0.0.6-alpha.22 → 0.0.6-alpha.220

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/package.json +9 -29
  3. package/dist/bin/build-rig-binaries.js +0 -107
  4. package/dist/bin/rig.js +0 -10655
  5. package/dist/src/commands/_authority-runs.js +0 -111
  6. package/dist/src/commands/_cli-format.js +0 -106
  7. package/dist/src/commands/_connection-state.js +0 -123
  8. package/dist/src/commands/_doctor-checks.js +0 -507
  9. package/dist/src/commands/_operator-surface.js +0 -204
  10. package/dist/src/commands/_operator-view.js +0 -731
  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 -185
  14. package/dist/src/commands/_policy.js +0 -79
  15. package/dist/src/commands/_preflight.js +0 -483
  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 -435
  19. package/dist/src/commands/_snapshot-upload.js +0 -318
  20. package/dist/src/commands/_task-picker.js +0 -76
  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 -517
  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 -1563
  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 -1258
  37. package/dist/src/commands/server.js +0 -373
  38. package/dist/src/commands/setup.js +0 -687
  39. package/dist/src/commands/task-report-bug.js +0 -1083
  40. package/dist/src/commands/task-run-driver.js +0 -2554
  41. package/dist/src/commands/task.js +0 -1842
  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 -10334
  45. package/dist/src/index.js +0 -10673
  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,1258 +0,0 @@
1
- // @bun
2
- var __require = import.meta.require;
3
-
4
- // packages/cli/src/commands/run.ts
5
- import { createInterface as createInterface2 } from "readline/promises";
6
-
7
- // packages/cli/src/runner.ts
8
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
9
- import { CliError } from "@rig/runtime/control-plane/errors";
10
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
11
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
12
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
13
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
14
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
15
- function takeFlag(args, flag) {
16
- const rest = [];
17
- let value = false;
18
- for (const arg of args) {
19
- if (arg === flag) {
20
- value = true;
21
- continue;
22
- }
23
- rest.push(arg);
24
- }
25
- return { value, rest };
26
- }
27
- function takeOption(args, option) {
28
- const rest = [];
29
- let value;
30
- for (let index = 0;index < args.length; index += 1) {
31
- const current = args[index];
32
- if (current === option) {
33
- const next = args[index + 1];
34
- if (!next || next.startsWith("-")) {
35
- throw new CliError(`Missing value for ${option}`);
36
- }
37
- value = next;
38
- index += 1;
39
- continue;
40
- }
41
- if (current !== undefined) {
42
- rest.push(current);
43
- }
44
- }
45
- return { value, rest };
46
- }
47
- function requireNoExtraArgs(args, usage) {
48
- if (args.length > 0) {
49
- throw new CliError(`Unexpected arguments: ${args.join(" ")}
50
- Usage: ${usage}`);
51
- }
52
- }
53
-
54
- // packages/cli/src/commands/run.ts
55
- import {
56
- listAuthorityRuns,
57
- readAuthorityRun
58
- } from "@rig/runtime/control-plane/authority-files";
59
- import {
60
- cleanupRunState,
61
- deleteRunState,
62
- listOpenEpics,
63
- resolveDefaultEpic,
64
- runResume,
65
- runRestart,
66
- runStatus,
67
- runStop,
68
- startRun,
69
- defaultStartRunOptions
70
- } from "@rig/runtime/control-plane/native/run-ops";
71
- import { loadRuntimeContextFromEnv as loadRuntimeContextFromEnv2 } from "@rig/runtime/control-plane/runtime/context";
72
-
73
- // packages/cli/src/commands/_parsers.ts
74
- function parsePositiveInt(value, option, fallback) {
75
- if (!value) {
76
- return fallback;
77
- }
78
- const parsed = Number.parseInt(value, 10);
79
- if (!Number.isFinite(parsed) || parsed <= 0) {
80
- throw new CliError2(`Invalid ${option} value: ${value}`);
81
- }
82
- return parsed;
83
- }
84
-
85
- // packages/cli/src/commands/_server-client.ts
86
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
87
- import { resolve as resolve2 } from "path";
88
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
89
-
90
- // packages/cli/src/commands/_connection-state.ts
91
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
92
- import { homedir } from "os";
93
- import { dirname, resolve } from "path";
94
- function resolveGlobalConnectionsPath(env = process.env) {
95
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
96
- if (explicit)
97
- return resolve(explicit);
98
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
99
- if (stateDir)
100
- return resolve(stateDir, "connections.json");
101
- return resolve(homedir(), ".rig", "connections.json");
102
- }
103
- function resolveRepoConnectionPath(projectRoot) {
104
- return resolve(projectRoot, ".rig", "state", "connection.json");
105
- }
106
- function readJsonFile(path) {
107
- if (!existsSync(path))
108
- return null;
109
- try {
110
- return JSON.parse(readFileSync(path, "utf8"));
111
- } catch (error) {
112
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
113
- }
114
- }
115
- function normalizeConnection(value) {
116
- if (!value || typeof value !== "object" || Array.isArray(value))
117
- return null;
118
- const record = value;
119
- if (record.kind === "local")
120
- return { kind: "local", mode: "auto" };
121
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
122
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
123
- return { kind: "remote", baseUrl };
124
- }
125
- return null;
126
- }
127
- function readGlobalConnections(options = {}) {
128
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
129
- const payload = readJsonFile(path);
130
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
131
- return { connections: {} };
132
- }
133
- const rawConnections = payload.connections;
134
- const connections = {};
135
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
136
- for (const [alias, raw] of Object.entries(rawConnections)) {
137
- const connection = normalizeConnection(raw);
138
- if (connection)
139
- connections[alias] = connection;
140
- }
141
- }
142
- return { connections };
143
- }
144
- function readRepoConnection(projectRoot) {
145
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
146
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
147
- return null;
148
- const record = payload;
149
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
150
- if (!selected)
151
- return null;
152
- return {
153
- selected,
154
- project: typeof record.project === "string" ? record.project : undefined,
155
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
156
- };
157
- }
158
- function resolveSelectedConnection(projectRoot, options = {}) {
159
- const repo = readRepoConnection(projectRoot);
160
- if (!repo)
161
- return null;
162
- if (repo.selected === "local")
163
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
164
- const global = readGlobalConnections(options);
165
- const connection = global.connections[repo.selected];
166
- if (!connection) {
167
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
168
- }
169
- return { alias: repo.selected, connection };
170
- }
171
-
172
- // packages/cli/src/commands/_server-client.ts
173
- var scopedGitHubBearerTokens = new Map;
174
- function cleanToken(value) {
175
- const trimmed = value?.trim();
176
- return trimmed ? trimmed : null;
177
- }
178
- function readPrivateRemoteSessionToken(projectRoot) {
179
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
180
- if (!existsSync2(path))
181
- return null;
182
- try {
183
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
184
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
185
- } catch {
186
- return null;
187
- }
188
- }
189
- function readGitHubBearerTokenForRemote(projectRoot) {
190
- const scopedKey = resolve2(projectRoot);
191
- if (scopedGitHubBearerTokens.has(scopedKey))
192
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
193
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
194
- if (privateSession)
195
- return privateSession;
196
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
197
- }
198
- async function ensureServerForCli(projectRoot) {
199
- try {
200
- const selected = resolveSelectedConnection(projectRoot);
201
- if (selected?.connection.kind === "remote") {
202
- return {
203
- baseUrl: selected.connection.baseUrl,
204
- authToken: readGitHubBearerTokenForRemote(projectRoot),
205
- connectionKind: "remote"
206
- };
207
- }
208
- const connection = await ensureLocalRigServerConnection(projectRoot);
209
- return {
210
- baseUrl: connection.baseUrl,
211
- authToken: connection.authToken,
212
- connectionKind: "local"
213
- };
214
- } catch (error) {
215
- if (error instanceof Error) {
216
- throw new CliError2(error.message, 1);
217
- }
218
- throw error;
219
- }
220
- }
221
- function mergeHeaders(headers, authToken) {
222
- const merged = new Headers(headers);
223
- if (authToken) {
224
- merged.set("authorization", `Bearer ${authToken}`);
225
- }
226
- return merged;
227
- }
228
- function diagnosticMessage(payload) {
229
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
230
- return null;
231
- const record = payload;
232
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
233
- const messages = diagnostics.flatMap((entry) => {
234
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
235
- return [];
236
- const diagnostic = entry;
237
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
238
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
239
- return message ? [`${kind}: ${message}`] : [];
240
- });
241
- return messages.length > 0 ? messages.join("; ") : null;
242
- }
243
- async function requestServerJson(context, pathname, init = {}) {
244
- const server = await ensureServerForCli(context.projectRoot);
245
- const response = await fetch(`${server.baseUrl}${pathname}`, {
246
- ...init,
247
- headers: mergeHeaders(init.headers, server.authToken)
248
- });
249
- const text = await response.text();
250
- const payload = text.trim().length > 0 ? (() => {
251
- try {
252
- return JSON.parse(text);
253
- } catch {
254
- return null;
255
- }
256
- })() : null;
257
- if (!response.ok) {
258
- const diagnostics = diagnosticMessage(payload);
259
- const detail = diagnostics ?? (text || response.statusText);
260
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
261
- }
262
- return payload;
263
- }
264
- async function listRunsViaServer(context, options = {}) {
265
- const url = new URL("http://rig.local/api/runs");
266
- if (options.limit !== undefined)
267
- url.searchParams.set("limit", String(options.limit));
268
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
269
- const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
270
- return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
271
- }
272
- async function getRunDetailsViaServer(context, runId) {
273
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
274
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
275
- }
276
- async function getRunLogsViaServer(context, runId, options = {}) {
277
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
278
- if (options.limit !== undefined)
279
- url.searchParams.set("limit", String(options.limit));
280
- if (options.cursor)
281
- url.searchParams.set("cursor", options.cursor);
282
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
283
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
284
- }
285
- async function getRunTimelineViaServer(context, runId, options = {}) {
286
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
287
- if (options.limit !== undefined)
288
- url.searchParams.set("limit", String(options.limit));
289
- if (options.cursor)
290
- url.searchParams.set("cursor", options.cursor);
291
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
292
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
293
- }
294
- async function stopRunViaServer(context, runId) {
295
- const payload = await requestServerJson(context, "/api/runs/stop", {
296
- method: "POST",
297
- headers: { "content-type": "application/json" },
298
- body: JSON.stringify({ runId })
299
- });
300
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
301
- }
302
- async function steerRunViaServer(context, runId, message) {
303
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
304
- method: "POST",
305
- headers: { "content-type": "application/json" },
306
- body: JSON.stringify({ message })
307
- });
308
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
309
- }
310
-
311
- // packages/cli/src/commands/_operator-surface.ts
312
- import { createInterface } from "readline";
313
- var CANONICAL_STAGES = [
314
- "Connect",
315
- "GitHub/task sync",
316
- "Prepare workspace",
317
- "Launch Pi",
318
- "Plan",
319
- "Implement",
320
- "Validate",
321
- "Commit",
322
- "Open PR",
323
- "Review/CI",
324
- "Merge",
325
- "Complete"
326
- ];
327
- function logDetail(log) {
328
- return typeof log.detail === "string" ? log.detail.trim() : "";
329
- }
330
- function parseProviderProtocolLog(title, detail) {
331
- if (title.trim().toLowerCase() !== "agent output")
332
- return null;
333
- if (!detail.startsWith("{") || !detail.endsWith("}"))
334
- return null;
335
- try {
336
- const record = JSON.parse(detail);
337
- if (!record || typeof record !== "object" || Array.isArray(record))
338
- return null;
339
- const type = record.type;
340
- return typeof type === "string" && [
341
- "assistant",
342
- "message_start",
343
- "message_update",
344
- "message_end",
345
- "stream_event",
346
- "tool_result",
347
- "tool_execution_start",
348
- "tool_execution_update",
349
- "tool_execution_end",
350
- "turn_start",
351
- "turn_end"
352
- ].includes(type) ? record : null;
353
- } catch {
354
- return null;
355
- }
356
- }
357
- function renderProviderProtocolLog(record) {
358
- const type = typeof record.type === "string" ? record.type : "";
359
- if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
360
- const toolName = String(record.toolName ?? record.name ?? "tool");
361
- const status = type === "tool_execution_start" ? "started" : type === "tool_execution_end" ? record.isError === true || record.result && typeof record.result === "object" && !Array.isArray(record.result) && record.result.isError === true ? "failed" : "completed" : "running";
362
- return `[Pi tool] ${toolName} ${status}`;
363
- }
364
- return null;
365
- }
366
- function entryId(entry, fallback) {
367
- return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
368
- }
369
- function renderOperatorSnapshot(snapshot) {
370
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
371
- const runId = String(run.runId ?? run.id ?? "run");
372
- const status = String(run.status ?? "unknown");
373
- const logs = snapshot.logs ?? [];
374
- const latestByStage = new Map;
375
- for (const log of logs) {
376
- const title = String(log.title ?? "").toLowerCase();
377
- const stageName = String(log.stage ?? "").toLowerCase();
378
- const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
379
- if (stage)
380
- latestByStage.set(stage, log);
381
- }
382
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
383
- const match = latestByStage.get(stage);
384
- return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
385
- });
386
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
387
- `);
388
- }
389
- function createPiRunStreamRenderer(output = process.stdout) {
390
- let lastSnapshot = "";
391
- const assistantTextById = new Map;
392
- const seenTimeline = new Set;
393
- const seenLogs = new Set;
394
- const writeLine = (line) => output.write(`${line}
395
- `);
396
- return {
397
- renderSnapshot(snapshot) {
398
- const rendered = renderOperatorSnapshot(snapshot);
399
- if (rendered && rendered !== lastSnapshot) {
400
- writeLine(rendered);
401
- lastSnapshot = rendered;
402
- }
403
- },
404
- renderTimeline(entries) {
405
- for (const [index, entry] of entries.entries()) {
406
- const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
407
- if (entry.type === "assistant_message" && typeof entry.text === "string") {
408
- const text = entry.text;
409
- const previousText = assistantTextById.get(id) ?? "";
410
- if (!previousText && text.trim()) {
411
- writeLine("[Pi assistant]");
412
- }
413
- if (text.startsWith(previousText)) {
414
- const delta = text.slice(previousText.length);
415
- if (delta)
416
- output.write(delta);
417
- } else if (text.trim() && text !== previousText) {
418
- if (previousText)
419
- writeLine(`
420
- [Pi assistant]`);
421
- output.write(text);
422
- }
423
- assistantTextById.set(id, text);
424
- continue;
425
- }
426
- if (seenTimeline.has(id))
427
- continue;
428
- seenTimeline.add(id);
429
- if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
430
- writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
431
- continue;
432
- }
433
- if (entry.type === "timeline_warning") {
434
- writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
435
- }
436
- }
437
- },
438
- renderLogs(entries) {
439
- for (const [index, entry] of entries.entries()) {
440
- const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
441
- if (seenLogs.has(id))
442
- continue;
443
- seenLogs.add(id);
444
- const title = String(entry.title ?? "");
445
- if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
446
- continue;
447
- const detail = logDetail(entry);
448
- if (!detail)
449
- continue;
450
- const protocolRecord = parseProviderProtocolLog(title, detail);
451
- if (protocolRecord) {
452
- const protocolLine = renderProviderProtocolLog(protocolRecord);
453
- if (protocolLine)
454
- writeLine(protocolLine);
455
- continue;
456
- }
457
- writeLine(`[${title || "Rig log"}] ${detail}`);
458
- }
459
- }
460
- };
461
- }
462
- function createOperatorSurface(options = {}) {
463
- const input = options.input ?? process.stdin;
464
- const output = options.output ?? process.stdout;
465
- const errorOutput = options.errorOutput ?? process.stderr;
466
- const renderer = createPiRunStreamRenderer(output);
467
- const writeLine = (line) => output.write(`${line}
468
- `);
469
- return {
470
- mode: "pi-compatible-text",
471
- ...renderer,
472
- info: writeLine,
473
- error: (message) => errorOutput.write(`${message}
474
- `),
475
- attachCommandInput(handler) {
476
- if (options.interactive === false || !input.isTTY)
477
- return null;
478
- const rl = createInterface({ input, output: process.stdout, terminal: false });
479
- rl.on("line", (line) => {
480
- Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
481
- });
482
- return { close: () => rl.close() };
483
- }
484
- };
485
- }
486
-
487
- // packages/cli/src/commands/_operator-view.ts
488
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
489
- var CANONICAL_STAGES2 = [
490
- "Connect",
491
- "GitHub/task sync",
492
- "Prepare workspace",
493
- "Launch Pi",
494
- "Plan",
495
- "Implement",
496
- "Validate",
497
- "Commit",
498
- "Open PR",
499
- "Review/CI",
500
- "Merge",
501
- "Complete"
502
- ];
503
- var GREEN = "\x1B[32m";
504
- var BLUE = "\x1B[34m";
505
- var MAGENTA = "\x1B[35m";
506
- var YELLOW = "\x1B[33m";
507
- var RED = "\x1B[31m";
508
- var DIM = "\x1B[2m";
509
- var BOLD = "\x1B[1m";
510
- var RESET = "\x1B[0m";
511
- async function loadPiTuiRuntime() {
512
- try {
513
- return await import("@earendil-works/pi-tui");
514
- } catch {
515
- const base = new URL("../../../pi/packages/tui/src/", import.meta.url);
516
- const [tui, input, terminal, keys, utils] = await Promise.all([
517
- import(new URL("tui.ts", base).href),
518
- import(new URL("components/input.ts", base).href),
519
- import(new URL("terminal.ts", base).href),
520
- import(new URL("keys.ts", base).href),
521
- import(new URL("utils.ts", base).href)
522
- ]);
523
- return {
524
- Container: tui.Container,
525
- TUI: tui.TUI,
526
- Input: input.Input,
527
- ProcessTerminal: terminal.ProcessTerminal,
528
- matchesKey: keys.matchesKey,
529
- truncateToWidth: utils.truncateToWidth
530
- };
531
- }
532
- }
533
- function runStatusFromPayload(payload) {
534
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
535
- return String(run.status ?? "unknown").toLowerCase();
536
- }
537
- async function applyOperatorCommand(context, input, deps = {}) {
538
- const line = input.line.trim();
539
- if (!line)
540
- return { action: "ignored" };
541
- if (line === "/detach" || line === "/quit" || line === "/q") {
542
- return { action: "detach", message: "Detached from run." };
543
- }
544
- if (line === "/stop") {
545
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
546
- return { action: "stopped", message: "Stop requested." };
547
- }
548
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
549
- if (!userMessage)
550
- return { action: "ignored" };
551
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
552
- return { action: "continue", message: "Steering message queued." };
553
- }
554
- async function readOperatorSnapshot(context, runId, options = {}) {
555
- const run = await getRunDetailsViaServer(context, runId);
556
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
557
- const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
558
- entries: [{
559
- id: `timeline-unavailable:${runId}`,
560
- type: "timeline_warning",
561
- detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
562
- createdAt: new Date().toISOString()
563
- }],
564
- nextCursor: options.timelineCursor ?? null
565
- }));
566
- const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
567
- const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
568
- const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
569
- return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
570
- }
571
- function unwrapRun(runPayload) {
572
- return runPayload.run && typeof runPayload.run === "object" && !Array.isArray(runPayload.run) ? runPayload.run : runPayload;
573
- }
574
- function logDetail2(log) {
575
- return typeof log.detail === "string" ? log.detail.trim() : "";
576
- }
577
- function logTitle(log) {
578
- return typeof log.title === "string" ? log.title.trim() : "";
579
- }
580
- function renderAssistantTextFromTimeline(entries) {
581
- const assistant = entries.filter((entry) => entry.type === "assistant_message" && typeof entry.text === "string").at(-1);
582
- const text = typeof assistant?.text === "string" ? assistant.text.trimEnd() : "";
583
- if (!text)
584
- return [];
585
- return [`${BLUE}${BOLD}Remote Pi assistant${RESET}`, ...text.split(/\r?\n/).slice(-18)];
586
- }
587
- function renderToolLines(entries) {
588
- return entries.filter((entry) => entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call").slice(-8).map((entry) => `${DIM}[tool]${RESET} ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
589
- }
590
- function renderStageLines(logs) {
591
- const latestByStage = new Map;
592
- for (const log of logs) {
593
- const title = logTitle(log).toLowerCase();
594
- const stageName = String(log.stage ?? "").toLowerCase();
595
- const stage = CANONICAL_STAGES2.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
596
- if (stage)
597
- latestByStage.set(stage, log);
598
- }
599
- return CANONICAL_STAGES2.map((stage) => {
600
- const log = latestByStage.get(stage);
601
- const status = String(log?.status ?? "pending");
602
- const detail = log ? logDetail2(log) : "";
603
- const color = status === "completed" ? GREEN : status === "failed" || status === "rejected" ? RED : status === "pending" ? DIM : YELLOW;
604
- const mark = status === "completed" ? "\u2713" : status === "pending" ? "\xB7" : status === "failed" ? "\u2717" : "\u25B6";
605
- return `${color}${mark} ${stage}${RESET}${detail ? ` ${DIM}\u2014 ${detail.slice(0, 140)}${RESET}` : ""}`;
606
- });
607
- }
608
- function renderEventLines(logs) {
609
- return logs.filter((log) => !CANONICAL_STAGES2.some((stage) => stage.toLowerCase() === logTitle(log).toLowerCase())).slice(-12).flatMap((log) => {
610
- const title = logTitle(log) || "Rig event";
611
- const detail = logDetail2(log);
612
- if (!detail)
613
- return [];
614
- const tone = String(log.tone ?? "");
615
- const color = tone === "error" ? RED : tone === "tool" ? MAGENTA : DIM;
616
- return [`${color}[${title}]${RESET} ${detail.slice(0, 220)}`];
617
- });
618
- }
619
-
620
- class RigRunComponent {
621
- truncateToWidth;
622
- snapshot = { run: {}, logs: [], timeline: [] };
623
- localEvents = [];
624
- constructor(truncateToWidth) {
625
- this.truncateToWidth = truncateToWidth;
626
- }
627
- update(snapshot) {
628
- this.snapshot = snapshot;
629
- }
630
- addLocalEvent(message) {
631
- this.localEvents.push(`${new Date().toLocaleTimeString()} ${message}`);
632
- this.localEvents = this.localEvents.slice(-8);
633
- }
634
- invalidate() {}
635
- render(width) {
636
- const run = unwrapRun(this.snapshot.run);
637
- const runId = String(run.runId ?? run.id ?? "run");
638
- const status = String(run.status ?? "unknown");
639
- const worker = typeof run.worktreePath === "string" && run.worktreePath.trim() ? run.worktreePath.trim() : typeof run.projectRoot === "string" && run.projectRoot.trim() ? run.projectRoot.trim() : "worker workspace pending";
640
- const lines = [
641
- `${BOLD}Rig Pi frontend${RESET} ${DIM}(local Pi TUI \u2192 Rig server \u2192 worker Pi backend)${RESET}`,
642
- `${BOLD}${runId}${RESET} \xB7 ${status} \xB7 ${DIM}${worker}${RESET}`,
643
- "",
644
- `${BOLD}Rig flow${RESET}`,
645
- ...renderStageLines(this.snapshot.logs ?? []),
646
- "",
647
- ...renderAssistantTextFromTimeline(this.snapshot.timeline ?? []),
648
- ...renderToolLines(this.snapshot.timeline ?? []),
649
- "",
650
- `${BOLD}Rig / Pi events${RESET}`,
651
- ...renderEventLines(this.snapshot.logs ?? []),
652
- ...this.localEvents.map((event) => `${GREEN}[frontend]${RESET} ${event}`),
653
- ""
654
- ];
655
- return lines.slice(-42).map((line) => this.truncateToWidth(line, Math.max(10, width)));
656
- }
657
- }
658
-
659
- class RigInputComponent {
660
- matchesKey;
661
- truncateToWidth;
662
- input;
663
- status = "Type text, /skill:..., or remote Pi slash commands. Local: /stop /detach.";
664
- constructor(InputCtor, matchesKey, truncateToWidth, onSubmit, onEscape) {
665
- this.matchesKey = matchesKey;
666
- this.truncateToWidth = truncateToWidth;
667
- this.input = new InputCtor;
668
- this.input.onSubmit = (value) => {
669
- const text = value.trim();
670
- this.input.setValue("");
671
- if (text)
672
- Promise.resolve(onSubmit(text));
673
- };
674
- this.input.onEscape = onEscape;
675
- }
676
- handleInput(data) {
677
- if (this.matchesKey(data, "ctrl+d")) {
678
- this.input.onEscape?.();
679
- return;
680
- }
681
- this.input.handleInput?.(data);
682
- }
683
- setStatus(status) {
684
- this.status = status;
685
- }
686
- invalidate() {
687
- this.input.invalidate();
688
- }
689
- render(width) {
690
- return [
691
- `${DIM}${this.truncateToWidth(this.status, Math.max(10, width))}${RESET}`,
692
- `${GREEN}${BOLD}You \u2192 worker Pi:${RESET}`,
693
- ...this.input.render(width)
694
- ];
695
- }
696
- }
697
- async function attachRunPiTuiFrontend(context, input) {
698
- const piTui = await loadPiTuiRuntime();
699
- const terminal = new piTui.ProcessTerminal;
700
- const tui = new piTui.TUI(terminal);
701
- const root = new piTui.Container;
702
- const runView = new RigRunComponent(piTui.truncateToWidth);
703
- let detached = false;
704
- let steered = input.steered === true;
705
- let latest = await readOperatorSnapshot(context, input.runId);
706
- let timelineCursor = latest.timelineCursor;
707
- runView.update(latest);
708
- if (steered)
709
- runView.addLocalEvent("initial message queued to worker Pi.");
710
- const stop = () => {
711
- detached = true;
712
- tui.stop();
713
- };
714
- const inputView = new RigInputComponent(piTui.Input, piTui.matchesKey, piTui.truncateToWidth, async (line) => {
715
- if (line === "/detach" || line === "/quit" || line === "/q") {
716
- runView.addLocalEvent("detached from run.");
717
- stop();
718
- return;
719
- }
720
- if (line === "/stop") {
721
- await stopRunViaServer(context, input.runId);
722
- runView.addLocalEvent("stop requested.");
723
- stop();
724
- return;
725
- }
726
- await steerRunViaServer(context, input.runId, line);
727
- steered = true;
728
- runView.addLocalEvent(`queued to worker Pi: ${line.slice(0, 160)}`);
729
- tui.requestRender();
730
- }, stop);
731
- root.addChild(runView);
732
- root.addChild(inputView);
733
- tui.addChild(root);
734
- tui.setFocus(inputView.input);
735
- tui.start();
736
- tui.requestRender(true);
737
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 1000));
738
- try {
739
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(latest.run))) {
740
- await Bun.sleep(pollMs);
741
- latest = await readOperatorSnapshot(context, input.runId, { timelineCursor });
742
- timelineCursor = latest.timelineCursor;
743
- runView.update(latest);
744
- inputView.setStatus(`Remote worker ${runStatusFromPayload(latest.run)}. Input is forwarded to worker Pi; /stop /detach are local controls.`);
745
- tui.requestRender();
746
- }
747
- } finally {
748
- if (!detached)
749
- tui.stop();
750
- }
751
- return { ...latest, timelineCursor, steered, detached, rendered: renderOperatorSnapshot(latest) };
752
- }
753
- async function attachRunOperatorView(context, input) {
754
- let steered = false;
755
- if (input.message?.trim()) {
756
- await steerRunViaServer(context, input.runId, input.message.trim());
757
- steered = true;
758
- }
759
- if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
760
- return attachRunPiTuiFrontend(context, {
761
- runId: input.runId,
762
- pollMs: input.pollMs,
763
- steered
764
- });
765
- }
766
- const surface = createOperatorSurface({ interactive: input.interactive !== false });
767
- let snapshot = await readOperatorSnapshot(context, input.runId);
768
- if (context.outputMode === "text") {
769
- surface.renderSnapshot(snapshot);
770
- surface.renderTimeline(snapshot.timeline);
771
- surface.renderLogs(snapshot.logs);
772
- if (steered)
773
- surface.info("Steering message queued.");
774
- }
775
- let detached = false;
776
- let commandInput = null;
777
- if (input.follow && !input.once && context.outputMode === "text") {
778
- if (input.interactive !== false && process.stdin.isTTY) {
779
- surface.info("Controls: /user <message>, /stop, /detach");
780
- commandInput = surface.attachCommandInput(async (line) => {
781
- const result = await applyOperatorCommand(context, { runId: input.runId, line });
782
- if (result.message)
783
- surface.info(result.message);
784
- if (result.action === "detach" || result.action === "stopped") {
785
- detached = true;
786
- commandInput?.close();
787
- }
788
- });
789
- }
790
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
791
- let timelineCursor = snapshot.timelineCursor;
792
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
793
- await Bun.sleep(pollMs);
794
- snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
795
- timelineCursor = snapshot.timelineCursor;
796
- surface.renderSnapshot(snapshot);
797
- surface.renderTimeline(snapshot.timeline);
798
- surface.renderLogs(snapshot.logs);
799
- }
800
- commandInput?.close();
801
- }
802
- return { ...snapshot, steered, detached };
803
- }
804
-
805
- // packages/cli/src/commands/_cli-format.ts
806
- import pc from "picocolors";
807
- function stringField(record, key, fallback = "") {
808
- const value = record[key];
809
- return typeof value === "string" && value.trim() ? value.trim() : fallback;
810
- }
811
- function truncate(value, width) {
812
- if (value.length <= width)
813
- return value;
814
- if (width <= 1)
815
- return "\u2026";
816
- return `${value.slice(0, width - 1)}\u2026`;
817
- }
818
- function pad(value, width) {
819
- return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
820
- }
821
- function statusColor(status) {
822
- const normalized = status.toLowerCase();
823
- if (["completed", "merged", "closed", "done", "accepted"].includes(normalized))
824
- return pc.green;
825
- if (["failed", "needs_attention", "needs-attention", "blocked"].includes(normalized))
826
- return pc.red;
827
- if (["running", "reviewing", "validating", "in_progress", "in-progress"].includes(normalized))
828
- return pc.cyan;
829
- if (["ready", "open", "queued", "created", "preparing"].includes(normalized))
830
- return pc.yellow;
831
- return pc.dim;
832
- }
833
- function formatRunList(runs, options = {}) {
834
- if (runs.length === 0) {
835
- return pc.dim(options.source === "server" ? "No runs recorded on the selected Rig server." : "No runs recorded in .rig/runs.");
836
- }
837
- const rows = runs.map((run) => {
838
- const runId = stringField(run, "runId", stringField(run, "id", "(unknown-run)"));
839
- const status = stringField(run, "status", "unknown");
840
- const taskId = stringField(run, "taskId", "");
841
- const title = stringField(run, "title", taskId || "(untitled)");
842
- const runtime = stringField(run, "runtimeAdapter", "");
843
- return { runId, status, title, runtime };
844
- });
845
- const idWidth = Math.min(36, Math.max(6, ...rows.map((row) => row.runId.length)));
846
- const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
847
- const header = `${pc.bold(pad("RUN", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
848
- const body = rows.map((row) => [
849
- pc.bold(pad(truncate(row.runId, idWidth), idWidth)),
850
- statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
851
- `${row.title}${row.runtime ? pc.dim(` ${row.runtime}`) : ""}`
852
- ].join(" "));
853
- return [pc.bold(options.source === "server" ? "Rig runs (server)" : "Rig runs"), header, ...body].join(`
854
- `);
855
- }
856
-
857
- // packages/cli/src/commands/run.ts
858
- function normalizeRemoteRunDetails(payload) {
859
- const run = payload.run;
860
- if (!run || typeof run !== "object" || Array.isArray(run))
861
- return null;
862
- return {
863
- ...run,
864
- ...Array.isArray(payload.timeline) ? { timeline: payload.timeline } : {},
865
- ...Array.isArray(payload.approvals) ? { approvals: payload.approvals } : {},
866
- ...Array.isArray(payload.userInputs) ? { userInputs: payload.userInputs } : {}
867
- };
868
- }
869
- var REMOTE_TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged"]);
870
- function isRemoteConnectionSelected(projectRoot) {
871
- return resolveSelectedConnection(projectRoot)?.connection.kind === "remote";
872
- }
873
- async function listRunsForSelectedConnection(context, options = {}) {
874
- if (isRemoteConnectionSelected(context.projectRoot)) {
875
- return { runs: await listRunsViaServer(context, options), source: "server" };
876
- }
877
- return { runs: listAuthorityRuns(context.projectRoot), source: "local" };
878
- }
879
- function runStringField(run, key, fallback = "") {
880
- const value = run[key];
881
- return typeof value === "string" && value.trim() ? value : fallback;
882
- }
883
- function runDisplayTitle(run) {
884
- return runStringField(run, "title", runStringField(run, "taskId", "(untitled)"));
885
- }
886
- function buildServerRunStatus(runs) {
887
- const activeRuns = runs.filter((run) => !REMOTE_TERMINAL_RUN_STATUSES.has(runStringField(run, "status").toLowerCase()));
888
- const recentRuns = runs.filter((run) => REMOTE_TERMINAL_RUN_STATUSES.has(runStringField(run, "status").toLowerCase()));
889
- return { activeRuns, recentRuns, runs };
890
- }
891
- function shouldPromptForEpicSelection(context, command, promptEpic, noEpicPrompt) {
892
- if (noEpicPrompt) {
893
- return false;
894
- }
895
- if (promptEpic) {
896
- return true;
897
- }
898
- if (command !== "start-serial") {
899
- return false;
900
- }
901
- return context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY;
902
- }
903
- async function promptForEpicSelection(projectRoot, command) {
904
- const epics = listOpenEpics(projectRoot);
905
- const defaultEpic = await resolveDefaultEpic(projectRoot);
906
- const options = epics.map((epic) => epic.id);
907
- if (defaultEpic && !options.includes(defaultEpic)) {
908
- options.unshift(defaultEpic);
909
- }
910
- if (options.length === 0) {
911
- throw new CliError2("No open epic found. Pass --epic <id>.");
912
- }
913
- console.log(`Select epic for run ${command}:`);
914
- options.forEach((id, index) => {
915
- const metadata = epics.find((epic) => epic.id === id);
916
- const details = [
917
- metadata?.priority !== undefined ? `priority:${metadata.priority}` : "",
918
- metadata?.createdAt ? `created:${metadata.createdAt.slice(0, 10)}` : "",
919
- id === defaultEpic ? "default" : ""
920
- ].filter(Boolean).join(" ");
921
- const suffix = details ? ` (${details})` : "";
922
- console.log(` ${index + 1}. ${id}${suffix}`);
923
- });
924
- const fallback = defaultEpic || options[0];
925
- const rl = createInterface2({ input: process.stdin, output: process.stdout });
926
- try {
927
- while (true) {
928
- const answer = (await rl.question(`Epic [1-${options.length}] or id (Enter for ${fallback}, q to cancel): `)).trim();
929
- if (!answer) {
930
- return fallback ?? options[0];
931
- }
932
- if (answer === "q" || answer === "quit") {
933
- throw new CliError2("Run cancelled by user.");
934
- }
935
- if (/^\d+$/.test(answer)) {
936
- const index = Number.parseInt(answer, 10) - 1;
937
- if (index >= 0 && index < options.length) {
938
- return options[index];
939
- }
940
- }
941
- if (options.includes(answer)) {
942
- return answer;
943
- }
944
- console.log("Invalid selection. Choose a listed number, exact epic id, or q to cancel.");
945
- }
946
- } finally {
947
- rl.close();
948
- }
949
- }
950
- async function executeRun(context, args) {
951
- const [command = "status", ...rest] = args;
952
- const runtimeContext = loadRuntimeContextFromEnv2() ?? undefined;
953
- switch (command) {
954
- case "list": {
955
- requireNoExtraArgs(rest, "bun run rig run list");
956
- const { runs, source } = await listRunsForSelectedConnection(context, { limit: 100 });
957
- if (context.outputMode === "text") {
958
- console.log(formatRunList(runs, { source }));
959
- }
960
- return { ok: true, group: "run", command, details: { runs, source } };
961
- }
962
- case "delete": {
963
- let pending = rest;
964
- const run = takeOption(pending, "--run");
965
- pending = run.rest;
966
- const purgeArtifacts = takeFlag(pending, "--purge-artifacts");
967
- pending = purgeArtifacts.rest;
968
- requireNoExtraArgs(pending, "bun run rig run delete --run <id> [--purge-artifacts]");
969
- if (!run.value) {
970
- throw new CliError2("run delete requires --run <id>.");
971
- }
972
- const result = await deleteRunState(context.projectRoot, {
973
- runId: run.value,
974
- purgeRuntime: true,
975
- purgeTaskArtifacts: purgeArtifacts.value
976
- });
977
- if (context.outputMode === "text") {
978
- console.log(`Deleted run ${result.runId}`);
979
- if (result.runtimeIds.length > 0) {
980
- console.log(`Cleaned runtimes: ${result.runtimeIds.join(", ")}`);
981
- }
982
- if (result.taskArtifactsDeleted) {
983
- console.log(`Cleared task artifacts for ${result.taskId}`);
984
- }
985
- }
986
- return { ok: true, group: "run", command, details: result };
987
- }
988
- case "cleanup": {
989
- let pending = rest;
990
- const all = takeFlag(pending, "--all");
991
- pending = all.rest;
992
- const keepArtifacts = takeFlag(pending, "--keep-artifacts");
993
- pending = keepArtifacts.rest;
994
- const keepRuntimes = takeFlag(pending, "--keep-runtimes");
995
- pending = keepRuntimes.rest;
996
- const keepQueue = takeFlag(pending, "--keep-queue");
997
- pending = keepQueue.rest;
998
- requireNoExtraArgs(pending, "bun run rig run cleanup --all [--keep-artifacts] [--keep-runtimes] [--keep-queue]");
999
- if (!all.value) {
1000
- throw new CliError2("run cleanup currently requires --all.");
1001
- }
1002
- const result = await cleanupRunState(context.projectRoot, {
1003
- includeArtifacts: !keepArtifacts.value,
1004
- includeRuntimes: !keepRuntimes.value,
1005
- includeQueue: !keepQueue.value
1006
- });
1007
- if (context.outputMode === "text") {
1008
- console.log(`Deleted runs: ${result.runIds.length}`);
1009
- console.log(`Cleaned runtimes: ${result.runtimeIds.length}`);
1010
- console.log(`Artifacts cleared: ${result.artifactsCleared ? "yes" : "no"}`);
1011
- console.log(`Queue cleared: ${result.queueCleared ? "yes" : "no"}`);
1012
- }
1013
- return { ok: true, group: "run", command, details: result };
1014
- }
1015
- case "show": {
1016
- let pending = rest;
1017
- const run = takeOption(pending, "--run");
1018
- pending = run.rest;
1019
- requireNoExtraArgs(pending, "bun run rig run show --run <id>");
1020
- if (!run.value) {
1021
- throw new CliError2("run show requires --run <id>.");
1022
- }
1023
- const record = readAuthorityRun(context.projectRoot, run.value) ?? normalizeRemoteRunDetails(await getRunDetailsViaServer(context, run.value).catch(() => ({})));
1024
- if (!record) {
1025
- throw new CliError2(`Run not found: ${run.value}`, 2);
1026
- }
1027
- if (context.outputMode === "text") {
1028
- console.log(JSON.stringify(record, null, 2));
1029
- }
1030
- return { ok: true, group: "run", command, details: record };
1031
- }
1032
- case "timeline": {
1033
- let pending = rest;
1034
- const run = takeOption(pending, "--run");
1035
- pending = run.rest;
1036
- const follow = takeFlag(pending, "--follow");
1037
- pending = follow.rest;
1038
- requireNoExtraArgs(pending, "bun run rig run timeline --run <id> [--follow]");
1039
- if (!run.value) {
1040
- throw new CliError2("run timeline requires --run <id>.");
1041
- }
1042
- const renderer = createPiRunStreamRenderer();
1043
- let cursor = null;
1044
- const page = await getRunTimelineViaServer(context, run.value, { limit: 500 });
1045
- const events = Array.isArray(page.entries) ? page.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1046
- cursor = typeof page.nextCursor === "string" ? page.nextCursor : null;
1047
- if (context.outputMode === "text") {
1048
- renderer.renderTimeline(events);
1049
- }
1050
- if (follow.value && context.outputMode === "text") {
1051
- while (true) {
1052
- await Bun.sleep(1000);
1053
- const nextPage = await getRunTimelineViaServer(context, run.value, { limit: 500, ...cursor ? { cursor } : {} });
1054
- const nextEvents = Array.isArray(nextPage.entries) ? nextPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1055
- cursor = typeof nextPage.nextCursor === "string" ? nextPage.nextCursor : cursor;
1056
- renderer.renderTimeline(nextEvents);
1057
- }
1058
- }
1059
- return { ok: true, group: "run", command, details: { runId: run.value, events, cursor } };
1060
- }
1061
- case "attach": {
1062
- let pending = rest;
1063
- const runOption = takeOption(pending, "--run");
1064
- pending = runOption.rest;
1065
- const messageOption = takeOption(pending, "--message");
1066
- pending = messageOption.rest;
1067
- const once = takeFlag(pending, "--once");
1068
- pending = once.rest;
1069
- const follow = takeFlag(pending, "--follow");
1070
- pending = follow.rest;
1071
- const pollMs = takeOption(pending, "--poll-ms");
1072
- pending = pollMs.rest;
1073
- const positionalRunId = pending.length > 0 ? pending[0] : undefined;
1074
- const extra = positionalRunId ? pending.slice(1) : pending;
1075
- requireNoExtraArgs(extra, "bun run rig run attach <run-id>|--run <run-id> [--message <text>] [--once|--follow] [--poll-ms <ms>]");
1076
- const runId = runOption.value ?? positionalRunId;
1077
- if (!runId) {
1078
- throw new CliError2("run attach requires a run id.", 2);
1079
- }
1080
- let steered = false;
1081
- if (messageOption.value?.trim()) {
1082
- await steerRunViaServer(context, runId, messageOption.value.trim());
1083
- steered = true;
1084
- }
1085
- const attached = await attachRunOperatorView(context, {
1086
- runId,
1087
- message: null,
1088
- once: once.value,
1089
- follow: follow.value,
1090
- pollMs: parsePositiveInt(pollMs.value, "--poll-ms", 2000)
1091
- });
1092
- return { ok: true, group: "run", command, details: { ...attached, steered: attached.steered || steered } };
1093
- }
1094
- case "status": {
1095
- requireNoExtraArgs(rest, "bun run rig run status");
1096
- if (context.dryRun) {
1097
- if (context.outputMode === "text") {
1098
- console.log("[dry-run] rig run status");
1099
- }
1100
- return { ok: true, group: "run", command };
1101
- }
1102
- const summary = isRemoteConnectionSelected(context.projectRoot) ? buildServerRunStatus(await listRunsViaServer(context, { limit: 100 })) : runStatus(context.projectRoot, runtimeContext);
1103
- const activeRuns = Array.isArray(summary.activeRuns) ? summary.activeRuns.filter((run) => Boolean(run && typeof run === "object" && !Array.isArray(run))) : [];
1104
- const recentRuns = Array.isArray(summary.recentRuns) ? summary.recentRuns.filter((run) => Boolean(run && typeof run === "object" && !Array.isArray(run))) : [];
1105
- if (context.outputMode === "text") {
1106
- console.log(`Active runs: ${activeRuns.length}`);
1107
- for (const run of activeRuns) {
1108
- console.log(`- ${runStringField(run, "runId", "(unknown-run)")} \xB7 ${runStringField(run, "status", "unknown")} \xB7 ${runStringField(run, "taskId", runDisplayTitle(run))}`);
1109
- }
1110
- if (recentRuns.length > 0) {
1111
- console.log("");
1112
- console.log("Recent runs:");
1113
- for (const run of recentRuns) {
1114
- console.log(`- ${runStringField(run, "runId", "(unknown-run)")} \xB7 ${runStringField(run, "status", "unknown")} \xB7 ${runStringField(run, "taskId", runDisplayTitle(run))}`);
1115
- }
1116
- }
1117
- }
1118
- return { ok: true, group: "run", command, details: summary };
1119
- }
1120
- case "start":
1121
- case "start-serial":
1122
- case "start-parallel": {
1123
- let pending = rest;
1124
- const epicResult = takeOption(pending, "--epic");
1125
- pending = epicResult.rest;
1126
- const promptEpicResult = takeFlag(pending, "--prompt-epic");
1127
- pending = promptEpicResult.rest;
1128
- const noEpicPromptResult = takeFlag(pending, "--no-epic-prompt");
1129
- pending = noEpicPromptResult.rest;
1130
- const wsPortResult = takeOption(pending, "--ws-port");
1131
- pending = wsPortResult.rest;
1132
- const serverHostResult = takeOption(pending, "--server-host");
1133
- pending = serverHostResult.rest;
1134
- const serverPortResult = takeOption(pending, "--server-port");
1135
- pending = serverPortResult.rest;
1136
- const pollResult = takeOption(pending, "--poll-ms");
1137
- pending = pollResult.rest;
1138
- const noServerResult = takeFlag(pending, "--no-server");
1139
- pending = noServerResult.rest;
1140
- 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]");
1141
- if (promptEpicResult.value && noEpicPromptResult.value) {
1142
- throw new CliError2("Cannot use --prompt-epic and --no-epic-prompt together.");
1143
- }
1144
- if (promptEpicResult.value && (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY)) {
1145
- throw new CliError2("--prompt-epic requires an interactive terminal (TTY) in text mode.");
1146
- }
1147
- let resolvedEpicId = epicResult.value || undefined;
1148
- if (!resolvedEpicId && shouldPromptForEpicSelection(context, command, promptEpicResult.value, noEpicPromptResult.value)) {
1149
- resolvedEpicId = await promptForEpicSelection(context.projectRoot, command);
1150
- }
1151
- const defaults = defaultStartRunOptions(command === "start-parallel" ? "parallel" : "serial");
1152
- const result = await startRun(context.projectRoot, {
1153
- mode: command === "start-parallel" ? "parallel" : "serial",
1154
- workers: defaults.workers,
1155
- epicId: resolvedEpicId,
1156
- wsPort: parsePositiveInt(wsPortResult.value, "--ws-port", defaults.wsPort),
1157
- startEventServer: noServerResult.value ? false : defaults.startEventServer,
1158
- serverHost: serverHostResult.value || defaults.serverHost,
1159
- serverPort: parsePositiveInt(serverPortResult.value, "--server-port", defaults.serverPort),
1160
- serverPollMs: parsePositiveInt(pollResult.value, "--poll-ms", defaults.serverPollMs),
1161
- dryRun: context.dryRun,
1162
- runtimeContext
1163
- });
1164
- if (context.outputMode === "text") {
1165
- console.log(`Epic: ${result.epicId}`);
1166
- console.log(`Server: ${result.baseUrl}`);
1167
- if (result.eventServerUrl) {
1168
- console.log(`Events: ${result.eventServerUrl}`);
1169
- }
1170
- console.log(`Runs: ${result.runIds.join(", ")}`);
1171
- }
1172
- if (result.exitCode !== 0) {
1173
- throw new CliError2(`run ${command} failed with exit code ${result.exitCode}.`, result.exitCode);
1174
- }
1175
- return {
1176
- ok: true,
1177
- group: "run",
1178
- command,
1179
- details: {
1180
- epicId: result.epicId,
1181
- baseUrl: result.baseUrl,
1182
- runIds: result.runIds,
1183
- eventServerUrl: result.eventServerUrl || null
1184
- }
1185
- };
1186
- }
1187
- case "resume": {
1188
- requireNoExtraArgs(rest, "bun run rig run resume");
1189
- if (context.dryRun) {
1190
- if (context.outputMode === "text") {
1191
- console.log("[dry-run] rig run resume");
1192
- }
1193
- return { ok: true, group: "run", command };
1194
- }
1195
- const resumed = await runResume(context.projectRoot, runtimeContext);
1196
- if (context.outputMode === "text") {
1197
- console.log(`Resumed run: ${resumed.runId}`);
1198
- }
1199
- return { ok: true, group: "run", command, details: resumed };
1200
- }
1201
- case "restart": {
1202
- requireNoExtraArgs(rest, "bun run rig run restart");
1203
- if (context.dryRun) {
1204
- if (context.outputMode === "text") {
1205
- console.log("[dry-run] rig run restart");
1206
- }
1207
- return { ok: true, group: "run", command };
1208
- }
1209
- const restarted = await runRestart(context.projectRoot, runtimeContext);
1210
- if (context.outputMode === "text") {
1211
- console.log(`Restarted run: ${restarted.runId}`);
1212
- }
1213
- return { ok: true, group: "run", command, details: restarted };
1214
- }
1215
- case "stop": {
1216
- const runOption = takeOption(rest, "--run");
1217
- const positionalRunId = runOption.rest.length > 0 ? runOption.rest[0] : undefined;
1218
- const extra = positionalRunId ? runOption.rest.slice(1) : runOption.rest;
1219
- requireNoExtraArgs(extra, "bun run rig run stop [<run-id>|--run <id>]");
1220
- const runId = runOption.value ?? positionalRunId;
1221
- if (context.dryRun) {
1222
- return {
1223
- ok: true,
1224
- group: "run",
1225
- command,
1226
- details: runId ? { runId, accepted: true } : { stopped: 0, remaining: [] }
1227
- };
1228
- }
1229
- if (runId) {
1230
- const stopped = await stopRunViaServer(context, runId);
1231
- if (context.outputMode === "text")
1232
- console.log(`Stop requested: ${runId}`);
1233
- return { ok: true, group: "run", command, details: stopped };
1234
- }
1235
- const result = await runStop(context.projectRoot);
1236
- if (result.remaining.length > 0) {
1237
- throw new CliError2(`Failed to stop run(s): ${result.remaining.join(", ")}`, 1);
1238
- }
1239
- if (context.outputMode === "text") {
1240
- console.log(`Stopped process count: ${result.stopped}`);
1241
- }
1242
- return {
1243
- ok: true,
1244
- group: "run",
1245
- command,
1246
- details: {
1247
- stopped: result.stopped,
1248
- remaining: result.remaining
1249
- }
1250
- };
1251
- }
1252
- default:
1253
- throw new CliError2(`Unknown run command: ${command}`);
1254
- }
1255
- }
1256
- export {
1257
- executeRun
1258
- };