@h-rig/cli 0.0.6-alpha.21 → 0.0.6-alpha.210

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 (50) hide show
  1. package/README.md +6 -28
  2. package/package.json +9 -28
  3. package/dist/bin/build-rig-binaries.js +0 -107
  4. package/dist/bin/rig.js +0 -10443
  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 -496
  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/_pi-session.js +0 -253
  15. package/dist/src/commands/_policy.js +0 -79
  16. package/dist/src/commands/_preflight.js +0 -483
  17. package/dist/src/commands/_probes.js +0 -13
  18. package/dist/src/commands/_run-driver-helpers.js +0 -289
  19. package/dist/src/commands/_server-client.js +0 -435
  20. package/dist/src/commands/_snapshot-upload.js +0 -318
  21. package/dist/src/commands/_task-picker.js +0 -76
  22. package/dist/src/commands/agent.js +0 -499
  23. package/dist/src/commands/browser.js +0 -890
  24. package/dist/src/commands/connect.js +0 -180
  25. package/dist/src/commands/dist.js +0 -402
  26. package/dist/src/commands/doctor.js +0 -517
  27. package/dist/src/commands/github.js +0 -281
  28. package/dist/src/commands/inbox.js +0 -160
  29. package/dist/src/commands/init.js +0 -1563
  30. package/dist/src/commands/inspect.js +0 -174
  31. package/dist/src/commands/inspector.js +0 -256
  32. package/dist/src/commands/plugin.js +0 -167
  33. package/dist/src/commands/profile-and-review.js +0 -178
  34. package/dist/src/commands/queue.js +0 -198
  35. package/dist/src/commands/remote.js +0 -507
  36. package/dist/src/commands/repo-git-harness.js +0 -221
  37. package/dist/src/commands/run.js +0 -1132
  38. package/dist/src/commands/server.js +0 -373
  39. package/dist/src/commands/setup.js +0 -687
  40. package/dist/src/commands/task-report-bug.js +0 -1083
  41. package/dist/src/commands/task-run-driver.js +0 -2469
  42. package/dist/src/commands/task.js +0 -1715
  43. package/dist/src/commands/test.js +0 -39
  44. package/dist/src/commands/workspace.js +0 -123
  45. package/dist/src/commands.js +0 -10122
  46. package/dist/src/index.js +0 -10461
  47. package/dist/src/launcher.js +0 -133
  48. package/dist/src/report-bug.js +0 -260
  49. package/dist/src/runner.js +0 -273
  50. package/dist/src/withMutedConsole.js +0 -42
@@ -1,1715 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/task.ts
3
- import { readFileSync as readFileSync4 } from "fs";
4
- import { spawnSync } from "child_process";
5
- import { resolve as resolve4 } from "path";
6
- import { cancel as cancel2, confirm, isCancel as isCancel2 } from "@clack/prompts";
7
-
8
- // packages/cli/src/runner.ts
9
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
- import { CliError } from "@rig/runtime/control-plane/errors";
11
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
12
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
13
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
14
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
16
- function formatCommand(parts) {
17
- return parts.map((part) => /[^a-zA-Z0-9_./:-]/.test(part) ? JSON.stringify(part) : part).join(" ");
18
- }
19
- function takeFlag(args, flag) {
20
- const rest = [];
21
- let value = false;
22
- for (const arg of args) {
23
- if (arg === flag) {
24
- value = true;
25
- continue;
26
- }
27
- rest.push(arg);
28
- }
29
- return { value, rest };
30
- }
31
- function takeOption(args, option) {
32
- const rest = [];
33
- let value;
34
- for (let index = 0;index < args.length; index += 1) {
35
- const current = args[index];
36
- if (current === option) {
37
- const next = args[index + 1];
38
- if (!next || next.startsWith("-")) {
39
- throw new CliError(`Missing value for ${option}`);
40
- }
41
- value = next;
42
- index += 1;
43
- continue;
44
- }
45
- if (current !== undefined) {
46
- rest.push(current);
47
- }
48
- }
49
- return { value, rest };
50
- }
51
- function requireNoExtraArgs(args, usage) {
52
- if (args.length > 0) {
53
- throw new CliError(`Unexpected arguments: ${args.join(" ")}
54
- Usage: ${usage}`);
55
- }
56
- }
57
- function requireTask(taskId, usage) {
58
- if (!taskId) {
59
- throw new CliError(`Missing --task option.
60
- Usage: ${usage}`);
61
- }
62
- return taskId;
63
- }
64
-
65
- // packages/cli/src/commands/task.ts
66
- import {
67
- taskArtifactDir,
68
- taskArtifacts,
69
- taskArtifactWrite,
70
- taskDeps,
71
- taskInfo,
72
- taskLookup,
73
- taskReady,
74
- taskRecord,
75
- taskReopen,
76
- taskScope,
77
- taskStatus as taskStatus2,
78
- taskValidate,
79
- taskVerify
80
- } from "@rig/runtime/control-plane/native/task-ops";
81
-
82
- // packages/cli/src/commands/_authority-runs.ts
83
- import {
84
- readAuthorityRun,
85
- readJsonlFile,
86
- resolveAuthorityRunDir,
87
- writeJsonFile
88
- } from "@rig/runtime/control-plane/authority-files";
89
-
90
- // packages/cli/src/commands/_paths.ts
91
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
92
-
93
- // packages/cli/src/commands/_authority-runs.ts
94
- function normalizeRuntimeAdapter(value) {
95
- const normalized = value?.trim().toLowerCase();
96
- if (!normalized) {
97
- return "pi";
98
- }
99
- if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
100
- return "codex";
101
- }
102
- if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
103
- return "pi";
104
- }
105
- return "claude-code";
106
- }
107
-
108
- // packages/cli/src/commands/_preflight.ts
109
- import { ensureProjectMainFreshBeforeRun } from "@rig/runtime/control-plane/project-main-pre-run-sync";
110
-
111
- // packages/cli/src/commands/_connection-state.ts
112
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
113
- import { homedir } from "os";
114
- import { dirname, resolve } from "path";
115
- function resolveGlobalConnectionsPath(env = process.env) {
116
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
117
- if (explicit)
118
- return resolve(explicit);
119
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
120
- if (stateDir)
121
- return resolve(stateDir, "connections.json");
122
- return resolve(homedir(), ".rig", "connections.json");
123
- }
124
- function resolveRepoConnectionPath(projectRoot) {
125
- return resolve(projectRoot, ".rig", "state", "connection.json");
126
- }
127
- function readJsonFile(path) {
128
- if (!existsSync(path))
129
- return null;
130
- try {
131
- return JSON.parse(readFileSync(path, "utf8"));
132
- } catch (error) {
133
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
134
- }
135
- }
136
- function normalizeConnection(value) {
137
- if (!value || typeof value !== "object" || Array.isArray(value))
138
- return null;
139
- const record = value;
140
- if (record.kind === "local")
141
- return { kind: "local", mode: "auto" };
142
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
143
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
144
- return { kind: "remote", baseUrl };
145
- }
146
- return null;
147
- }
148
- function readGlobalConnections(options = {}) {
149
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
150
- const payload = readJsonFile(path);
151
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
152
- return { connections: {} };
153
- }
154
- const rawConnections = payload.connections;
155
- const connections = {};
156
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
157
- for (const [alias, raw] of Object.entries(rawConnections)) {
158
- const connection = normalizeConnection(raw);
159
- if (connection)
160
- connections[alias] = connection;
161
- }
162
- }
163
- return { connections };
164
- }
165
- function readRepoConnection(projectRoot) {
166
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
167
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
168
- return null;
169
- const record = payload;
170
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
171
- if (!selected)
172
- return null;
173
- return {
174
- selected,
175
- project: typeof record.project === "string" ? record.project : undefined,
176
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
177
- };
178
- }
179
- function resolveSelectedConnection(projectRoot, options = {}) {
180
- const repo = readRepoConnection(projectRoot);
181
- if (!repo)
182
- return null;
183
- if (repo.selected === "local")
184
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
185
- const global = readGlobalConnections(options);
186
- const connection = global.connections[repo.selected];
187
- if (!connection) {
188
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
189
- }
190
- return { alias: repo.selected, connection };
191
- }
192
-
193
- // packages/cli/src/commands/_server-client.ts
194
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
195
- import { resolve as resolve2 } from "path";
196
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
197
- var scopedGitHubBearerTokens = new Map;
198
- function cleanToken(value) {
199
- const trimmed = value?.trim();
200
- return trimmed ? trimmed : null;
201
- }
202
- function readPrivateRemoteSessionToken(projectRoot) {
203
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
204
- if (!existsSync2(path))
205
- return null;
206
- try {
207
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
208
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
209
- } catch {
210
- return null;
211
- }
212
- }
213
- function readGitHubBearerTokenForRemote(projectRoot) {
214
- const scopedKey = resolve2(projectRoot);
215
- if (scopedGitHubBearerTokens.has(scopedKey))
216
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
217
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
218
- if (privateSession)
219
- return privateSession;
220
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
221
- }
222
- async function ensureServerForCli(projectRoot) {
223
- try {
224
- const selected = resolveSelectedConnection(projectRoot);
225
- if (selected?.connection.kind === "remote") {
226
- return {
227
- baseUrl: selected.connection.baseUrl,
228
- authToken: readGitHubBearerTokenForRemote(projectRoot),
229
- connectionKind: "remote"
230
- };
231
- }
232
- const connection = await ensureLocalRigServerConnection(projectRoot);
233
- return {
234
- baseUrl: connection.baseUrl,
235
- authToken: connection.authToken,
236
- connectionKind: "local"
237
- };
238
- } catch (error) {
239
- if (error instanceof Error) {
240
- throw new CliError2(error.message, 1);
241
- }
242
- throw error;
243
- }
244
- }
245
- function appendTaskFilterParams(url, filters) {
246
- if (filters.assignee)
247
- url.searchParams.set("assignee", filters.assignee);
248
- if (filters.state)
249
- url.searchParams.set("state", filters.state);
250
- if (filters.status)
251
- url.searchParams.set("status", filters.status);
252
- if (filters.limit !== undefined)
253
- url.searchParams.set("limit", String(filters.limit));
254
- }
255
- function mergeHeaders(headers, authToken) {
256
- const merged = new Headers(headers);
257
- if (authToken) {
258
- merged.set("authorization", `Bearer ${authToken}`);
259
- }
260
- return merged;
261
- }
262
- function diagnosticMessage(payload) {
263
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
264
- return null;
265
- const record = payload;
266
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
267
- const messages = diagnostics.flatMap((entry) => {
268
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
269
- return [];
270
- const diagnostic = entry;
271
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
272
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
273
- return message ? [`${kind}: ${message}`] : [];
274
- });
275
- return messages.length > 0 ? messages.join("; ") : null;
276
- }
277
- async function requestServerJson(context, pathname, init = {}) {
278
- const server = await ensureServerForCli(context.projectRoot);
279
- const response = await fetch(`${server.baseUrl}${pathname}`, {
280
- ...init,
281
- headers: mergeHeaders(init.headers, server.authToken)
282
- });
283
- const text = await response.text();
284
- const payload = text.trim().length > 0 ? (() => {
285
- try {
286
- return JSON.parse(text);
287
- } catch {
288
- return null;
289
- }
290
- })() : null;
291
- if (!response.ok) {
292
- const diagnostics = diagnosticMessage(payload);
293
- const detail = diagnostics ?? (text || response.statusText);
294
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
295
- }
296
- return payload;
297
- }
298
- async function listWorkspaceTasksViaServer(context, filters = {}) {
299
- const url = new URL("http://rig.local/api/workspace/tasks");
300
- appendTaskFilterParams(url, filters);
301
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
302
- if (!Array.isArray(payload)) {
303
- throw new CliError2("Rig server returned an invalid task list payload.", 1);
304
- }
305
- return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
306
- }
307
- async function getWorkspaceTaskViaServer(context, taskId) {
308
- const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
309
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
310
- return null;
311
- const task = payload.task;
312
- return task && typeof task === "object" && !Array.isArray(task) ? task : null;
313
- }
314
- async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
315
- const url = new URL("http://rig.local/api/workspace/tasks/next");
316
- appendTaskFilterParams(url, filters);
317
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
318
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
319
- throw new CliError2("Rig server returned an invalid next-task payload.", 1);
320
- }
321
- const record = payload;
322
- const rawTask = record.task;
323
- const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
324
- const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
325
- return { task, count };
326
- }
327
- async function getRunDetailsViaServer(context, runId) {
328
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
329
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
330
- }
331
- async function getRunLogsViaServer(context, runId, options = {}) {
332
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
333
- if (options.limit !== undefined)
334
- url.searchParams.set("limit", String(options.limit));
335
- if (options.cursor)
336
- url.searchParams.set("cursor", options.cursor);
337
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
338
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
339
- }
340
- async function getRunTimelineViaServer(context, runId, options = {}) {
341
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
342
- if (options.limit !== undefined)
343
- url.searchParams.set("limit", String(options.limit));
344
- if (options.cursor)
345
- url.searchParams.set("cursor", options.cursor);
346
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
347
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
348
- }
349
- async function stopRunViaServer(context, runId) {
350
- const payload = await requestServerJson(context, "/api/runs/stop", {
351
- method: "POST",
352
- headers: { "content-type": "application/json" },
353
- body: JSON.stringify({ runId })
354
- });
355
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
356
- }
357
- async function steerRunViaServer(context, runId, message) {
358
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
359
- method: "POST",
360
- headers: { "content-type": "application/json" },
361
- body: JSON.stringify({ message })
362
- });
363
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
364
- }
365
- async function submitTaskRunViaServer(context, input) {
366
- const isTaskRun = Boolean(input.taskId);
367
- const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
368
- const payload = await requestServerJson(context, endpoint, {
369
- method: "POST",
370
- headers: {
371
- "content-type": "application/json"
372
- },
373
- body: JSON.stringify({
374
- runId: input.runId,
375
- taskId: input.taskId,
376
- title: input.title,
377
- runtimeAdapter: input.runtimeAdapter,
378
- model: input.model,
379
- runtimeMode: input.runtimeMode,
380
- interactionMode: input.interactionMode,
381
- initialPrompt: input.initialPrompt,
382
- baselineMode: input.baselineMode,
383
- prMode: input.prMode,
384
- executionTarget: "local"
385
- })
386
- });
387
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
388
- throw new CliError2("Rig server returned an invalid run submission payload.", 1);
389
- }
390
- const runId = payload.runId;
391
- if (typeof runId !== "string" || runId.trim().length === 0) {
392
- throw new CliError2("Rig server returned no runId for the submitted run.", 1);
393
- }
394
- return { runId };
395
- }
396
-
397
- // packages/cli/src/commands/_pi-install.ts
398
- import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
399
- import { homedir as homedir2 } from "os";
400
- import { resolve as resolve3 } from "path";
401
- var PI_RIG_PACKAGE_NAME = "@h-rig/pi-rig";
402
- var LEGACY_PI_RIG_PACKAGE_NAME = "@rig/pi-rig";
403
- async function defaultCommandRunner(command, options = {}) {
404
- const proc = Bun.spawn(command, { cwd: options.cwd, stdout: "pipe", stderr: "pipe" });
405
- const [stdout, stderr, exitCode] = await Promise.all([
406
- new Response(proc.stdout).text(),
407
- new Response(proc.stderr).text(),
408
- proc.exited
409
- ]);
410
- return { exitCode, stdout, stderr };
411
- }
412
- function resolvePiRigExtensionPath(homeDir) {
413
- return resolve3(homeDir, ".pi", "agent", "extensions", "pi-rig");
414
- }
415
- function resolvePiRigPackageSource(projectRoot, exists = existsSync3) {
416
- const localPackage = resolve3(projectRoot, "packages", "pi-rig");
417
- if (exists(resolve3(localPackage, "package.json")))
418
- return localPackage;
419
- return `npm:${PI_RIG_PACKAGE_NAME}`;
420
- }
421
- function resolvePiHomeDir(inputHomeDir) {
422
- return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
423
- }
424
- function piListContainsPiRig(output) {
425
- return output.split(/\r?\n/).some((line) => {
426
- const normalized = line.trim();
427
- return normalized.includes(PI_RIG_PACKAGE_NAME) || normalized.includes(LEGACY_PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
428
- });
429
- }
430
- async function safeRun(runner, command, options) {
431
- try {
432
- return await runner(command, options);
433
- } catch (error) {
434
- return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
435
- }
436
- }
437
- async function checkPiRigInstall(input = {}) {
438
- const home = resolvePiHomeDir(input.homeDir);
439
- const extensionPath = resolvePiRigExtensionPath(home);
440
- if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
441
- return {
442
- extensionPath,
443
- pi: { ok: true, label: "pi", detail: "fake-pi" },
444
- piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
445
- };
446
- }
447
- const exists = input.exists ?? existsSync3;
448
- const runner = input.commandRunner ?? defaultCommandRunner;
449
- const piResult = await safeRun(runner, ["pi", "--version"]);
450
- const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
451
- const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
452
- ${piListResult.stderr}`);
453
- const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
454
- const hasPiRig = listedPiRig;
455
- return {
456
- extensionPath,
457
- pi: {
458
- ok: piResult.exitCode === 0,
459
- label: "pi",
460
- detail: (piResult.stdout || piResult.stderr).trim() || undefined,
461
- hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
462
- },
463
- piRig: {
464
- ok: hasPiRig,
465
- label: "pi-rig global extension",
466
- detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
467
- hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
468
- }
469
- };
470
- }
471
- async function buildPiSetupChecks(input = {}) {
472
- const status = await checkPiRigInstall(input);
473
- return [status.pi, status.piRig];
474
- }
475
-
476
- // packages/cli/src/commands/_preflight.ts
477
- function preflightCheck(id, label, status, detail, remediation) {
478
- return {
479
- id,
480
- label,
481
- status,
482
- ...detail ? { detail } : {},
483
- ...remediation ? { remediation } : {}
484
- };
485
- }
486
- function message(error) {
487
- return error instanceof Error ? error.message : String(error);
488
- }
489
- function isAuthenticated(payload) {
490
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
491
- return false;
492
- const record = payload;
493
- return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
494
- }
495
- function taskMatchesId(entry, taskId) {
496
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
497
- return false;
498
- const record = entry;
499
- if (record.id === taskId || record.taskId === taskId)
500
- return true;
501
- const raw = record.raw;
502
- if (raw && typeof raw === "object" && !Array.isArray(raw)) {
503
- const rawRecord = raw;
504
- if (String(rawRecord.number ?? "") === taskId.replace(/^#/, ""))
505
- return true;
506
- }
507
- return false;
508
- }
509
- function isActiveRunStatus(status) {
510
- const normalized = String(status ?? "running").toLowerCase();
511
- return !["completed", "complete", "done", "merged", "closed", "failed", "cancelled", "canceled", "needs_attention", "needs-attention", "stopped"].includes(normalized);
512
- }
513
- function permissionAllowsPr(payload) {
514
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
515
- return null;
516
- const record = payload;
517
- if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
518
- return true;
519
- if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
520
- return false;
521
- const permissions = record.permissions;
522
- if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
523
- const p = permissions;
524
- if (p.push === true || p.maintain === true || p.admin === true)
525
- return true;
526
- if (p.push === false && p.maintain !== true && p.admin !== true)
527
- return false;
528
- }
529
- return null;
530
- }
531
- function isNotFoundError(error) {
532
- return /\b(404|not found)\b/i.test(message(error));
533
- }
534
- function projectCheckoutReady(payload) {
535
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
536
- return null;
537
- const record = payload;
538
- if (record.checkoutReady === true || record.ready === true)
539
- return true;
540
- if (record.checkoutReady === false || record.ready === false)
541
- return false;
542
- const project = record.project;
543
- if (project && typeof project === "object" && !Array.isArray(project)) {
544
- const checkouts = project.checkouts;
545
- if (Array.isArray(checkouts))
546
- return checkouts.length > 0;
547
- }
548
- return null;
549
- }
550
- function activeDuplicateRun(runs, taskId) {
551
- if (!Array.isArray(runs))
552
- return null;
553
- for (const run of runs) {
554
- if (!run || typeof run !== "object" || Array.isArray(run))
555
- continue;
556
- const record = run;
557
- if ((record.taskId === taskId || record.task === taskId) && isActiveRunStatus(record.status))
558
- return record;
559
- }
560
- return null;
561
- }
562
- async function runFastTaskRunPreflight(context, options = {}) {
563
- const checks = [];
564
- const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
565
- const taskId = options.taskId?.trim() || null;
566
- const requiresCurrentRunApi = Boolean(taskId);
567
- const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
568
- const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
569
- let legacyServerCompatibility = false;
570
- try {
571
- await request("/api/server/status");
572
- checks.push(preflightCheck("server", "Rig server reachable", "pass"));
573
- } catch (error) {
574
- if (isNotFoundError(error)) {
575
- try {
576
- await request("/health");
577
- legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
578
- checks.push(requiresCurrentRunApi && !allowLocalLegacyTaskRunCompatibility ? preflightCheck("server", "Rig server reachable", "fail", "legacy /health endpoint only; current task-run APIs are required", "Upgrade/select the Rig server before launching a task run.") : preflightCheck("server", "Rig server reachable", "pass", allowLocalLegacyTaskRunCompatibility ? "local legacy /health endpoint; submit endpoint will be authoritative" : "legacy /health endpoint"));
579
- } catch (healthError) {
580
- checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
581
- }
582
- } else {
583
- checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
584
- }
585
- }
586
- const repo = readRepoConnection(context.projectRoot);
587
- checks.push(repo ? preflightCheck("project-link", "project linked to Rig connection", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to Rig connection", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig connect use <alias|local>`."));
588
- try {
589
- const auth = await request("/api/github/auth/status");
590
- checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
591
- } catch (error) {
592
- checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
593
- }
594
- try {
595
- const projection = await request("/api/workspace/task-projection");
596
- checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
597
- } catch (error) {
598
- checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
599
- }
600
- try {
601
- const permissions = await request("/api/github/repo/permissions");
602
- const allowed = permissionAllowsPr(permissions);
603
- checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
604
- } catch (error) {
605
- checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
606
- }
607
- if (repo?.project) {
608
- try {
609
- const project = await request(`/api/projects/${encodeURIComponent(repo.project)}`);
610
- const ready = projectCheckoutReady(project);
611
- checks.push(ready === false ? preflightCheck("remote-checkout", "execution checkout ready", "fail", JSON.stringify(project).slice(0, 120), "Repair the server checkout or rerun `rig init` with a valid checkout strategy.") : preflightCheck("remote-checkout", "execution checkout ready", ready === true ? "pass" : "warn", JSON.stringify(project).slice(0, 120), "Confirm the selected server has a prepared execution checkout."));
612
- } catch (error) {
613
- checks.push(preflightCheck("remote-checkout", "execution checkout ready", "warn", message(error), "Run `rig init` or repair the server checkout before launch."));
614
- }
615
- }
616
- if (taskId) {
617
- try {
618
- const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
619
- const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
620
- checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
621
- } catch (error) {
622
- checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
623
- }
624
- try {
625
- const runs = await request("/api/runs?limit=200");
626
- const duplicate = activeDuplicateRun(runs, taskId);
627
- checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
628
- } catch (error) {
629
- checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
630
- }
631
- }
632
- if ((options.runtimeAdapter ?? "pi") === "pi") {
633
- const piChecks = await (options.piChecks ?? (() => buildPiSetupChecks()))().catch((error) => [{
634
- ok: false,
635
- label: "pi/pi-rig checks",
636
- hint: message(error)
637
- }]);
638
- for (const pi of piChecks) {
639
- checks.push(preflightCheck(pi.label === "pi" ? "pi" : "pi-rig", pi.label, pi.ok ? "pass" : "fail", pi.detail, pi.hint ?? (pi.ok ? undefined : "Run `rig init --yes` to install/update Pi and enable pi-rig.")));
640
- }
641
- } else {
642
- checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
643
- }
644
- const failures = checks.filter((check) => check.status === "fail");
645
- if (failures.length > 0) {
646
- const summary = failures.map((check) => `${check.label}${check.detail ? `: ${check.detail}` : ""}`).join("; ");
647
- if (failures.some((check) => check.id === "duplicate-active-run") && taskId) {
648
- throw new CliError2(`Task ${taskId} already has an active Rig run. ${summary}`, 1);
649
- }
650
- throw new CliError2(`Task run preflight failed: ${summary}`, 1);
651
- }
652
- return { ok: true, checks };
653
- }
654
- async function runProjectMainSyncPreflight(context, options) {
655
- if (context.dryRun) {
656
- if (context.outputMode === "text" && !options.disabled) {
657
- console.log("[dry-run] project-rig pre-run sync check");
658
- }
659
- return;
660
- }
661
- const result = await ensureProjectMainFreshBeforeRun({
662
- projectRoot: context.projectRoot,
663
- disabled: options.disabled,
664
- runBootstrap: async () => {
665
- const bootstrap = await context.runCommand(["bun", "run", "bootstrap"]);
666
- if (bootstrap.exitCode !== 0) {
667
- throw new CliError2(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
668
- }
669
- }
670
- });
671
- if (context.outputMode !== "text") {
672
- return;
673
- }
674
- switch (result.status) {
675
- case "disabled":
676
- console.log("Project pre-run sync skipped (--skip-project-sync).");
677
- break;
678
- case "skipped_not_main":
679
- console.log(`Project pre-run sync skipped (current branch: ${result.branch}).`);
680
- break;
681
- case "up_to_date":
682
- break;
683
- case "local_ahead":
684
- console.log(`Project pre-run sync skipped (local main ahead by ${result.localAhead} commit(s)).`);
685
- break;
686
- case "updated":
687
- console.log(`Project pre-run sync updated local main from origin/main (+${result.remoteAhead}) and bootstrapped.`);
688
- break;
689
- }
690
- }
691
-
692
- // packages/cli/src/withMutedConsole.ts
693
- function isPromise(value) {
694
- if (typeof value !== "object" && typeof value !== "function") {
695
- return false;
696
- }
697
- return value !== null && typeof value.then === "function";
698
- }
699
- function withMutedConsole(mute, fn) {
700
- if (!mute) {
701
- return fn();
702
- }
703
- const originalLog = console.log;
704
- const originalWarn = console.warn;
705
- const originalInfo = console.info;
706
- const restore = () => {
707
- console.log = originalLog;
708
- console.warn = originalWarn;
709
- console.info = originalInfo;
710
- };
711
- console.log = () => {};
712
- console.warn = () => {};
713
- console.info = () => {};
714
- try {
715
- const result = fn();
716
- if (isPromise(result)) {
717
- return result.finally(restore);
718
- }
719
- restore();
720
- return result;
721
- } catch (error) {
722
- restore();
723
- throw error;
724
- } finally {
725
- if (console.log === originalLog) {
726
- restore();
727
- }
728
- }
729
- }
730
-
731
- // packages/cli/src/commands/_task-picker.ts
732
- import { cancel, isCancel, select } from "@clack/prompts";
733
-
734
- // packages/cli/src/commands/_operator-surface.ts
735
- import { createInterface } from "readline";
736
- import { createInterface as createPromptInterface } from "readline/promises";
737
- var CANONICAL_STAGES = [
738
- "Connect",
739
- "GitHub/task sync",
740
- "Prepare workspace",
741
- "Launch Pi",
742
- "Plan",
743
- "Implement",
744
- "Validate",
745
- "Commit",
746
- "Open PR",
747
- "Review/CI",
748
- "Merge",
749
- "Complete"
750
- ];
751
- function logDetail(log) {
752
- return typeof log.detail === "string" ? log.detail.trim() : "";
753
- }
754
- function parseProviderProtocolLog(title, detail) {
755
- if (title.trim().toLowerCase() !== "agent output")
756
- return null;
757
- if (!detail.startsWith("{") || !detail.endsWith("}"))
758
- return null;
759
- try {
760
- const record = JSON.parse(detail);
761
- if (!record || typeof record !== "object" || Array.isArray(record))
762
- return null;
763
- const type = record.type;
764
- return typeof type === "string" && [
765
- "assistant",
766
- "message_start",
767
- "message_update",
768
- "message_end",
769
- "stream_event",
770
- "tool_result",
771
- "tool_execution_start",
772
- "tool_execution_update",
773
- "tool_execution_end",
774
- "turn_start",
775
- "turn_end"
776
- ].includes(type) ? record : null;
777
- } catch {
778
- return null;
779
- }
780
- }
781
- function renderProviderProtocolLog(record) {
782
- const type = typeof record.type === "string" ? record.type : "";
783
- if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
784
- const toolName = String(record.toolName ?? record.name ?? "tool");
785
- 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";
786
- return `[Pi tool] ${toolName} ${status}`;
787
- }
788
- return null;
789
- }
790
- function entryId(entry, fallback) {
791
- return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
792
- }
793
- function renderOperatorSnapshot(snapshot) {
794
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
795
- const runId = String(run.runId ?? run.id ?? "run");
796
- const status = String(run.status ?? "unknown");
797
- const logs = snapshot.logs ?? [];
798
- const latestByStage = new Map;
799
- for (const log of logs) {
800
- const title = String(log.title ?? "").toLowerCase();
801
- const stageName = String(log.stage ?? "").toLowerCase();
802
- const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
803
- if (stage)
804
- latestByStage.set(stage, log);
805
- }
806
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
807
- const match = latestByStage.get(stage);
808
- return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
809
- });
810
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
811
- `);
812
- }
813
- function createPiRunStreamRenderer(output = process.stdout) {
814
- let lastSnapshot = "";
815
- const assistantTextById = new Map;
816
- const seenTimeline = new Set;
817
- const seenLogs = new Set;
818
- const writeLine = (line) => output.write(`${line}
819
- `);
820
- return {
821
- renderSnapshot(snapshot) {
822
- const rendered = renderOperatorSnapshot(snapshot);
823
- if (rendered && rendered !== lastSnapshot) {
824
- writeLine(rendered);
825
- lastSnapshot = rendered;
826
- }
827
- },
828
- renderTimeline(entries) {
829
- for (const [index, entry] of entries.entries()) {
830
- const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
831
- if (entry.type === "assistant_message" && typeof entry.text === "string") {
832
- const text = entry.text;
833
- const previousText = assistantTextById.get(id) ?? "";
834
- if (!previousText && text.trim()) {
835
- writeLine("[Pi assistant]");
836
- }
837
- if (text.startsWith(previousText)) {
838
- const delta = text.slice(previousText.length);
839
- if (delta)
840
- output.write(delta);
841
- } else if (text.trim() && text !== previousText) {
842
- if (previousText)
843
- writeLine(`
844
- [Pi assistant]`);
845
- output.write(text);
846
- }
847
- assistantTextById.set(id, text);
848
- continue;
849
- }
850
- if (seenTimeline.has(id))
851
- continue;
852
- seenTimeline.add(id);
853
- if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
854
- writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
855
- continue;
856
- }
857
- if (entry.type === "timeline_warning") {
858
- writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
859
- }
860
- }
861
- },
862
- renderLogs(entries) {
863
- for (const [index, entry] of entries.entries()) {
864
- const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
865
- if (seenLogs.has(id))
866
- continue;
867
- seenLogs.add(id);
868
- const title = String(entry.title ?? "");
869
- if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
870
- continue;
871
- const detail = logDetail(entry);
872
- if (!detail)
873
- continue;
874
- const protocolRecord = parseProviderProtocolLog(title, detail);
875
- if (protocolRecord) {
876
- const protocolLine = renderProviderProtocolLog(protocolRecord);
877
- if (protocolLine)
878
- writeLine(protocolLine);
879
- continue;
880
- }
881
- writeLine(`[${title || "Rig log"}] ${detail}`);
882
- }
883
- }
884
- };
885
- }
886
- function createOperatorSurface(options = {}) {
887
- const input = options.input ?? process.stdin;
888
- const output = options.output ?? process.stdout;
889
- const errorOutput = options.errorOutput ?? process.stderr;
890
- const renderer = createPiRunStreamRenderer(output);
891
- const writeLine = (line) => output.write(`${line}
892
- `);
893
- return {
894
- mode: "pi-compatible-text",
895
- ...renderer,
896
- info: writeLine,
897
- error: (message2) => errorOutput.write(`${message2}
898
- `),
899
- attachCommandInput(handler) {
900
- if (options.interactive === false || !input.isTTY)
901
- return null;
902
- const rl = createInterface({ input, output: process.stdout, terminal: false });
903
- rl.on("line", (line) => {
904
- Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
905
- });
906
- return { close: () => rl.close() };
907
- }
908
- };
909
- }
910
- function taskId(task) {
911
- return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
912
- }
913
- function taskTitle(task) {
914
- return typeof task.title === "string" && task.title.trim() ? task.title : "Untitled task";
915
- }
916
- function taskStatus(task) {
917
- return typeof task.status === "string" && task.status.trim() ? task.status : "unknown";
918
- }
919
- function renderTaskPickerRows(tasks) {
920
- return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
921
- }
922
- async function promptForTaskSelection(question) {
923
- const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
924
- try {
925
- return await rl.question(question);
926
- } finally {
927
- rl.close();
928
- }
929
- }
930
-
931
- // packages/cli/src/commands/_task-picker.ts
932
- function taskId2(task) {
933
- return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
934
- }
935
- async function selectTaskWithTextPicker(tasks, io = {}) {
936
- if (tasks.length === 0)
937
- return null;
938
- if (tasks.length === 1)
939
- return tasks[0];
940
- const isTty = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
941
- if (!isTty) {
942
- throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
943
- }
944
- if (io.prompt || io.renderer) {
945
- const prompt = io.prompt ?? promptForTaskSelection;
946
- const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
947
- `) };
948
- renderer.writeLine("Select Rig task:");
949
- for (const row of renderTaskPickerRows(tasks))
950
- renderer.writeLine(` ${row}`);
951
- const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
952
- if (!answer2)
953
- return null;
954
- if (/^\d+$/.test(answer2)) {
955
- const index2 = Number.parseInt(answer2, 10) - 1;
956
- return tasks[index2] ?? null;
957
- }
958
- return tasks.find((task) => taskId2(task) === answer2) ?? null;
959
- }
960
- const options = tasks.map((task, index2) => ({
961
- value: `${index2}`,
962
- label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
963
- hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
964
- }));
965
- const answer = await select({
966
- message: "Select Rig task",
967
- options
968
- });
969
- if (isCancel(answer)) {
970
- cancel("No task selected.");
971
- return null;
972
- }
973
- const index = Number.parseInt(String(answer), 10);
974
- return Number.isFinite(index) ? tasks[index] ?? null : null;
975
- }
976
-
977
- // packages/cli/src/commands/_operator-view.ts
978
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
979
- function runStatusFromPayload(payload) {
980
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
981
- return String(run.status ?? "unknown").toLowerCase();
982
- }
983
- async function applyOperatorCommand(context, input, deps = {}) {
984
- const line = input.line.trim();
985
- if (!line)
986
- return { action: "ignored" };
987
- if (line === "/detach" || line === "/quit" || line === "/q") {
988
- return { action: "detach", message: "Detached from run." };
989
- }
990
- if (line === "/stop") {
991
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
992
- return { action: "stopped", message: "Stop requested." };
993
- }
994
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
995
- if (!userMessage)
996
- return { action: "ignored" };
997
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
998
- return { action: "continue", message: "Steering message queued." };
999
- }
1000
- async function readOperatorSnapshot(context, runId, options = {}) {
1001
- const run = await getRunDetailsViaServer(context, runId);
1002
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
1003
- const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
1004
- entries: [{
1005
- id: `timeline-unavailable:${runId}`,
1006
- type: "timeline_warning",
1007
- detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
1008
- createdAt: new Date().toISOString()
1009
- }],
1010
- nextCursor: options.timelineCursor ?? null
1011
- }));
1012
- const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
1013
- const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1014
- const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
1015
- return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
1016
- }
1017
- async function attachRunOperatorView(context, input) {
1018
- let steered = false;
1019
- if (input.message?.trim()) {
1020
- await steerRunViaServer(context, input.runId, input.message.trim());
1021
- steered = true;
1022
- }
1023
- const surface = createOperatorSurface({ interactive: input.interactive !== false });
1024
- let snapshot = await readOperatorSnapshot(context, input.runId);
1025
- if (context.outputMode === "text") {
1026
- surface.renderSnapshot(snapshot);
1027
- surface.renderTimeline(snapshot.timeline);
1028
- surface.renderLogs(snapshot.logs);
1029
- if (steered)
1030
- surface.info("Steering message queued.");
1031
- }
1032
- let detached = false;
1033
- let commandInput = null;
1034
- if (input.follow && !input.once && context.outputMode === "text") {
1035
- if (input.interactive !== false && process.stdin.isTTY) {
1036
- surface.info("Controls: /user <message>, /stop, /detach");
1037
- commandInput = surface.attachCommandInput(async (line) => {
1038
- const result = await applyOperatorCommand(context, { runId: input.runId, line });
1039
- if (result.message)
1040
- surface.info(result.message);
1041
- if (result.action === "detach" || result.action === "stopped") {
1042
- detached = true;
1043
- commandInput?.close();
1044
- }
1045
- });
1046
- }
1047
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
1048
- let timelineCursor = snapshot.timelineCursor;
1049
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
1050
- await Bun.sleep(pollMs);
1051
- snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
1052
- timelineCursor = snapshot.timelineCursor;
1053
- surface.renderSnapshot(snapshot);
1054
- surface.renderTimeline(snapshot.timeline);
1055
- surface.renderLogs(snapshot.logs);
1056
- }
1057
- commandInput?.close();
1058
- }
1059
- return { ...snapshot, steered, detached };
1060
- }
1061
-
1062
- // packages/cli/src/commands/_cli-format.ts
1063
- import pc from "picocolors";
1064
- function stringField(record, key, fallback = "") {
1065
- const value = record[key];
1066
- return typeof value === "string" && value.trim() ? value.trim() : fallback;
1067
- }
1068
- function arrayField(record, key) {
1069
- const value = record[key];
1070
- return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
1071
- }
1072
- function rawObject(record) {
1073
- const raw = record.raw;
1074
- return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
1075
- }
1076
- function truncate(value, width) {
1077
- if (value.length <= width)
1078
- return value;
1079
- if (width <= 1)
1080
- return "\u2026";
1081
- return `${value.slice(0, width - 1)}\u2026`;
1082
- }
1083
- function pad(value, width) {
1084
- return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
1085
- }
1086
- function statusColor(status) {
1087
- const normalized = status.toLowerCase();
1088
- if (["completed", "merged", "closed", "done", "accepted"].includes(normalized))
1089
- return pc.green;
1090
- if (["failed", "needs_attention", "needs-attention", "blocked"].includes(normalized))
1091
- return pc.red;
1092
- if (["running", "reviewing", "validating", "in_progress", "in-progress"].includes(normalized))
1093
- return pc.cyan;
1094
- if (["ready", "open", "queued", "created", "preparing"].includes(normalized))
1095
- return pc.yellow;
1096
- return pc.dim;
1097
- }
1098
- function formatTaskList(tasks, options = {}) {
1099
- if (tasks.length === 0)
1100
- return pc.dim("No matching tasks.");
1101
- if (options.raw)
1102
- return tasks.map((task) => JSON.stringify(task)).join(`
1103
- `);
1104
- const rows = tasks.map((task) => {
1105
- const raw = rawObject(task);
1106
- const id = stringField(task, "id", "<unknown>");
1107
- const status = stringField(task, "status", "unknown");
1108
- const title = stringField(task, "title", "Untitled task");
1109
- const source = stringField(task, "source", stringField(raw, "source", ""));
1110
- const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
1111
- return { id, status, title, source, labels };
1112
- });
1113
- const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
1114
- const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
1115
- const header = `${pc.bold(pad("TASK", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
1116
- const body = rows.map((row) => {
1117
- const labels = row.labels.length > 0 ? pc.dim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
1118
- const source = row.source ? pc.dim(` ${row.source}`) : "";
1119
- return [
1120
- pc.bold(pad(truncate(row.id, idWidth), idWidth)),
1121
- statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
1122
- `${row.title}${labels}${source}`
1123
- ].join(" ");
1124
- });
1125
- return [pc.bold("Rig tasks"), header, ...body].join(`
1126
- `);
1127
- }
1128
- function formatSubmittedRun(input) {
1129
- const lines = [`${pc.green("Run submitted")}: ${pc.bold(input.runId)}`];
1130
- if (input.task) {
1131
- const id = stringField(input.task, "id", "<unknown>");
1132
- const status = stringField(input.task, "status", "unknown");
1133
- const title = stringField(input.task, "title", "Untitled task");
1134
- lines.push(`${pc.dim("task")} ${pc.bold(id)} ${statusColor(status)(status)} ${title}`);
1135
- }
1136
- return lines.join(`
1137
- `);
1138
- }
1139
-
1140
- // packages/cli/src/commands/_pi-session.ts
1141
- import { spawn } from "child_process";
1142
- function buildPiRigSessionEnv(input) {
1143
- return {
1144
- RIG_PROJECT_ROOT: input.projectRoot,
1145
- PROJECT_RIG_ROOT: input.projectRoot,
1146
- RIG_RUN_ID: input.runId,
1147
- RIG_SERVER_RUN_ID: input.runId,
1148
- RIG_RUNTIME_ADAPTER: "pi",
1149
- RIG_SERVER_URL: input.serverUrl,
1150
- RIG_SERVER_BASE_URL: input.serverUrl,
1151
- RIG_STEERING_POLL_MS: process.env.RIG_STEERING_POLL_MS?.trim() || "1000",
1152
- RIG_PI_OPERATOR_SESSION: "1",
1153
- ...input.taskId ? { RIG_TASK_ID: input.taskId } : {},
1154
- ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {}
1155
- };
1156
- }
1157
- function shellBinary(name) {
1158
- const explicit = process.env.RIG_PI_BINARY?.trim();
1159
- if (explicit)
1160
- return explicit;
1161
- return Bun.which(name) || name;
1162
- }
1163
- function buildPiRigSessionCommand(input) {
1164
- const configuredExtension = input.extensionSource ?? process.env.RIG_PI_RIG_EXTENSION_SOURCE?.trim();
1165
- const extensionSource = configuredExtension && configuredExtension.length > 0 ? configuredExtension : resolvePiRigPackageSource(input.projectRoot);
1166
- const initialCommand = `/rig attach ${input.runId}`;
1167
- return [
1168
- shellBinary("pi"),
1169
- "--no-extensions",
1170
- "--extension",
1171
- extensionSource,
1172
- initialCommand
1173
- ];
1174
- }
1175
- async function launchPiRigSession(context, input) {
1176
- if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
1177
- return { launched: false, exitCode: null, command: [] };
1178
- }
1179
- if (process.env.RIG_DISABLE_PI_LAUNCH === "1") {
1180
- return { launched: false, exitCode: null, command: [] };
1181
- }
1182
- const server = await ensureServerForCli(context.projectRoot);
1183
- const command = buildPiRigSessionCommand({ ...input, projectRoot: context.projectRoot });
1184
- const env = {
1185
- ...process.env,
1186
- ...buildPiRigSessionEnv({
1187
- projectRoot: context.projectRoot,
1188
- runId: input.runId,
1189
- taskId: input.taskId,
1190
- serverUrl: server.baseUrl,
1191
- authToken: server.authToken
1192
- })
1193
- };
1194
- process.stdout.write(`Launching Pi for Rig run ${input.runId}\u2026
1195
- `);
1196
- process.stdout.write(`Pi command: ${formatCommand(command)}
1197
- `);
1198
- const launchedAt = Date.now();
1199
- const child = spawn(command[0], command.slice(1), {
1200
- cwd: context.projectRoot,
1201
- env,
1202
- stdio: "inherit"
1203
- });
1204
- const launchError = await new Promise((resolve4) => {
1205
- child.once("error", (error) => {
1206
- resolve4({ error: error.message });
1207
- });
1208
- child.once("close", (code) => resolve4({ code }));
1209
- });
1210
- if ("error" in launchError) {
1211
- process.stderr.write(`Failed to launch Pi; falling back to Rig attach view: ${launchError.error}
1212
- `);
1213
- return { launched: false, exitCode: null, command, error: launchError.error };
1214
- }
1215
- const exitCode = launchError.code;
1216
- const elapsedMs = Date.now() - launchedAt;
1217
- if (typeof exitCode === "number" && exitCode !== 0 && elapsedMs < 5000) {
1218
- const error = `Pi exited during startup with code ${exitCode}.`;
1219
- process.stderr.write(`${error} Falling back to Rig attach view.
1220
- `);
1221
- return { launched: false, exitCode, command, error };
1222
- }
1223
- return { launched: true, exitCode, command };
1224
- }
1225
-
1226
- // packages/cli/src/commands/task.ts
1227
- import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
1228
- import { loadConfig } from "@rig/core/load-config";
1229
- async function readStdin() {
1230
- const chunks = [];
1231
- for await (const chunk of process.stdin) {
1232
- chunks.push(Buffer.from(chunk));
1233
- }
1234
- return Buffer.concat(chunks).toString("utf-8");
1235
- }
1236
- function normalizeAssignedToAlias(value) {
1237
- if (!value)
1238
- return;
1239
- return value.trim().toLowerCase() === "me" ? "@me" : value;
1240
- }
1241
- function parseTaskFilters(args) {
1242
- let pending = args;
1243
- const assigneeResult = takeOption(pending, "--assignee");
1244
- pending = assigneeResult.rest;
1245
- const assignedToResult = takeOption(pending, "--assigned-to");
1246
- pending = assignedToResult.rest;
1247
- const stateResult = takeOption(pending, "--state");
1248
- pending = stateResult.rest;
1249
- const statusResult = takeOption(pending, "--status");
1250
- pending = statusResult.rest;
1251
- const limitResult = takeOption(pending, "--limit");
1252
- pending = limitResult.rest;
1253
- const normalizedAssignedTo = normalizeAssignedToAlias(assignedToResult.value);
1254
- if (assigneeResult.value && normalizedAssignedTo && assigneeResult.value !== normalizedAssignedTo) {
1255
- throw new CliError2("--assignee and --assigned-to cannot specify different assignees.", 2);
1256
- }
1257
- const assignee = normalizedAssignedTo ?? assigneeResult.value;
1258
- const limit = (() => {
1259
- if (!limitResult.value)
1260
- return;
1261
- const parsed = Number.parseInt(limitResult.value, 10);
1262
- if (!Number.isFinite(parsed) || parsed < 1) {
1263
- throw new CliError2("--limit must be a positive integer.", 2);
1264
- }
1265
- return parsed;
1266
- })();
1267
- const filters = {
1268
- ...assignee ? { assignee } : {},
1269
- ...stateResult.value ? { state: stateResult.value } : {},
1270
- ...statusResult.value ? { status: statusResult.value } : {},
1271
- ...limit !== undefined ? { limit } : {}
1272
- };
1273
- return { filters, rest: pending };
1274
- }
1275
- function mapConfiguredRuntimeMode(mode) {
1276
- if (!mode)
1277
- return;
1278
- return mode === "yolo" ? "full-access" : mode;
1279
- }
1280
- async function loadTaskRunProjectDefaults(projectRoot) {
1281
- try {
1282
- const config = await loadConfig(projectRoot);
1283
- return {
1284
- runtimeAdapter: config.runtime?.harness,
1285
- model: config.runtime?.model,
1286
- runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
1287
- prMode: config.pr?.mode
1288
- };
1289
- } catch {
1290
- return {};
1291
- }
1292
- }
1293
- function normalizePrMode(value) {
1294
- if (!value)
1295
- return;
1296
- if (value === "auto" || value === "ask" || value === "off")
1297
- return value;
1298
- throw new CliError2("--pr must be auto, ask, or off.", 2);
1299
- }
1300
- function detectLocalDirtyState(projectRoot) {
1301
- const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
1302
- if (result.status !== 0)
1303
- return { dirty: false, modified: 0, untracked: 0, lines: [] };
1304
- const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
1305
- return {
1306
- dirty: lines.length > 0,
1307
- modified: lines.filter((line) => !line.startsWith("?? ")).length,
1308
- untracked: lines.filter((line) => line.startsWith("?? ")).length,
1309
- lines
1310
- };
1311
- }
1312
- function selectedServerKind(projectRoot) {
1313
- try {
1314
- return resolveSelectedConnection(projectRoot)?.connection.kind === "remote" ? "remote" : "local";
1315
- } catch {
1316
- return "local";
1317
- }
1318
- }
1319
- async function resolveDirtyBaselineForTaskRun(context, explicit) {
1320
- if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
1321
- throw new CliError2("--dirty-baseline must be head or dirty-snapshot.", 2);
1322
- }
1323
- if (selectedServerKind(context.projectRoot) !== "local") {
1324
- return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
1325
- }
1326
- const state = detectLocalDirtyState(context.projectRoot);
1327
- if (!state.dirty)
1328
- return { mode: "head", state };
1329
- if (context.outputMode === "text") {
1330
- console.log(`Repo state: dirty (${state.modified} modified, ${state.untracked} untracked).`);
1331
- }
1332
- if (explicit)
1333
- return { mode: explicit, state };
1334
- if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
1335
- const answer = await confirm({
1336
- message: "Include current uncommitted changes in run baseline?",
1337
- initialValue: false
1338
- });
1339
- if (isCancel2(answer)) {
1340
- cancel2("Run cancelled.");
1341
- throw new CliError2("Run cancelled by user.", 1);
1342
- }
1343
- return { mode: answer ? "dirty-snapshot" : "head", state };
1344
- }
1345
- return { mode: "head", state };
1346
- }
1347
- function normalizeTaskRunTaskId(value) {
1348
- const trimmed = value?.trim() ?? "";
1349
- if (!trimmed)
1350
- return null;
1351
- const issueNumber = trimmed.match(/^#(\d+)$/)?.[1];
1352
- return issueNumber ?? trimmed;
1353
- }
1354
- function readTaskId(task) {
1355
- return typeof task.id === "string" && task.id.trim().length > 0 ? task.id : null;
1356
- }
1357
- function readTaskString(task, key) {
1358
- const value = task[key];
1359
- return typeof value === "string" && value.trim().length > 0 ? value : null;
1360
- }
1361
- function summarizeTask(task, options = {}) {
1362
- const raw = task.raw && typeof task.raw === "object" && !Array.isArray(task.raw) ? task.raw : null;
1363
- return {
1364
- id: readTaskId(task),
1365
- title: readTaskString(task, "title"),
1366
- status: readTaskString(task, "status"),
1367
- source: typeof task.source === "string" ? task.source : undefined,
1368
- url: typeof raw?.url === "string" ? raw.url : undefined,
1369
- number: typeof raw?.number === "number" ? raw.number : undefined,
1370
- labels: Array.isArray(task.labels) ? task.labels : Array.isArray(raw?.labels) ? raw.labels : undefined,
1371
- assignees: Array.isArray(raw?.assignees) ? raw.assignees : undefined,
1372
- readiness: typeof task.readiness === "string" || typeof task.readiness === "boolean" ? task.readiness : undefined,
1373
- validators: Array.isArray(task.validators) ? task.validators : Array.isArray(task.validation) ? task.validation : undefined,
1374
- ...options.raw ? { raw: raw ?? task } : {}
1375
- };
1376
- }
1377
- function printTaskSummary(task) {
1378
- console.log(formatTaskList([task]));
1379
- }
1380
- async function validatorRegistryForTaskCommands(projectRoot) {
1381
- return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
1382
- return;
1383
- });
1384
- }
1385
- async function executeTask(context, args, options) {
1386
- const [command = "info", ...rest] = args;
1387
- switch (command) {
1388
- case "list": {
1389
- let pending = rest;
1390
- const rawResult = takeFlag(pending, "--raw");
1391
- pending = rawResult.rest;
1392
- const { filters, rest: remaining } = parseTaskFilters(pending);
1393
- requireNoExtraArgs(remaining, "bun run rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1394
- const tasks = await listWorkspaceTasksViaServer(context, filters);
1395
- if (context.outputMode === "text") {
1396
- const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
1397
- console.log(formatTaskList(renderedTasks, { raw: rawResult.value }));
1398
- }
1399
- return {
1400
- ok: true,
1401
- group: "task",
1402
- command,
1403
- details: { count: tasks.length, filters, raw: rawResult.value, tasks: tasks.map((task) => summarizeTask(task, { raw: rawResult.value })) }
1404
- };
1405
- }
1406
- case "show": {
1407
- const taskOption = takeOption(rest, "--task");
1408
- const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
1409
- const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
1410
- requireNoExtraArgs(remaining, "bun run rig task show <id>|--task <id>");
1411
- const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
1412
- if (!taskId3)
1413
- throw new CliError2("task show requires a task id.", 2);
1414
- const task = await getWorkspaceTaskViaServer(context, taskId3);
1415
- if (!task)
1416
- throw new CliError2(`Task not found: ${taskId3}`, 3);
1417
- const summary = summarizeTask(task, { raw: true });
1418
- if (context.outputMode === "text")
1419
- console.log(JSON.stringify(summary, null, 2));
1420
- return { ok: true, group: "task", command, details: { task: summary } };
1421
- }
1422
- case "next": {
1423
- const { filters, rest: remaining } = parseTaskFilters(rest);
1424
- requireNoExtraArgs(remaining, "bun run rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1425
- const selected = await selectNextWorkspaceTaskViaServer(context, filters);
1426
- if (context.outputMode === "text") {
1427
- if (selected.task) {
1428
- printTaskSummary(selected.task);
1429
- } else {
1430
- console.log("No matching tasks.");
1431
- }
1432
- }
1433
- return {
1434
- ok: true,
1435
- group: "task",
1436
- command,
1437
- details: {
1438
- count: selected.count,
1439
- filters,
1440
- task: selected.task ? summarizeTask(selected.task) : null
1441
- }
1442
- };
1443
- }
1444
- case "info": {
1445
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1446
- requireNoExtraArgs(remaining, "bun run rig task info [--task <beads-id>]");
1447
- await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
1448
- return { ok: true, group: "task", command, details: { task: task || null } };
1449
- }
1450
- case "scope": {
1451
- const filesFlag = takeFlag(rest, "--files");
1452
- const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
1453
- requireNoExtraArgs(remaining, "bun run rig task scope [--task <id>] [--files]");
1454
- await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
1455
- return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
1456
- }
1457
- case "deps":
1458
- requireNoExtraArgs(rest, "bun run rig task deps");
1459
- await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
1460
- return { ok: true, group: "task", command };
1461
- case "status":
1462
- requireNoExtraArgs(rest, "bun run rig task status");
1463
- withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
1464
- return { ok: true, group: "task", command };
1465
- case "artifacts":
1466
- requireNoExtraArgs(rest, "bun run rig task artifacts");
1467
- withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
1468
- return { ok: true, group: "task", command };
1469
- case "artifact-dir": {
1470
- requireNoExtraArgs(rest, "bun run rig task artifact-dir");
1471
- const path = taskArtifactDir(context.projectRoot);
1472
- if (context.outputMode === "text") {
1473
- console.log(path);
1474
- }
1475
- return { ok: true, group: "task", command, details: { path } };
1476
- }
1477
- case "artifact-write": {
1478
- if (rest.length < 1) {
1479
- throw new CliError2(`Usage: bun run rig task artifact-write <filename> [--file <path>]
1480
- ` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
1481
- ` + " Example: echo '...' | rig task artifact-write collection-audit.md");
1482
- }
1483
- const artifactFilename = rest[0];
1484
- const fileFlag = takeOption(rest.slice(1), "--file");
1485
- let content;
1486
- if (fileFlag.value) {
1487
- content = readFileSync4(resolve4(context.projectRoot, fileFlag.value), "utf-8");
1488
- } else {
1489
- content = await readStdin();
1490
- }
1491
- if (!artifactFilename) {
1492
- throw new CliError2("Usage: bun run rig task artifact-write <filename> [--file path]");
1493
- }
1494
- withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
1495
- return { ok: true, group: "task", command, details: { filename: artifactFilename } };
1496
- }
1497
- case "report-bug":
1498
- return options.executeTaskReportBug(context, rest);
1499
- case "lookup": {
1500
- if (rest.length !== 1) {
1501
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
1502
- }
1503
- const lookupId = rest[0];
1504
- if (!lookupId) {
1505
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
1506
- }
1507
- const result = taskLookup(context.projectRoot, lookupId);
1508
- if (context.outputMode === "text") {
1509
- console.log(result);
1510
- }
1511
- return { ok: true, group: "task", command, details: { id: lookupId, result } };
1512
- }
1513
- case "record": {
1514
- if (rest.length < 2) {
1515
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
1516
- }
1517
- const type = rest[0];
1518
- if (type !== "decision" && type !== "failure") {
1519
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
1520
- }
1521
- withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
1522
- return { ok: true, group: "task", command, details: { type: rest[0] } };
1523
- }
1524
- case "ready":
1525
- requireNoExtraArgs(rest, "bun run rig task ready");
1526
- await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
1527
- return { ok: true, group: "task", command };
1528
- case "run": {
1529
- let pending = rest;
1530
- const nextResult = takeFlag(pending, "--next");
1531
- pending = nextResult.rest;
1532
- const taskResult = takeOption(pending, "--task");
1533
- pending = taskResult.rest;
1534
- const titleResult = takeOption(pending, "--title");
1535
- pending = titleResult.rest;
1536
- const runtimeAdapterResult = takeOption(pending, "--runtime-adapter");
1537
- pending = runtimeAdapterResult.rest;
1538
- const modelResult = takeOption(pending, "--model");
1539
- pending = modelResult.rest;
1540
- const runtimeModeResult = takeOption(pending, "--runtime-mode");
1541
- pending = runtimeModeResult.rest;
1542
- const interactionModeResult = takeOption(pending, "--interaction-mode");
1543
- pending = interactionModeResult.rest;
1544
- const initialPromptResult = takeOption(pending, "--initial-prompt");
1545
- pending = initialPromptResult.rest;
1546
- const prResult = takeOption(pending, "--pr");
1547
- pending = prResult.rest;
1548
- const noPrResult = takeFlag(pending, "--no-pr");
1549
- pending = noPrResult.rest;
1550
- const dirtyBaselineResult = takeOption(pending, "--dirty-baseline");
1551
- pending = dirtyBaselineResult.rest;
1552
- const skipProjectSyncResult = takeFlag(pending, "--skip-project-sync");
1553
- pending = skipProjectSyncResult.rest;
1554
- const detachResult = takeFlag(pending, "--detach");
1555
- pending = detachResult.rest;
1556
- const filterResult = parseTaskFilters(pending);
1557
- pending = filterResult.rest;
1558
- const positionalTaskId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? normalizeTaskRunTaskId(pending[0]) : null;
1559
- if (positionalTaskId) {
1560
- pending = pending.slice(1);
1561
- }
1562
- requireNoExtraArgs(pending, "bun run rig task run [#<issue>|<task-id>] [--next] [--task <id>] [--detach] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>] [--title <text>] [--runtime-adapter claude-code|codex|pi] [--model <model>] [--runtime-mode <mode>] [--interaction-mode <mode>] [--initial-prompt <text>] [--pr auto|ask|off] [--no-pr] [--dirty-baseline head|dirty-snapshot] [--skip-project-sync]");
1563
- if (nextResult.value && (taskResult.value || positionalTaskId)) {
1564
- throw new CliError2("task run cannot combine --next with an explicit task id.", 2);
1565
- }
1566
- if (taskResult.value && positionalTaskId) {
1567
- throw new CliError2("task run cannot combine positional task id with --task <id>.", 2);
1568
- }
1569
- if (prResult.value && noPrResult.value) {
1570
- throw new CliError2("task run cannot combine --pr with --no-pr.", 2);
1571
- }
1572
- let selectedTask = null;
1573
- let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
1574
- if (nextResult.value) {
1575
- const selected = await selectNextWorkspaceTaskViaServer(context, filterResult.filters);
1576
- selectedTask = selected.task;
1577
- selectedTaskId = selected.task ? readTaskId(selected.task) : null;
1578
- if (!selectedTaskId) {
1579
- throw new CliError2("No matching task found for task run --next.", 3);
1580
- }
1581
- }
1582
- if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
1583
- if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
1584
- throw new CliError2("task run requires an interactive terminal to pick a task; pass --next, --task <id>, or --initial-prompt/--title for an ad hoc run.", 2);
1585
- }
1586
- const tasks = await listWorkspaceTasksViaServer(context, filterResult.filters);
1587
- selectedTask = await selectTaskWithTextPicker(tasks);
1588
- selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
1589
- if (!selectedTaskId) {
1590
- throw new CliError2("No task selected.", 3);
1591
- }
1592
- }
1593
- await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
1594
- const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
1595
- const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
1596
- await runFastTaskRunPreflight(context, {
1597
- taskId: selectedTaskId,
1598
- runtimeAdapter
1599
- });
1600
- const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
1601
- const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
1602
- const submitted = await submitTaskRunViaServer(context, {
1603
- runId: context.runId,
1604
- taskId: selectedTaskId ?? undefined,
1605
- title: titleResult.value ?? undefined,
1606
- runtimeAdapter,
1607
- model: modelResult.value ?? projectDefaults.model,
1608
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
1609
- interactionMode: interactionModeResult.value || "default",
1610
- initialPrompt: initialPromptResult.value ?? undefined,
1611
- baselineMode: dirtyBaseline.mode,
1612
- prMode
1613
- });
1614
- let attachDetails = null;
1615
- if (!detachResult.value && context.outputMode === "text") {
1616
- console.log(formatSubmittedRun({ runId: submitted.runId, task: selectedTask ? summarizeTask(selectedTask) : null }));
1617
- if (runtimeAdapter === "pi") {
1618
- const piSession = await launchPiRigSession(context, {
1619
- runId: submitted.runId,
1620
- taskId: selectedTaskId,
1621
- title: titleResult.value ?? readTaskString(selectedTask ?? {}, "title"),
1622
- runtimeAdapter
1623
- });
1624
- attachDetails = { mode: "pi", ...piSession };
1625
- if (!piSession.launched) {
1626
- attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
1627
- }
1628
- } else {
1629
- attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
1630
- }
1631
- } else if (context.outputMode === "text") {
1632
- console.log(formatSubmittedRun({ runId: submitted.runId, task: selectedTask ? summarizeTask(selectedTask) : null }));
1633
- }
1634
- return {
1635
- ok: true,
1636
- group: "task",
1637
- command,
1638
- details: {
1639
- runId: submitted.runId,
1640
- taskId: selectedTaskId,
1641
- title: titleResult.value ?? null,
1642
- selectedTask: selectedTask ? summarizeTask(selectedTask) : null,
1643
- filters: nextResult.value ? filterResult.filters : undefined,
1644
- attached: Boolean(attachDetails),
1645
- attach: attachDetails,
1646
- runtimeAdapter,
1647
- model: modelResult.value ?? projectDefaults.model ?? null,
1648
- runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
1649
- prMode: prMode ?? null,
1650
- dirtyBaseline: { mode: dirtyBaseline.mode, dirty: dirtyBaseline.state?.dirty ?? false }
1651
- }
1652
- };
1653
- }
1654
- case "validate": {
1655
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1656
- requireNoExtraArgs(remaining, "bun run rig task validate [--task <beads-id>]");
1657
- if (context.dryRun) {
1658
- await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
1659
- return { ok: true, group: "task", command, details: { task: task || "active" } };
1660
- }
1661
- const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
1662
- if (!ok) {
1663
- throw new CliError2(`Validation failed for ${task || "active task"}.`, 2);
1664
- }
1665
- return { ok: true, group: "task", command, details: { task: task || "active" } };
1666
- }
1667
- case "verify": {
1668
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1669
- requireNoExtraArgs(remaining, "bun run rig task verify [--task <beads-id>]");
1670
- if (context.dryRun) {
1671
- await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
1672
- return { ok: true, group: "task", command, details: { task: task || "active" } };
1673
- }
1674
- const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, context.plugins, task || undefined));
1675
- if (!ok) {
1676
- throw new CliError2(`Verification rejected for ${task || "active task"}.`, 2);
1677
- }
1678
- return { ok: true, group: "task", command, details: { task: task || "active" } };
1679
- }
1680
- case "reset": {
1681
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1682
- requireNoExtraArgs(remaining, "bun run rig task reset --task <beads-id>");
1683
- const requiredTask = requireTask(task, "bun run rig task reset --task <beads-id>");
1684
- await context.runCommand(["br", "--no-db", "update", requiredTask, "--status", "open"]);
1685
- return { ok: true, group: "task", command, details: { task: requiredTask } };
1686
- }
1687
- case "details": {
1688
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1689
- requireNoExtraArgs(remaining, "bun run rig task details --task <beads-id>");
1690
- const requiredTask = requireTask(task, "bun run rig task details --task <beads-id>");
1691
- await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
1692
- return { ok: true, group: "task", command, details: { task: requiredTask } };
1693
- }
1694
- case "reopen": {
1695
- const { value: task, rest: rest1 } = takeOption(rest, "--task");
1696
- const allFlag = takeFlag(rest1, "--all");
1697
- const { rest: remaining } = takeOption(allFlag.rest, "--reason");
1698
- requireNoExtraArgs(remaining, "bun run rig task reopen [--task <id> | --all] [--reason <text>]");
1699
- if (!allFlag.value && !task) {
1700
- throw new CliError2("Usage: bun run rig task reopen [--task <id> | --all] [--reason <text>]");
1701
- }
1702
- const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
1703
- all: allFlag.value,
1704
- taskId: task || undefined,
1705
- dryRun: false
1706
- }));
1707
- return { ok: true, group: "task", command, details: summary };
1708
- }
1709
- default:
1710
- throw new CliError2(`Unknown task command: ${command}`);
1711
- }
1712
- }
1713
- export {
1714
- executeTask
1715
- };