@h-rig/cli 0.0.6-alpha.5 → 0.0.6-alpha.50

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/dist/bin/rig.js +4072 -1204
  2. package/dist/src/commands/_cli-format.js +369 -0
  3. package/dist/src/commands/_connection-state.js +12 -6
  4. package/dist/src/commands/_doctor-checks.js +65 -34
  5. package/dist/src/commands/_help-catalog.js +445 -0
  6. package/dist/src/commands/_operator-surface.js +220 -0
  7. package/dist/src/commands/_operator-view.js +1109 -63
  8. package/dist/src/commands/_parsers.js +0 -2
  9. package/dist/src/commands/_pi-frontend.js +1066 -0
  10. package/dist/src/commands/_pi-install.js +4 -3
  11. package/dist/src/commands/_pi-remote-session.js +757 -0
  12. package/dist/src/commands/_pi-worker-bridge-extension.js +820 -0
  13. package/dist/src/commands/_policy.js +0 -2
  14. package/dist/src/commands/_preflight.js +84 -116
  15. package/dist/src/commands/_run-driver-helpers.js +2 -2
  16. package/dist/src/commands/_server-client.js +211 -48
  17. package/dist/src/commands/_snapshot-upload.js +60 -30
  18. package/dist/src/commands/_spinner.js +63 -0
  19. package/dist/src/commands/_task-picker.js +44 -16
  20. package/dist/src/commands/agent.js +8 -9
  21. package/dist/src/commands/browser.js +4 -6
  22. package/dist/src/commands/connect.js +134 -26
  23. package/dist/src/commands/dist.js +4 -6
  24. package/dist/src/commands/doctor.js +65 -34
  25. package/dist/src/commands/github.js +62 -32
  26. package/dist/src/commands/inbox.js +396 -31
  27. package/dist/src/commands/init.js +342 -88
  28. package/dist/src/commands/inspect.js +282 -23
  29. package/dist/src/commands/inspector.js +2 -4
  30. package/dist/src/commands/pi.js +168 -0
  31. package/dist/src/commands/plugin.js +81 -22
  32. package/dist/src/commands/profile-and-review.js +8 -10
  33. package/dist/src/commands/queue.js +2 -3
  34. package/dist/src/commands/remote.js +18 -20
  35. package/dist/src/commands/repo-git-harness.js +6 -8
  36. package/dist/src/commands/run.js +1407 -130
  37. package/dist/src/commands/server.js +266 -40
  38. package/dist/src/commands/setup.js +69 -44
  39. package/dist/src/commands/task-report-bug.js +5 -7
  40. package/dist/src/commands/task-run-driver.js +662 -70
  41. package/dist/src/commands/task.js +1846 -259
  42. package/dist/src/commands/test.js +3 -5
  43. package/dist/src/commands/workspace.js +4 -6
  44. package/dist/src/commands.js +4054 -1180
  45. package/dist/src/index.js +4065 -1200
  46. package/dist/src/launcher.js +5 -3
  47. package/dist/src/report-bug.js +3 -3
  48. package/dist/src/runner.js +5 -19
  49. package/package.json +7 -4
@@ -1,16 +1,14 @@
1
1
  // @bun
2
2
  // packages/cli/src/commands/task.ts
3
- import { readFileSync as readFileSync4 } from "fs";
4
- import { spawnSync as spawnSync2 } from "child_process";
5
- import { createInterface as createInterface3 } from "readline/promises";
6
- import { resolve as resolve4 } from "path";
3
+ import { readFileSync as readFileSync3 } from "fs";
4
+ import { spawnSync } from "child_process";
5
+ import { resolve as resolve3 } from "path";
6
+ import { cancel as cancel2, confirm, isCancel as isCancel2 } from "@clack/prompts";
7
7
 
8
8
  // packages/cli/src/runner.ts
9
9
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
10
  import { CliError } from "@rig/runtime/control-plane/errors";
11
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
12
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
13
  import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
16
14
  function takeFlag(args, flag) {
@@ -130,6 +128,11 @@ function readJsonFile(path) {
130
128
  throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
131
129
  }
132
130
  }
131
+ function writeJsonFile2(path, value) {
132
+ mkdirSync(dirname(path), { recursive: true });
133
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
134
+ `, "utf8");
135
+ }
133
136
  function normalizeConnection(value) {
134
137
  if (!value || typeof value !== "object" || Array.isArray(value))
135
138
  return null;
@@ -170,29 +173,38 @@ function readRepoConnection(projectRoot) {
170
173
  return {
171
174
  selected,
172
175
  project: typeof record.project === "string" ? record.project : undefined,
173
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
176
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
177
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
174
178
  };
175
179
  }
180
+ function writeRepoConnection(projectRoot, state) {
181
+ writeJsonFile2(resolveRepoConnectionPath(projectRoot), state);
182
+ }
176
183
  function resolveSelectedConnection(projectRoot, options = {}) {
177
184
  const repo = readRepoConnection(projectRoot);
178
185
  if (!repo)
179
186
  return null;
180
187
  if (repo.selected === "local")
181
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
188
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
182
189
  const global = readGlobalConnections(options);
183
190
  const connection = global.connections[repo.selected];
184
191
  if (!connection) {
185
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
192
+ throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
186
193
  }
187
- return { alias: repo.selected, connection };
194
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
195
+ }
196
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
197
+ const repo = readRepoConnection(projectRoot);
198
+ if (!repo)
199
+ return;
200
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
188
201
  }
189
202
 
190
203
  // packages/cli/src/commands/_server-client.ts
191
- import { spawnSync } from "child_process";
192
204
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
193
205
  import { resolve as resolve2 } from "path";
194
206
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
195
- var cachedGitHubBearerToken;
207
+ var scopedGitHubBearerTokens = new Map;
196
208
  function cleanToken(value) {
197
209
  const trimmed = value?.trim();
198
210
  return trimmed ? trimmed : null;
@@ -209,41 +221,33 @@ function readPrivateRemoteSessionToken(projectRoot) {
209
221
  }
210
222
  }
211
223
  function readGitHubBearerTokenForRemote(projectRoot) {
212
- if (cachedGitHubBearerToken !== undefined)
213
- return cachedGitHubBearerToken;
224
+ const scopedKey = resolve2(projectRoot);
225
+ if (scopedGitHubBearerTokens.has(scopedKey))
226
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
214
227
  const privateSession = readPrivateRemoteSessionToken(projectRoot);
215
- if (privateSession) {
216
- cachedGitHubBearerToken = privateSession;
217
- return cachedGitHubBearerToken;
218
- }
219
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
220
- if (envToken) {
221
- cachedGitHubBearerToken = envToken;
222
- return cachedGitHubBearerToken;
223
- }
224
- const result = spawnSync("gh", ["auth", "token"], {
225
- encoding: "utf8",
226
- timeout: 5000,
227
- stdio: ["ignore", "pipe", "ignore"]
228
- });
229
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
230
- return cachedGitHubBearerToken;
228
+ if (privateSession)
229
+ return privateSession;
230
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
231
231
  }
232
232
  async function ensureServerForCli(projectRoot) {
233
233
  try {
234
234
  const selected = resolveSelectedConnection(projectRoot);
235
235
  if (selected?.connection.kind === "remote") {
236
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
237
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
236
238
  return {
237
239
  baseUrl: selected.connection.baseUrl,
238
- authToken: readGitHubBearerTokenForRemote(projectRoot),
239
- connectionKind: "remote"
240
+ authToken,
241
+ connectionKind: "remote",
242
+ serverProjectRoot
240
243
  };
241
244
  }
242
245
  const connection = await ensureLocalRigServerConnection(projectRoot);
243
246
  return {
244
247
  baseUrl: connection.baseUrl,
245
248
  authToken: connection.authToken,
246
- connectionKind: "local"
249
+ connectionKind: "local",
250
+ serverProjectRoot: resolve2(projectRoot)
247
251
  };
248
252
  } catch (error) {
249
253
  if (error instanceof Error) {
@@ -252,6 +256,29 @@ async function ensureServerForCli(projectRoot) {
252
256
  throw error;
253
257
  }
254
258
  }
259
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
260
+ const repo = readRepoConnection(projectRoot);
261
+ const slug = repo?.project?.trim();
262
+ if (!slug)
263
+ return null;
264
+ try {
265
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
266
+ headers: mergeHeaders(undefined, authToken)
267
+ });
268
+ if (!response.ok)
269
+ return null;
270
+ const payload = await response.json();
271
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
272
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
273
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
274
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
275
+ if (path)
276
+ writeRepoServerProjectRoot(projectRoot, path);
277
+ return path;
278
+ } catch {
279
+ return null;
280
+ }
281
+ }
255
282
  function appendTaskFilterParams(url, filters) {
256
283
  if (filters.assignee)
257
284
  url.searchParams.set("assignee", filters.assignee);
@@ -286,9 +313,12 @@ function diagnosticMessage(payload) {
286
313
  }
287
314
  async function requestServerJson(context, pathname, init = {}) {
288
315
  const server = await ensureServerForCli(context.projectRoot);
316
+ const headers = mergeHeaders(init.headers, server.authToken);
317
+ if (server.serverProjectRoot)
318
+ headers.set("x-rig-project-root", server.serverProjectRoot);
289
319
  const response = await fetch(`${server.baseUrl}${pathname}`, {
290
320
  ...init,
291
- headers: mergeHeaders(init.headers, server.authToken)
321
+ headers
292
322
  });
293
323
  const text = await response.text();
294
324
  const payload = text.trim().length > 0 ? (() => {
@@ -347,6 +377,15 @@ async function getRunLogsViaServer(context, runId, options = {}) {
347
377
  const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
348
378
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
349
379
  }
380
+ async function getRunTimelineViaServer(context, runId, options = {}) {
381
+ const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
382
+ if (options.limit !== undefined)
383
+ url.searchParams.set("limit", String(options.limit));
384
+ if (options.cursor)
385
+ url.searchParams.set("cursor", options.cursor);
386
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
387
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
388
+ }
350
389
  async function stopRunViaServer(context, runId) {
351
390
  const payload = await requestServerJson(context, "/api/runs/stop", {
352
391
  method: "POST",
@@ -363,6 +402,72 @@ async function steerRunViaServer(context, runId, message) {
363
402
  });
364
403
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
365
404
  }
405
+ async function getRunPiSessionViaServer(context, runId) {
406
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
407
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
408
+ }
409
+ async function getRunPiMessagesViaServer(context, runId) {
410
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
411
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
412
+ }
413
+ async function getRunPiStatusViaServer(context, runId) {
414
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
415
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
416
+ }
417
+ async function getRunPiCommandsViaServer(context, runId) {
418
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
419
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
420
+ }
421
+ async function getRunPiCapabilitiesViaServer(context, runId) {
422
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
423
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
424
+ }
425
+ async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
426
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
427
+ method: "POST",
428
+ headers: { "content-type": "application/json" },
429
+ body: JSON.stringify({ text, streamingBehavior })
430
+ });
431
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
432
+ }
433
+ async function sendRunPiShellViaServer(context, runId, text) {
434
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
435
+ method: "POST",
436
+ headers: { "content-type": "application/json" },
437
+ body: JSON.stringify({ text })
438
+ });
439
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
440
+ }
441
+ async function runRunPiCommandViaServer(context, runId, text) {
442
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
443
+ method: "POST",
444
+ headers: { "content-type": "application/json" },
445
+ body: JSON.stringify({ text })
446
+ });
447
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
448
+ }
449
+ async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
450
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
451
+ method: "POST",
452
+ headers: { "content-type": "application/json" },
453
+ body: JSON.stringify({ requestId, ...valueOrCancel })
454
+ });
455
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
456
+ }
457
+ async function abortRunPiViaServer(context, runId) {
458
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
459
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
460
+ }
461
+ async function buildRunPiEventsWebSocketUrl(context, runId) {
462
+ const server = await ensureServerForCli(context.projectRoot);
463
+ const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
464
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
465
+ if (server.authToken)
466
+ url.searchParams.set("token", server.authToken);
467
+ if (server.serverProjectRoot)
468
+ url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
469
+ return url.toString();
470
+ }
366
471
  async function submitTaskRunViaServer(context, input) {
367
472
  const isTaskRun = Boolean(input.taskId);
368
473
  const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
@@ -395,78 +500,6 @@ async function submitTaskRunViaServer(context, input) {
395
500
  return { runId };
396
501
  }
397
502
 
398
- // packages/cli/src/commands/_pi-install.ts
399
- import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
400
- import { homedir as homedir2 } from "os";
401
- import { resolve as resolve3 } from "path";
402
- var 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 resolvePiHomeDir(inputHomeDir) {
416
- return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
417
- }
418
- function piListContainsPiRig(output) {
419
- return output.split(/\r?\n/).some((line) => {
420
- const normalized = line.trim();
421
- return normalized.includes(PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
422
- });
423
- }
424
- async function safeRun(runner, command, options) {
425
- try {
426
- return await runner(command, options);
427
- } catch (error) {
428
- return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
429
- }
430
- }
431
- async function checkPiRigInstall(input = {}) {
432
- const home = resolvePiHomeDir(input.homeDir);
433
- const extensionPath = resolvePiRigExtensionPath(home);
434
- if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
435
- return {
436
- extensionPath,
437
- pi: { ok: true, label: "pi", detail: "fake-pi" },
438
- piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
439
- };
440
- }
441
- const exists = input.exists ?? existsSync3;
442
- const runner = input.commandRunner ?? defaultCommandRunner;
443
- const piResult = await safeRun(runner, ["pi", "--version"]);
444
- const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
445
- const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
446
- ${piListResult.stderr}`);
447
- const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
448
- const hasPiRig = listedPiRig;
449
- return {
450
- extensionPath,
451
- pi: {
452
- ok: piResult.exitCode === 0,
453
- label: "pi",
454
- detail: (piResult.stdout || piResult.stderr).trim() || undefined,
455
- hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
456
- },
457
- piRig: {
458
- ok: hasPiRig,
459
- label: "pi-rig global extension",
460
- detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
461
- hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
462
- }
463
- };
464
- }
465
- async function buildPiSetupChecks(input = {}) {
466
- const status = await checkPiRigInstall(input);
467
- return [status.pi, status.piRig];
468
- }
469
-
470
503
  // packages/cli/src/commands/_preflight.ts
471
504
  function preflightCheck(id, label, status, detail, remediation) {
472
505
  return {
@@ -522,6 +555,9 @@ function permissionAllowsPr(payload) {
522
555
  }
523
556
  return null;
524
557
  }
558
+ function isNotFoundError(error) {
559
+ return /\b(404|not found)\b/i.test(message(error));
560
+ }
525
561
  function projectCheckoutReady(payload) {
526
562
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
527
563
  return null;
@@ -554,19 +590,33 @@ async function runFastTaskRunPreflight(context, options = {}) {
554
590
  const checks = [];
555
591
  const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
556
592
  const taskId = options.taskId?.trim() || null;
593
+ const requiresCurrentRunApi = Boolean(taskId);
594
+ const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
595
+ const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
596
+ let legacyServerCompatibility = false;
557
597
  try {
558
598
  await request("/api/server/status");
559
599
  checks.push(preflightCheck("server", "Rig server reachable", "pass"));
560
600
  } catch (error) {
561
- checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
601
+ if (isNotFoundError(error)) {
602
+ try {
603
+ await request("/health");
604
+ legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
605
+ 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"));
606
+ } catch (healthError) {
607
+ checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
608
+ }
609
+ } else {
610
+ checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
611
+ }
562
612
  }
563
613
  const repo = readRepoConnection(context.projectRoot);
564
- 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", "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig connect use <alias|local>`."));
614
+ checks.push(repo ? preflightCheck("project-link", "project linked to Rig server", 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 server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
565
615
  try {
566
616
  const auth = await request("/api/github/auth/status");
567
- checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
617
+ 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>`."));
568
618
  } catch (error) {
569
- checks.push(preflightCheck("github-auth", "GitHub auth valid", "fail", message(error), "Fix GitHub auth on the selected Rig server."));
619
+ checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
570
620
  }
571
621
  try {
572
622
  const projection = await request("/api/workspace/task-projection");
@@ -594,9 +644,9 @@ async function runFastTaskRunPreflight(context, options = {}) {
594
644
  try {
595
645
  const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
596
646
  const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
597
- checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
647
+ 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."));
598
648
  } catch (error) {
599
- checks.push(preflightCheck("issue", "task/issue accessible", "fail", message(error), "Fix the task source before launching a run."));
649
+ checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
600
650
  }
601
651
  try {
602
652
  const runs = await request("/api/runs?limit=200");
@@ -607,14 +657,7 @@ async function runFastTaskRunPreflight(context, options = {}) {
607
657
  }
608
658
  }
609
659
  if ((options.runtimeAdapter ?? "pi") === "pi") {
610
- const piChecks = await (options.piChecks ?? (() => buildPiSetupChecks()))().catch((error) => [{
611
- ok: false,
612
- label: "pi/pi-rig checks",
613
- hint: message(error)
614
- }]);
615
- for (const pi of piChecks) {
616
- 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.")));
617
- }
660
+ checks.push(preflightCheck("runtime", "worker Pi SDK session daemon", "pass", selectedServer?.connectionKind === "remote" ? "remote worker-owned runtime" : "bundled server-owned runtime"));
618
661
  } else {
619
662
  checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
620
663
  }
@@ -706,7 +749,200 @@ function withMutedConsole(mute, fn) {
706
749
  }
707
750
 
708
751
  // packages/cli/src/commands/_task-picker.ts
709
- import { createInterface } from "readline/promises";
752
+ import { cancel, isCancel, select } from "@clack/prompts";
753
+
754
+ // packages/cli/src/commands/_operator-surface.ts
755
+ import { createInterface } from "readline";
756
+ import { createInterface as createPromptInterface } from "readline/promises";
757
+ var CANONICAL_STAGES = [
758
+ "Connect",
759
+ "GitHub/task sync",
760
+ "Prepare workspace",
761
+ "Launch Pi",
762
+ "Plan",
763
+ "Implement",
764
+ "Validate",
765
+ "Commit",
766
+ "Open PR",
767
+ "Review/CI",
768
+ "Merge",
769
+ "Complete"
770
+ ];
771
+ function logDetail(log) {
772
+ return typeof log.detail === "string" ? log.detail.trim() : "";
773
+ }
774
+ function parseProviderProtocolLog(title, detail) {
775
+ if (title.trim().toLowerCase() !== "agent output")
776
+ return null;
777
+ if (!detail.startsWith("{") || !detail.endsWith("}"))
778
+ return null;
779
+ try {
780
+ const record = JSON.parse(detail);
781
+ if (!record || typeof record !== "object" || Array.isArray(record))
782
+ return null;
783
+ const type = record.type;
784
+ return typeof type === "string" && [
785
+ "assistant",
786
+ "message_start",
787
+ "message_update",
788
+ "message_end",
789
+ "stream_event",
790
+ "tool_result",
791
+ "tool_execution_start",
792
+ "tool_execution_update",
793
+ "tool_execution_end",
794
+ "turn_start",
795
+ "turn_end"
796
+ ].includes(type) ? record : null;
797
+ } catch {
798
+ return null;
799
+ }
800
+ }
801
+ function renderProviderProtocolLog(record) {
802
+ const type = typeof record.type === "string" ? record.type : "";
803
+ if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
804
+ const toolName = String(record.toolName ?? record.name ?? "tool");
805
+ 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";
806
+ return `[Pi tool] ${toolName} ${status}`;
807
+ }
808
+ return null;
809
+ }
810
+ function entryId(entry, fallback) {
811
+ return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
812
+ }
813
+ function renderOperatorSnapshot(snapshot) {
814
+ const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
815
+ const runId = String(run.runId ?? run.id ?? "run");
816
+ const status = String(run.status ?? "unknown");
817
+ const logs = snapshot.logs ?? [];
818
+ const latestByStage = new Map;
819
+ for (const log of logs) {
820
+ const title = String(log.title ?? "").toLowerCase();
821
+ const stageName = String(log.stage ?? "").toLowerCase();
822
+ const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
823
+ if (stage)
824
+ latestByStage.set(stage, log);
825
+ }
826
+ const stageLines = CANONICAL_STAGES.flatMap((stage) => {
827
+ const match = latestByStage.get(stage);
828
+ return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
829
+ });
830
+ return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
831
+ `);
832
+ }
833
+ function createPiRunStreamRenderer(output = process.stdout) {
834
+ let lastSnapshot = "";
835
+ const assistantTextById = new Map;
836
+ const seenTimeline = new Set;
837
+ const seenLogs = new Set;
838
+ const writeLine = (line) => output.write(`${line}
839
+ `);
840
+ return {
841
+ renderSnapshot(snapshot) {
842
+ const rendered = renderOperatorSnapshot(snapshot);
843
+ if (rendered && rendered !== lastSnapshot) {
844
+ writeLine(rendered);
845
+ lastSnapshot = rendered;
846
+ }
847
+ },
848
+ renderTimeline(entries) {
849
+ for (const [index, entry] of entries.entries()) {
850
+ const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
851
+ if (entry.type === "assistant_message" && typeof entry.text === "string") {
852
+ const text = entry.text;
853
+ const previousText = assistantTextById.get(id) ?? "";
854
+ if (!previousText && text.trim()) {
855
+ writeLine("[Pi assistant]");
856
+ }
857
+ if (text.startsWith(previousText)) {
858
+ const delta = text.slice(previousText.length);
859
+ if (delta)
860
+ output.write(delta);
861
+ } else if (text.trim() && text !== previousText) {
862
+ if (previousText)
863
+ writeLine(`
864
+ [Pi assistant]`);
865
+ output.write(text);
866
+ }
867
+ assistantTextById.set(id, text);
868
+ continue;
869
+ }
870
+ if (seenTimeline.has(id))
871
+ continue;
872
+ seenTimeline.add(id);
873
+ if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
874
+ writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
875
+ continue;
876
+ }
877
+ if (entry.type === "timeline_warning") {
878
+ writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
879
+ continue;
880
+ }
881
+ if (entry.type === "action") {
882
+ const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
883
+ if (text)
884
+ writeLine(`[Rig action] ${text}`);
885
+ continue;
886
+ }
887
+ if (entry.type === "user_message") {
888
+ const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
889
+ if (text)
890
+ writeLine(`[Operator] ${text}`);
891
+ continue;
892
+ }
893
+ const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
894
+ if (fallback)
895
+ writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
896
+ }
897
+ },
898
+ renderLogs(entries) {
899
+ for (const [index, entry] of entries.entries()) {
900
+ const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
901
+ if (seenLogs.has(id))
902
+ continue;
903
+ seenLogs.add(id);
904
+ const title = String(entry.title ?? "");
905
+ if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
906
+ continue;
907
+ const detail = logDetail(entry);
908
+ if (!detail)
909
+ continue;
910
+ const protocolRecord = parseProviderProtocolLog(title, detail);
911
+ if (protocolRecord) {
912
+ const protocolLine = renderProviderProtocolLog(protocolRecord);
913
+ if (protocolLine)
914
+ writeLine(protocolLine);
915
+ continue;
916
+ }
917
+ writeLine(`[${title || "Rig log"}] ${detail}`);
918
+ }
919
+ }
920
+ };
921
+ }
922
+ function createOperatorSurface(options = {}) {
923
+ const input = options.input ?? process.stdin;
924
+ const output = options.output ?? process.stdout;
925
+ const errorOutput = options.errorOutput ?? process.stderr;
926
+ const renderer = createPiRunStreamRenderer(output);
927
+ const writeLine = (line) => output.write(`${line}
928
+ `);
929
+ return {
930
+ mode: "pi-compatible-text",
931
+ ...renderer,
932
+ info: writeLine,
933
+ error: (message2) => errorOutput.write(`${message2}
934
+ `),
935
+ attachCommandInput(handler) {
936
+ if (options.interactive === false || !input.isTTY)
937
+ return null;
938
+ const rl = createInterface({ input, output: process.stdout, terminal: false });
939
+ rl.on("line", (line) => {
940
+ Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
941
+ });
942
+ return { close: () => rl.close() };
943
+ }
944
+ };
945
+ }
710
946
  function taskId(task) {
711
947
  return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
712
948
  }
@@ -719,6 +955,19 @@ function taskStatus(task) {
719
955
  function renderTaskPickerRows(tasks) {
720
956
  return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
721
957
  }
958
+ async function promptForTaskSelection(question) {
959
+ const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
960
+ try {
961
+ return await rl.question(question);
962
+ } finally {
963
+ rl.close();
964
+ }
965
+ }
966
+
967
+ // packages/cli/src/commands/_task-picker.ts
968
+ function taskId2(task) {
969
+ return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
970
+ }
722
971
  async function selectTaskWithTextPicker(tasks, io = {}) {
723
972
  if (tasks.length === 0)
724
973
  return null;
@@ -728,56 +977,800 @@ async function selectTaskWithTextPicker(tasks, io = {}) {
728
977
  if (!isTty) {
729
978
  throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
730
979
  }
731
- const prompt = io.prompt ?? (async (question) => {
732
- const rl = createInterface({ input: process.stdin, output: process.stdout });
733
- try {
734
- return await rl.question(question);
735
- } finally {
736
- rl.close();
980
+ if (io.prompt || io.renderer) {
981
+ const prompt = io.prompt ?? promptForTaskSelection;
982
+ const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
983
+ `) };
984
+ renderer.writeLine("Select Rig task:");
985
+ for (const row of renderTaskPickerRows(tasks))
986
+ renderer.writeLine(` ${row}`);
987
+ const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
988
+ if (!answer2)
989
+ return null;
990
+ if (/^\d+$/.test(answer2)) {
991
+ const index2 = Number.parseInt(answer2, 10) - 1;
992
+ return tasks[index2] ?? null;
737
993
  }
994
+ return tasks.find((task) => taskId2(task) === answer2) ?? null;
995
+ }
996
+ const options = tasks.map((task, index2) => ({
997
+ value: `${index2}`,
998
+ label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
999
+ hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
1000
+ }));
1001
+ const answer = await select({
1002
+ message: "Select Rig task",
1003
+ options
738
1004
  });
739
- console.log("Select Rig task:");
740
- for (const row of renderTaskPickerRows(tasks))
741
- console.log(` ${row}`);
742
- const answer = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
743
- if (!answer)
1005
+ if (isCancel(answer)) {
1006
+ cancel("No task selected.");
744
1007
  return null;
745
- if (/^\d+$/.test(answer)) {
746
- const index = Number.parseInt(answer, 10) - 1;
747
- return tasks[index] ?? null;
748
1008
  }
749
- return tasks.find((task) => taskId(task) === answer) ?? null;
1009
+ const index = Number.parseInt(String(answer), 10);
1010
+ return Number.isFinite(index) ? tasks[index] ?? null : null;
750
1011
  }
751
1012
 
752
- // packages/cli/src/commands/_operator-view.ts
753
- import { createInterface as createInterface2 } from "readline";
1013
+ // packages/cli/src/commands/_pi-frontend.ts
1014
+ import { mkdtempSync, rmSync } from "fs";
1015
+ import { tmpdir } from "os";
1016
+ import { join } from "path";
1017
+ import {
1018
+ createAgentSessionFromServices,
1019
+ createAgentSessionServices,
1020
+ main as runPiMain
1021
+ } from "@earendil-works/pi-coding-agent";
1022
+
1023
+ // packages/cli/src/commands/_pi-remote-session.ts
1024
+ import { AgentSession as PiAgentSession, expandPromptTemplate } from "@earendil-works/pi-coding-agent";
754
1025
  var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
755
- var CANONICAL_STAGES = [
756
- "Connect",
757
- "GitHub/task sync",
758
- "Prepare workspace",
759
- "Launch Pi",
760
- "Plan",
761
- "Implement",
762
- "Validate",
763
- "Commit",
764
- "Open PR",
765
- "Review/CI",
766
- "Merge",
767
- "Complete"
768
- ];
769
- function renderOperatorSnapshot(snapshot) {
770
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
771
- const runId = String(run.runId ?? run.id ?? "run");
772
- const status = String(run.status ?? "unknown");
773
- const logs = snapshot.logs ?? [];
774
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
775
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
776
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
1026
+ function defaultTransport() {
1027
+ return {
1028
+ getSession: getRunPiSessionViaServer,
1029
+ getMessages: getRunPiMessagesViaServer,
1030
+ getStatus: getRunPiStatusViaServer,
1031
+ getCommands: getRunPiCommandsViaServer,
1032
+ getCapabilities: getRunPiCapabilitiesViaServer,
1033
+ sendPrompt: sendRunPiPromptViaServer,
1034
+ sendShell: sendRunPiShellViaServer,
1035
+ runCommand: runRunPiCommandViaServer,
1036
+ abort: abortRunPiViaServer,
1037
+ buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
1038
+ };
1039
+ }
1040
+ function recordOf(value) {
1041
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1042
+ }
1043
+ function emptyRemoteStatus() {
1044
+ return {
1045
+ isStreaming: false,
1046
+ isCompacting: false,
1047
+ isBashRunning: false,
1048
+ pendingMessageCount: 0,
1049
+ steeringMessages: [],
1050
+ followUpMessages: [],
1051
+ model: null,
1052
+ thinkingLevel: null,
1053
+ sessionName: null,
1054
+ cwd: null,
1055
+ stats: null,
1056
+ contextUsage: null
1057
+ };
1058
+ }
1059
+ function resolveAttachReadyTimeoutMs() {
1060
+ const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
1061
+ return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
1062
+ }
1063
+
1064
+ class RigRemoteSessionController {
1065
+ context;
1066
+ runId;
1067
+ status = emptyRemoteStatus();
1068
+ transport;
1069
+ hooks = {};
1070
+ session = null;
1071
+ socket = null;
1072
+ closed = false;
1073
+ pendingShells = [];
1074
+ pendingCompactions = [];
1075
+ constructor(input) {
1076
+ this.context = input.context;
1077
+ this.runId = input.runId;
1078
+ this.transport = input.transport ?? defaultTransport();
1079
+ }
1080
+ ingestEnvelope(envelopeValue) {
1081
+ this.applyEnvelope(envelopeValue);
1082
+ }
1083
+ bindSession(session) {
1084
+ this.session = session;
1085
+ }
1086
+ setUiHooks(hooks) {
1087
+ this.hooks = hooks;
1088
+ }
1089
+ async connect() {
1090
+ const ready = await this.waitForReady();
1091
+ if (!ready || this.closed)
1092
+ return;
1093
+ let catchupDone = false;
1094
+ const buffered = [];
1095
+ const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
1096
+ const socket = new WebSocket(wsUrl);
1097
+ this.socket = socket;
1098
+ socket.onopen = () => {
1099
+ this.hooks.onConnectionChange?.(true);
1100
+ this.hooks.onStatusText?.("worker session live");
1101
+ };
1102
+ socket.onmessage = (message2) => {
1103
+ try {
1104
+ const payload = typeof message2.data === "string" ? JSON.parse(message2.data) : JSON.parse(Buffer.from(message2.data).toString("utf8"));
1105
+ if (!catchupDone)
1106
+ buffered.push(payload);
1107
+ else
1108
+ this.applyEnvelope(payload);
1109
+ } catch (error) {
1110
+ this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
1111
+ }
1112
+ };
1113
+ socket.onerror = () => socket.close();
1114
+ socket.onclose = () => {
1115
+ this.hooks.onConnectionChange?.(false);
1116
+ if (!this.closed)
1117
+ this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
1118
+ };
1119
+ try {
1120
+ const [messagesPayload, statusPayload, commandsPayload, capabilitiesPayload] = await Promise.all([
1121
+ this.transport.getMessages(this.context, this.runId),
1122
+ this.transport.getStatus(this.context, this.runId),
1123
+ this.transport.getCommands(this.context, this.runId),
1124
+ this.transport.getCapabilities(this.context, this.runId).catch(() => ({ capabilities: null }))
1125
+ ]);
1126
+ const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
1127
+ this.applyStatusPayload(statusPayload);
1128
+ this.session?.replaceRemoteMessages(messages);
1129
+ const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
1130
+ const capabilities = capabilitiesPayload.capabilities && typeof capabilitiesPayload.capabilities === "object" && !Array.isArray(capabilitiesPayload.capabilities) ? capabilitiesPayload.capabilities : null;
1131
+ this.hooks.onCatchUp?.(messages, commands, capabilities);
1132
+ catchupDone = true;
1133
+ for (const payload of buffered.splice(0))
1134
+ this.applyEnvelope(payload);
1135
+ } catch (error) {
1136
+ catchupDone = true;
1137
+ this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
1138
+ }
1139
+ }
1140
+ close() {
1141
+ this.closed = true;
1142
+ this.socket?.close();
1143
+ for (const shell of this.pendingShells.splice(0))
1144
+ shell.reject(new Error("Remote session closed."));
1145
+ for (const compaction of this.pendingCompactions.splice(0))
1146
+ compaction.reject(new Error("Remote session closed."));
1147
+ }
1148
+ async sendPrompt(text, streamingBehavior) {
1149
+ await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
1150
+ }
1151
+ async sendCommand(text) {
1152
+ const result = await this.transport.runCommand(this.context, this.runId, text);
1153
+ return typeof result.message === "string" ? result.message : "worker command accepted";
1154
+ }
1155
+ async sendShell(text) {
1156
+ await this.transport.sendShell(this.context, this.runId, text);
1157
+ }
1158
+ async abort() {
1159
+ await this.transport.abort(this.context, this.runId);
1160
+ }
1161
+ registerPendingShell(shell) {
1162
+ this.pendingShells.push(shell);
1163
+ }
1164
+ failPendingShell(shell, error) {
1165
+ const index = this.pendingShells.indexOf(shell);
1166
+ if (index !== -1)
1167
+ this.pendingShells.splice(index, 1);
1168
+ shell.reject(error);
1169
+ }
1170
+ registerPendingCompaction(pending) {
1171
+ this.pendingCompactions.push(pending);
1172
+ }
1173
+ async waitForReady() {
1174
+ const startedAt = Date.now();
1175
+ const deadline = startedAt + resolveAttachReadyTimeoutMs();
1176
+ let consecutiveFailures = 0;
1177
+ while (!this.closed) {
1178
+ let requestFailed = false;
1179
+ const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
1180
+ requestFailed = true;
1181
+ return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
1182
+ });
1183
+ if (session.ready !== false)
1184
+ return true;
1185
+ consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
1186
+ const status = String(session.status ?? "starting");
1187
+ if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
1188
+ this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
1189
+ return false;
1190
+ }
1191
+ this.hooks.onStatusText?.(consecutiveFailures >= 5 ? "Rig server unreachable \xB7 retrying \xB7 /detach to exit" : `waiting for worker Pi daemon \xB7 ${status} \xB7 /detach to exit`);
1192
+ if (Date.now() >= deadline) {
1193
+ this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
1194
+ return false;
1195
+ }
1196
+ await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
1197
+ }
1198
+ return false;
1199
+ }
1200
+ applyEnvelope(envelopeValue) {
1201
+ const envelope = recordOf(envelopeValue);
1202
+ if (!envelope)
1203
+ return;
1204
+ const type = String(envelope.type ?? "");
1205
+ if (type === "status.update") {
1206
+ this.applyStatusPayload(envelope);
1207
+ return;
1208
+ }
1209
+ if (type === "activity.update") {
1210
+ const activity = recordOf(envelope.activity);
1211
+ this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
1212
+ return;
1213
+ }
1214
+ if (type === "extension_ui_request") {
1215
+ const request = recordOf(envelope.request);
1216
+ if (request)
1217
+ this.hooks.onExtensionUiRequest?.(request);
1218
+ return;
1219
+ }
1220
+ if (type === "pi.ui_event") {
1221
+ this.applyShellUiEvent(envelope.event);
1222
+ return;
1223
+ }
1224
+ if (type === "pi.event") {
1225
+ this.session?.handleRemoteSessionEvent(envelope.event);
1226
+ this.settlePendingCompaction(envelope.event);
1227
+ return;
1228
+ }
1229
+ if (type === "error") {
1230
+ this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
1231
+ }
1232
+ }
1233
+ applyStatusPayload(payload) {
1234
+ const status = recordOf(payload.status) ?? payload;
1235
+ const next = this.status;
1236
+ next.isStreaming = status.isStreaming === true;
1237
+ next.isCompacting = status.isCompacting === true;
1238
+ next.isBashRunning = status.isBashRunning === true;
1239
+ next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
1240
+ next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
1241
+ next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
1242
+ next.model = recordOf(status.model) ?? next.model;
1243
+ next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
1244
+ next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
1245
+ next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
1246
+ next.stats = recordOf(status.stats) ?? next.stats;
1247
+ next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
1248
+ }
1249
+ applyShellUiEvent(value) {
1250
+ const event = recordOf(value);
1251
+ if (!event)
1252
+ return;
1253
+ const type = String(event.type ?? "");
1254
+ const pending = this.pendingShells[0];
1255
+ if (type === "shell.chunk" && pending) {
1256
+ pending.sawChunk = true;
1257
+ pending.onData(Buffer.from(String(event.chunk ?? "")));
1258
+ return;
1259
+ }
1260
+ if (type === "shell.end" && pending) {
1261
+ const output = String(event.output ?? "");
1262
+ if (output && !pending.sawChunk)
1263
+ pending.onData(Buffer.from(output));
1264
+ const index = this.pendingShells.indexOf(pending);
1265
+ if (index !== -1)
1266
+ this.pendingShells.splice(index, 1);
1267
+ pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
1268
+ }
1269
+ }
1270
+ settlePendingCompaction(eventValue) {
1271
+ const event = recordOf(eventValue);
1272
+ if (!event)
1273
+ return;
1274
+ const type = String(event.type ?? "");
1275
+ if (type !== "compaction_end" || this.pendingCompactions.length === 0)
1276
+ return;
1277
+ const pending = this.pendingCompactions.shift();
1278
+ const result = recordOf(event.result);
1279
+ if (result)
1280
+ pending.resolve(result);
1281
+ else if (event.aborted === true)
1282
+ pending.reject(new Error("Compaction aborted on the worker."));
1283
+ else
1284
+ pending.resolve({});
1285
+ }
1286
+ }
1287
+
1288
+ class RigRemoteAgentSession extends PiAgentSession {
1289
+ remote;
1290
+ constructor(config, remote) {
1291
+ super(config);
1292
+ this.remote = remote;
1293
+ remote.bindSession(this);
1294
+ }
1295
+ handleRemoteSessionEvent(eventValue) {
1296
+ const event = recordOf(eventValue);
1297
+ if (!event)
1298
+ return;
1299
+ const type = String(event.type ?? "");
1300
+ if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
1301
+ this.agent.state.messages = [...this.agent.state.messages, event.message];
1302
+ }
1303
+ this._emit(eventValue);
1304
+ }
1305
+ replaceRemoteMessages(messages) {
1306
+ this.agent.state.messages = messages;
1307
+ }
1308
+ async expandLocalInput(text) {
1309
+ let current = text;
1310
+ const runner = this.extensionRunner;
1311
+ if (runner.hasHandlers("input")) {
1312
+ const result = await runner.emitInput(current, undefined, "interactive");
1313
+ if (result.action === "handled")
1314
+ return null;
1315
+ if (result.action === "transform")
1316
+ current = result.text;
1317
+ }
1318
+ current = this._expandSkillCommand(current);
1319
+ current = expandPromptTemplate(current, [...this.promptTemplates]);
1320
+ return current;
1321
+ }
1322
+ async prompt(text, options) {
1323
+ const trimmed = text.trim();
1324
+ if (!trimmed)
1325
+ return;
1326
+ if (trimmed.startsWith("/")) {
1327
+ if (await this._tryExecuteExtensionCommand(trimmed))
1328
+ return;
1329
+ const expanded2 = await this.expandLocalInput(trimmed);
1330
+ if (expanded2 === null)
1331
+ return;
1332
+ if (expanded2 !== trimmed) {
1333
+ const behavior2 = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
1334
+ options?.preflightResult?.(true);
1335
+ await this.remote.sendPrompt(expanded2, behavior2);
1336
+ return;
1337
+ }
1338
+ await this.remote.sendCommand(trimmed);
1339
+ return;
1340
+ }
1341
+ if (trimmed.startsWith("!")) {
1342
+ await this.remote.sendShell(trimmed);
1343
+ return;
1344
+ }
1345
+ const expanded = await this.expandLocalInput(trimmed);
1346
+ if (expanded === null)
1347
+ return;
1348
+ const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
1349
+ options?.preflightResult?.(true);
1350
+ await this.remote.sendPrompt(expanded, behavior);
1351
+ }
1352
+ async steer(text) {
1353
+ const trimmed = text.trim();
1354
+ if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
1355
+ return;
1356
+ const expanded = await this.expandLocalInput(trimmed);
1357
+ if (expanded === null)
1358
+ return;
1359
+ await this.remote.sendPrompt(expanded, "steer");
1360
+ }
1361
+ async followUp(text) {
1362
+ const trimmed = text.trim();
1363
+ if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
1364
+ return;
1365
+ const expanded = await this.expandLocalInput(trimmed);
1366
+ if (expanded === null)
1367
+ return;
1368
+ await this.remote.sendPrompt(expanded, "followUp");
1369
+ }
1370
+ async abort() {
1371
+ await this.remote.abort();
1372
+ }
1373
+ async compact(customInstructions) {
1374
+ const pending = new Promise((resolve3, reject) => {
1375
+ this.remote.registerPendingCompaction({ resolve: resolve3, reject });
1376
+ });
1377
+ await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
1378
+ return pending;
1379
+ }
1380
+ clearQueue() {
1381
+ const cleared = {
1382
+ steering: [...this.remote.status.steeringMessages],
1383
+ followUp: [...this.remote.status.followUpMessages]
1384
+ };
1385
+ this.remote.status.steeringMessages = [];
1386
+ this.remote.status.followUpMessages = [];
1387
+ this.remote.status.pendingMessageCount = 0;
1388
+ this.remote.sendCommand("/queue-clear").catch(() => {});
1389
+ return cleared;
1390
+ }
1391
+ get isStreaming() {
1392
+ return this.remote.status.isStreaming;
1393
+ }
1394
+ get isCompacting() {
1395
+ return this.remote.status.isCompacting;
1396
+ }
1397
+ get isBashRunning() {
1398
+ return this.remote.status.isBashRunning;
1399
+ }
1400
+ get pendingMessageCount() {
1401
+ return this.remote.status.pendingMessageCount;
1402
+ }
1403
+ getSteeringMessages() {
1404
+ return this.remote.status.steeringMessages;
1405
+ }
1406
+ getFollowUpMessages() {
1407
+ return this.remote.status.followUpMessages;
1408
+ }
1409
+ get model() {
1410
+ return this.remote.status.model ?? super.model;
1411
+ }
1412
+ async setModel(model) {
1413
+ await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
1414
+ this.remote.status.model = model;
1415
+ }
1416
+ get thinkingLevel() {
1417
+ return this.remote.status.thinkingLevel ?? super.thinkingLevel;
1418
+ }
1419
+ setThinkingLevel(level) {
1420
+ this.remote.status.thinkingLevel = level;
1421
+ this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
1422
+ }
1423
+ get sessionName() {
1424
+ return this.remote.status.sessionName ?? super.sessionName;
1425
+ }
1426
+ setSessionName(name) {
1427
+ this.remote.status.sessionName = name;
1428
+ this.remote.sendCommand(`/name ${name}`).catch(() => {});
1429
+ }
1430
+ getSessionStats() {
1431
+ return this.remote.status.stats ?? super.getSessionStats();
1432
+ }
1433
+ getContextUsage() {
1434
+ return this.remote.status.contextUsage ?? super.getContextUsage();
1435
+ }
1436
+ dispose() {
1437
+ this.remote.close();
1438
+ super.dispose();
1439
+ }
1440
+ }
1441
+ function createRemoteBashOperations(controller, excludeFromContext) {
1442
+ return {
1443
+ exec(command, _cwd, execOptions) {
1444
+ return new Promise((resolve3, reject) => {
1445
+ const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
1446
+ const cleanup = () => {
1447
+ execOptions.signal?.removeEventListener("abort", onAbort);
1448
+ if (timer)
1449
+ clearTimeout(timer);
1450
+ };
1451
+ const onAbort = () => {
1452
+ cleanup();
1453
+ controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
1454
+ };
1455
+ const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
1456
+ const timer = timeoutMs > 0 ? setTimeout(() => {
1457
+ cleanup();
1458
+ controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
1459
+ }, timeoutMs) : null;
1460
+ const wrappedResolve = pending.resolve;
1461
+ const wrappedReject = pending.reject;
1462
+ pending.resolve = (result) => {
1463
+ cleanup();
1464
+ wrappedResolve(result);
1465
+ };
1466
+ pending.reject = (error) => {
1467
+ cleanup();
1468
+ wrappedReject(error);
1469
+ };
1470
+ execOptions.signal?.addEventListener("abort", onAbort, { once: true });
1471
+ controller.registerPendingShell(pending);
1472
+ controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
1473
+ cleanup();
1474
+ controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
1475
+ });
1476
+ });
1477
+ }
1478
+ };
1479
+ }
1480
+
1481
+ // packages/cli/src/commands/_spinner.ts
1482
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1483
+
1484
+ // packages/cli/src/commands/_pi-worker-bridge-extension.ts
1485
+ function recordOf2(value) {
1486
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1487
+ }
1488
+ function asText(value) {
1489
+ if (typeof value === "string")
1490
+ return value;
1491
+ if (value === null || value === undefined)
1492
+ return "";
1493
+ if (typeof value === "number" || typeof value === "boolean")
1494
+ return String(value);
1495
+ try {
1496
+ return JSON.stringify(value);
1497
+ } catch {
1498
+ return String(value);
1499
+ }
1500
+ }
1501
+ function names(value, key = "name") {
1502
+ if (!Array.isArray(value))
1503
+ return [];
1504
+ return value.flatMap((entry) => {
1505
+ if (typeof entry === "string")
1506
+ return [entry];
1507
+ const record = recordOf2(entry);
1508
+ const name = record?.[key];
1509
+ return typeof name === "string" ? [name] : [];
777
1510
  });
778
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
779
- `);
780
1511
  }
1512
+ function renderWorkerCapabilities(capabilities) {
1513
+ const lines = ["Worker session capabilities (in effect for this run)"];
1514
+ const tools = Array.isArray(capabilities.tools) ? capabilities.tools : [];
1515
+ const activeTools = tools.flatMap((tool) => {
1516
+ const record = recordOf2(tool);
1517
+ return record && record.active === true && typeof record.name === "string" ? [record.name] : [];
1518
+ });
1519
+ const inactiveCount = tools.length - activeTools.length;
1520
+ lines.push(` tools ${activeTools.join(", ") || "(none)"}${inactiveCount > 0 ? ` (+${inactiveCount} inactive)` : ""}`);
1521
+ const extensions = Array.isArray(capabilities.extensions) ? capabilities.extensions : [];
1522
+ const extensionLabels = extensions.flatMap((entry) => {
1523
+ const record = recordOf2(entry);
1524
+ if (!record)
1525
+ return [];
1526
+ const path = typeof record.path === "string" ? record.path : "";
1527
+ const short = path.split("/").filter(Boolean).slice(-2).join("/") || path || "extension";
1528
+ return [short];
1529
+ });
1530
+ lines.push(` extensions ${extensionLabels.join(", ") || "(none)"}`);
1531
+ const hookEvents = names(capabilities.hookEvents);
1532
+ const hookList = Array.isArray(capabilities.hookEvents) ? capabilities.hookEvents.map(asText).filter(Boolean) : hookEvents;
1533
+ lines.push(` hooks ${hookList.join(", ") || "(none)"}`);
1534
+ lines.push(` skills ${names(capabilities.skills).join(", ") || "(none)"}`);
1535
+ lines.push(` prompts ${names(capabilities.prompts).join(", ") || "(none)"}`);
1536
+ const model = typeof capabilities.model === "string" ? capabilities.model : "(unknown)";
1537
+ const thinking = typeof capabilities.thinkingLevel === "string" ? capabilities.thinkingLevel : "";
1538
+ const cwd = typeof capabilities.cwd === "string" ? capabilities.cwd : "";
1539
+ lines.push(` model ${model}${thinking ? ` \xB7 ${thinking}` : ""}`);
1540
+ if (cwd)
1541
+ lines.push(` cwd ${cwd}`);
1542
+ lines.push(" (worker commands are in your palette as [worker \u2026] \xB7 /worker shows this again)");
1543
+ return lines;
1544
+ }
1545
+ async function answerExtensionUiRequest(options, ctx, request) {
1546
+ const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
1547
+ const method = String(request.method ?? request.type ?? "input");
1548
+ const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
1549
+ const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
1550
+ const choices = rawOptions.map((option) => {
1551
+ const record = recordOf2(option);
1552
+ return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
1553
+ }).filter(Boolean);
1554
+ try {
1555
+ if (method === "confirm") {
1556
+ const confirmed = await ctx.ui.confirm("Worker request", prompt);
1557
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
1558
+ return;
1559
+ }
1560
+ if (choices.length > 0) {
1561
+ const selected = await ctx.ui.select(prompt, choices);
1562
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
1563
+ return;
1564
+ }
1565
+ const value = await ctx.ui.input("Worker request", prompt);
1566
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
1567
+ } catch (error) {
1568
+ ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
1569
+ }
1570
+ }
1571
+ var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "worker", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
1572
+ function registerDaemonCommands(pi, options, ctx, commands, registered) {
1573
+ for (const command of commands) {
1574
+ const record = recordOf2(command);
1575
+ const name = typeof record?.name === "string" ? record.name : "";
1576
+ const source = typeof record?.source === "string" ? record.source : "worker";
1577
+ if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
1578
+ continue;
1579
+ registered.add(name);
1580
+ const description = typeof record?.description === "string" ? record.description : undefined;
1581
+ try {
1582
+ pi.registerCommand(name, {
1583
+ description: `[worker ${source}] ${description ?? ""}`.trim(),
1584
+ handler: async (args) => {
1585
+ try {
1586
+ const message2 = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
1587
+ ctx.ui.notify(message2, "info");
1588
+ } catch (error) {
1589
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1590
+ }
1591
+ }
1592
+ });
1593
+ } catch {}
1594
+ }
1595
+ }
1596
+ function createRigWorkerPiBridgeExtension(options) {
1597
+ return (pi) => {
1598
+ const registeredDaemonCommands = new Set;
1599
+ let capabilityLines = null;
1600
+ let statusText = "connecting to worker session";
1601
+ let busy = true;
1602
+ let connected = false;
1603
+ let frame = 0;
1604
+ let spinnerTimer = null;
1605
+ const renderStatus = (ctx) => {
1606
+ const prefix = busy ? `${SPINNER_FRAMES[frame]} ` : connected ? "\u25CF " : "\u25CB ";
1607
+ ctx.ui.setStatus("rig-worker-pi", `${prefix}${statusText}`);
1608
+ };
1609
+ const setStatus = (ctx, text, isBusy) => {
1610
+ statusText = text;
1611
+ busy = isBusy;
1612
+ renderStatus(ctx);
1613
+ };
1614
+ pi.registerCommand("detach", {
1615
+ description: "Detach from this run; the worker keeps going",
1616
+ handler: async (_args, ctx) => {
1617
+ ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
1618
+ ctx.shutdown();
1619
+ }
1620
+ });
1621
+ pi.registerCommand("stop", {
1622
+ description: "Stop the worker Pi run and detach",
1623
+ handler: async (_args, ctx) => {
1624
+ await options.controller.abort();
1625
+ ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
1626
+ ctx.shutdown();
1627
+ }
1628
+ });
1629
+ pi.registerCommand("worker", {
1630
+ description: "Show the worker session's real capabilities (tools, extensions, hooks, skills)",
1631
+ handler: async (_args, ctx) => {
1632
+ if (capabilityLines)
1633
+ ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
1634
+ else
1635
+ ctx.ui.notify("Worker capabilities are not available yet (still connecting).", "info");
1636
+ }
1637
+ });
1638
+ pi.on("user_bash", (event) => ({
1639
+ operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
1640
+ }));
1641
+ pi.on("session_start", async (_event, ctx) => {
1642
+ ctx.ui.setTitle("Rig \xB7 enriched bundled Pi");
1643
+ setStatus(ctx, "waiting for worker Pi daemon", true);
1644
+ spinnerTimer = setInterval(() => {
1645
+ frame = (frame + 1) % SPINNER_FRAMES.length;
1646
+ if (busy)
1647
+ renderStatus(ctx);
1648
+ }, 150);
1649
+ ctx.ui.notify(`Enriched bundled Pi \u2014 native UI + Rig layers, worker brain. Attached to run ${options.runId}. /worker shows live capabilities \xB7 /detach exits \xB7 /stop cancels.`, "info");
1650
+ if (options.initialMessageSent)
1651
+ ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
1652
+ const nativeUi = ctx.ui;
1653
+ options.controller.setUiHooks({
1654
+ onStatusText: (text) => setStatus(ctx, text, !connected),
1655
+ onActivity: (label, detail) => {
1656
+ const active = label !== "idle" && !/complete|ready/i.test(label);
1657
+ setStatus(ctx, [label, detail].filter(Boolean).join(" \u2014 "), active);
1658
+ if (/agent running|tool:/.test(label))
1659
+ ctx.ui.setWidget("rig-worker-capabilities", undefined);
1660
+ },
1661
+ onConnectionChange: (nextConnected) => {
1662
+ connected = nextConnected;
1663
+ setStatus(ctx, nextConnected ? "worker session live" : "worker session disconnected", false);
1664
+ },
1665
+ onError: (message2) => ctx.ui.notify(message2, "error"),
1666
+ onExtensionUiRequest: (request) => {
1667
+ answerExtensionUiRequest(options, ctx, request);
1668
+ },
1669
+ onCatchUp: (messages, commands, capabilities) => {
1670
+ if (nativeUi.appendSessionMessages)
1671
+ nativeUi.appendSessionMessages(messages);
1672
+ const cwd = options.controller.status.cwd;
1673
+ if (nativeUi.setDisplayCwd && cwd)
1674
+ nativeUi.setDisplayCwd(cwd);
1675
+ registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
1676
+ if (capabilities) {
1677
+ capabilityLines = renderWorkerCapabilities(capabilities);
1678
+ ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
1679
+ }
1680
+ }
1681
+ });
1682
+ options.controller.connect().catch((error) => {
1683
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1684
+ });
1685
+ });
1686
+ pi.on("session_shutdown", () => {
1687
+ if (spinnerTimer)
1688
+ clearInterval(spinnerTimer);
1689
+ options.controller.close();
1690
+ });
1691
+ };
1692
+ }
1693
+
1694
+ // packages/cli/src/commands/_pi-frontend.ts
1695
+ function setTemporaryEnv(updates) {
1696
+ const previous = new Map;
1697
+ for (const [key, value] of Object.entries(updates)) {
1698
+ previous.set(key, process.env[key]);
1699
+ process.env[key] = value;
1700
+ }
1701
+ return () => {
1702
+ for (const [key, value] of previous) {
1703
+ if (value === undefined)
1704
+ delete process.env[key];
1705
+ else
1706
+ process.env[key] = value;
1707
+ }
1708
+ };
1709
+ }
1710
+ async function attachRunBundledPiFrontend(context, input) {
1711
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1712
+ const restoreEnv = setTemporaryEnv({
1713
+ PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
1714
+ PI_SKIP_VERSION_CHECK: "1",
1715
+ PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust"
1716
+ });
1717
+ const controller = new RigRemoteSessionController({ context, runId: input.runId });
1718
+ const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
1719
+ const services = await createAgentSessionServices({
1720
+ cwd,
1721
+ agentDir,
1722
+ resourceLoaderOptions: {
1723
+ extensionFactories: [
1724
+ createRigWorkerPiBridgeExtension({
1725
+ context,
1726
+ controller,
1727
+ runId: input.runId,
1728
+ initialMessageSent: input.steered === true
1729
+ })
1730
+ ],
1731
+ noExtensions: true,
1732
+ noSkills: true,
1733
+ noPromptTemplates: true,
1734
+ noContextFiles: true
1735
+ }
1736
+ });
1737
+ const created = await createAgentSessionFromServices({
1738
+ services,
1739
+ sessionManager,
1740
+ sessionStartEvent,
1741
+ noTools: "all",
1742
+ sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
1743
+ });
1744
+ return { ...created, services, diagnostics: services.diagnostics };
1745
+ };
1746
+ let detached = false;
1747
+ try {
1748
+ await runPiMain([], {
1749
+ createRuntimeOverride: () => createRemoteRuntime
1750
+ });
1751
+ detached = true;
1752
+ } finally {
1753
+ restoreEnv();
1754
+ controller.close();
1755
+ rmSync(tempSessionDir, { recursive: true, force: true });
1756
+ }
1757
+ let run = { runId: input.runId, status: "unknown" };
1758
+ try {
1759
+ run = await getRunDetailsViaServer(context, input.runId);
1760
+ } catch {}
1761
+ return {
1762
+ run,
1763
+ logs: [],
1764
+ timeline: [],
1765
+ timelineCursor: null,
1766
+ steered: input.steered === true,
1767
+ detached,
1768
+ rendered: "enriched bundled Pi frontend with remote worker session runtime"
1769
+ };
1770
+ }
1771
+
1772
+ // packages/cli/src/commands/_operator-view.ts
1773
+ var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
781
1774
  function runStatusFromPayload(payload) {
782
1775
  const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
783
1776
  return String(run.status ?? "unknown").toLowerCase();
@@ -799,56 +1792,640 @@ async function applyOperatorCommand(context, input, deps = {}) {
799
1792
  await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
800
1793
  return { action: "continue", message: "Steering message queued." };
801
1794
  }
802
- async function readOperatorSnapshot(context, runId) {
1795
+ async function readOperatorSnapshot(context, runId, options = {}) {
803
1796
  const run = await getRunDetailsViaServer(context, runId);
804
1797
  const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
805
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
806
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
1798
+ const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
1799
+ entries: [{
1800
+ id: `timeline-unavailable:${runId}`,
1801
+ type: "timeline_warning",
1802
+ detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
1803
+ createdAt: new Date().toISOString()
1804
+ }],
1805
+ nextCursor: options.timelineCursor ?? null
1806
+ }));
1807
+ const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
1808
+ const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1809
+ const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
1810
+ return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
807
1811
  }
808
1812
  async function attachRunOperatorView(context, input) {
809
1813
  let steered = false;
810
1814
  if (input.message?.trim()) {
811
- await steerRunViaServer(context, input.runId, input.message.trim());
1815
+ await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
812
1816
  steered = true;
813
1817
  }
1818
+ if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
1819
+ return attachRunBundledPiFrontend(context, {
1820
+ runId: input.runId,
1821
+ steered
1822
+ });
1823
+ }
1824
+ const surface = createOperatorSurface({ interactive: input.interactive !== false });
814
1825
  let snapshot = await readOperatorSnapshot(context, input.runId);
815
1826
  if (context.outputMode === "text") {
816
- console.log(snapshot.rendered);
1827
+ surface.renderSnapshot(snapshot);
1828
+ surface.renderTimeline(snapshot.timeline);
1829
+ surface.renderLogs(snapshot.logs);
817
1830
  if (steered)
818
- console.log("Steering message queued.");
1831
+ surface.info("Message submitted to worker Pi.");
819
1832
  }
820
1833
  let detached = false;
821
- let rl = null;
1834
+ let commandInput = null;
822
1835
  if (input.follow && !input.once && context.outputMode === "text") {
823
1836
  if (input.interactive !== false && process.stdin.isTTY) {
824
- console.log("Controls: /user <message>, /stop, /detach");
825
- rl = createInterface2({ input: process.stdin, output: process.stdout, terminal: false });
826
- rl.on("line", (line) => {
827
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
828
- if (result.message)
829
- console.log(result.message);
830
- if (result.action === "detach" || result.action === "stopped") {
831
- detached = true;
832
- rl?.close();
833
- }
834
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
1837
+ surface.info("Controls: /user <message>, /stop, /detach");
1838
+ commandInput = surface.attachCommandInput(async (line) => {
1839
+ const result = await applyOperatorCommand(context, { runId: input.runId, line });
1840
+ if (result.message)
1841
+ surface.info(result.message);
1842
+ if (result.action === "detach" || result.action === "stopped") {
1843
+ detached = true;
1844
+ commandInput?.close();
1845
+ }
835
1846
  });
836
1847
  }
837
- let lastRendered = snapshot.rendered;
838
1848
  const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
839
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
1849
+ let timelineCursor = snapshot.timelineCursor;
1850
+ while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
840
1851
  await Bun.sleep(pollMs);
841
- snapshot = await readOperatorSnapshot(context, input.runId);
842
- if (snapshot.rendered !== lastRendered) {
843
- console.log(snapshot.rendered);
844
- lastRendered = snapshot.rendered;
845
- }
1852
+ snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
1853
+ timelineCursor = snapshot.timelineCursor;
1854
+ surface.renderSnapshot(snapshot);
1855
+ surface.renderTimeline(snapshot.timeline);
1856
+ surface.renderLogs(snapshot.logs);
846
1857
  }
847
- rl?.close();
1858
+ commandInput?.close();
848
1859
  }
849
1860
  return { ...snapshot, steered, detached };
850
1861
  }
851
1862
 
1863
+ // packages/cli/src/commands/_cli-format.ts
1864
+ import { log, note } from "@clack/prompts";
1865
+ import pc from "picocolors";
1866
+ function stringField(record, key, fallback = "") {
1867
+ const value = record[key];
1868
+ return typeof value === "string" && value.trim() ? value.trim() : fallback;
1869
+ }
1870
+ function numberField(record, key) {
1871
+ const value = record[key];
1872
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
1873
+ }
1874
+ function arrayField(record, key) {
1875
+ const value = record[key];
1876
+ return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
1877
+ }
1878
+ function rawObject(record) {
1879
+ const raw = record.raw;
1880
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
1881
+ }
1882
+ function truncate(value, width) {
1883
+ if (value.length <= width)
1884
+ return value;
1885
+ if (width <= 1)
1886
+ return "\u2026";
1887
+ return `${value.slice(0, width - 1)}\u2026`;
1888
+ }
1889
+ function pad(value, width) {
1890
+ return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
1891
+ }
1892
+ function statusColor(status) {
1893
+ const normalized = status.toLowerCase();
1894
+ if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved"].includes(normalized))
1895
+ return pc.green;
1896
+ if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
1897
+ return pc.red;
1898
+ if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
1899
+ return pc.cyan;
1900
+ if (["ready", "open", "queued", "created", "preparing", "local", "pending"].includes(normalized))
1901
+ return pc.yellow;
1902
+ return pc.dim;
1903
+ }
1904
+ function compactValue(value) {
1905
+ if (value === null || value === undefined)
1906
+ return "";
1907
+ if (typeof value === "string")
1908
+ return value;
1909
+ if (typeof value === "number" || typeof value === "boolean")
1910
+ return String(value);
1911
+ if (Array.isArray(value))
1912
+ return value.map(compactValue).filter(Boolean).join(", ");
1913
+ return JSON.stringify(value);
1914
+ }
1915
+ function shouldUseClackOutput() {
1916
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
1917
+ }
1918
+ function printFormattedOutput(message2, options = {}) {
1919
+ if (!shouldUseClackOutput()) {
1920
+ console.log(message2);
1921
+ return;
1922
+ }
1923
+ if (options.title)
1924
+ note(message2, options.title);
1925
+ else
1926
+ log.message(message2);
1927
+ }
1928
+ function formatStatusPill(status) {
1929
+ const label = status || "unknown";
1930
+ return statusColor(label)(`\u25CF ${label}`);
1931
+ }
1932
+ function formatSection(title, subtitle) {
1933
+ return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
1934
+ }
1935
+ function formatSuccessCard(title, rows = []) {
1936
+ const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${pc.dim("\u2502")} ${pc.dim(key.padEnd(12))} ${value}`);
1937
+ return [formatSection(title), ...body].join(`
1938
+ `);
1939
+ }
1940
+ function formatNextSteps(steps) {
1941
+ if (steps.length === 0)
1942
+ return [];
1943
+ return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
1944
+ }
1945
+ function formatTaskList(tasks, options = {}) {
1946
+ if (options.raw)
1947
+ return tasks.map((task) => JSON.stringify(task)).join(`
1948
+ `);
1949
+ if (tasks.length === 0)
1950
+ return [formatSection("Tasks", "none found"), ...formatNextSteps(["Try `rig server status` to confirm the selected server.", "Relax filters or run `rig task run --title ... --initial-prompt ...` for ad hoc work."])].join(`
1951
+ `);
1952
+ const rows = tasks.map((task) => {
1953
+ const raw = rawObject(task);
1954
+ const id = stringField(task, "id", "<unknown>");
1955
+ const status = stringField(task, "status", "unknown");
1956
+ const title = stringField(task, "title", "Untitled task");
1957
+ const source = stringField(task, "source", stringField(raw, "source", ""));
1958
+ const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
1959
+ return { id, status, title, source, labels };
1960
+ });
1961
+ const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
1962
+ const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
1963
+ const header = `${pc.bold(pad("TASK", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
1964
+ const body = rows.map((row) => {
1965
+ const labels = row.labels.length > 0 ? pc.dim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
1966
+ const source = row.source ? pc.dim(` ${row.source}`) : "";
1967
+ return [
1968
+ pc.bold(pad(truncate(row.id, idWidth), idWidth)),
1969
+ statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
1970
+ `${row.title}${labels}${source}`
1971
+ ].join(" ");
1972
+ });
1973
+ return [formatSection("Tasks", `${rows.length} shown`), header, ...body, "", ...formatNextSteps(["Run one: `rig task run <id>` or `rig task run --next`", "Attach later: `rig run attach <run-id> --follow`"])].join(`
1974
+ `);
1975
+ }
1976
+ function formatTaskCard(task, options = {}) {
1977
+ const raw = rawObject(task);
1978
+ const id = stringField(task, "id", stringField(raw, "id", "<unknown>"));
1979
+ const status = stringField(task, "status", stringField(raw, "status", "unknown"));
1980
+ const title = stringField(task, "title", stringField(raw, "title", "Untitled task"));
1981
+ const source = stringField(task, "source", stringField(raw, "source", ""));
1982
+ const url = stringField(task, "url", stringField(raw, "url", ""));
1983
+ const number = numberField(task, "number") ?? numberField(raw, "number");
1984
+ const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
1985
+ const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
1986
+ const readiness = compactValue(task.readiness ?? raw.readiness);
1987
+ const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
1988
+ const rows = [
1989
+ ["task", pc.bold(id)],
1990
+ ["status", formatStatusPill(status)],
1991
+ ["title", title],
1992
+ ["source", source],
1993
+ ["number", number],
1994
+ ["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
1995
+ ["assignees", assignees.join(", ")],
1996
+ ["readiness", readiness],
1997
+ ["validators", validators],
1998
+ ["url", url]
1999
+ ];
2000
+ return [
2001
+ formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
2002
+ "",
2003
+ ...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
2004
+ ].join(`
2005
+ `);
2006
+ }
2007
+ function formatTaskDetails(task) {
2008
+ return formatTaskCard(task, { title: "Task details" });
2009
+ }
2010
+ function formatSubmittedRun(input) {
2011
+ const rows = [["run", pc.bold(input.runId)]];
2012
+ if (input.task) {
2013
+ const id = stringField(input.task, "id", "<unknown>");
2014
+ const status = stringField(input.task, "status", "unknown");
2015
+ const title = stringField(input.task, "title", "Untitled task");
2016
+ rows.push(["task", `${pc.bold(id)} ${formatStatusPill(status)} ${title}`]);
2017
+ }
2018
+ const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
2019
+ rows.push(["runtime", runtime]);
2020
+ return [
2021
+ formatSuccessCard("Run submitted", rows),
2022
+ "",
2023
+ ...formatNextSteps([
2024
+ `Attach: \`rig run attach ${input.runId} --follow\``,
2025
+ `Inspect: \`rig run show ${input.runId}\``,
2026
+ input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the enriched bundled Pi (native UI + Rig layers, worker brain)."
2027
+ ])
2028
+ ].join(`
2029
+ `);
2030
+ }
2031
+
2032
+ // packages/cli/src/commands/_help-catalog.ts
2033
+ import { intro, log as log2, note as note2, outro } from "@clack/prompts";
2034
+ import pc2 from "picocolors";
2035
+ var TOP_LEVEL_SECTIONS = [
2036
+ {
2037
+ title: "Start here",
2038
+ subtitle: "one-time setup for a repo",
2039
+ commands: [
2040
+ { command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
2041
+ { command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
2042
+ { command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." }
2043
+ ]
2044
+ },
2045
+ {
2046
+ title: "Work",
2047
+ subtitle: "find a task and put an agent on it",
2048
+ commands: [
2049
+ { command: "rig task list", description: "What's on the board (from the selected source/server)." },
2050
+ { command: "rig task next", description: "The next ready task, as a card." },
2051
+ { command: "rig task run --next", description: "Dispatch an agent; interactive mode opens the native Pi session." },
2052
+ { command: "rig task run <id> --detach", description: "Fire-and-forget a specific task." }
2053
+ ]
2054
+ },
2055
+ {
2056
+ title: "Watch & steer",
2057
+ subtitle: "live runs are observable and steerable, attached or not",
2058
+ commands: [
2059
+ { command: "rig run status", description: "Active and recent runs at a glance." },
2060
+ { command: "rig run attach <id> --follow", description: "Join the live Pi session (worker keeps running if you /detach)." },
2061
+ { command: "rig run steer <id> -m <text>", description: "Drop a message into a live worker without attaching." },
2062
+ { command: "rig run stop <id>", description: "Cancel a running worker." }
2063
+ ]
2064
+ },
2065
+ {
2066
+ title: "Unblock & gate",
2067
+ subtitle: "answer what workers ask; control what merges",
2068
+ commands: [
2069
+ { command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." },
2070
+ { command: "rig inbox inputs", description: "Questions workers asked (then `rig inbox respond \u2026`)." },
2071
+ { command: "rig review show|set", description: "The completion review gate (Greptile is mandatory on merges)." }
2072
+ ]
2073
+ },
2074
+ {
2075
+ title: "Extend",
2076
+ subtitle: "more Pi, more plugins",
2077
+ commands: [
2078
+ { command: "rig pi search <term>", description: "Discover community Pi extensions on npm." },
2079
+ { command: "rig pi add <pkg>", description: "Add a Pi extension to this project (workers pick it up too)." },
2080
+ { command: "rig plugin list", description: "What the rig.config.ts plugins contribute." }
2081
+ ]
2082
+ }
2083
+ ];
2084
+ var PRIMARY_GROUPS = [
2085
+ {
2086
+ name: "server",
2087
+ summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
2088
+ usage: ["rig server <status|list|add|use|start> [options]"],
2089
+ commands: [
2090
+ { command: "status", description: "Show the selected server for this repo.", primary: true },
2091
+ { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
2092
+ { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
2093
+ { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
2094
+ { command: "list", description: "List saved local/remote server aliases.", primary: true },
2095
+ { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
2096
+ ],
2097
+ examples: [
2098
+ "rig server status",
2099
+ "rig server add prod https://where.rig-does.work",
2100
+ "rig server use prod",
2101
+ "rig server use local",
2102
+ "rig server start --port 3773"
2103
+ ],
2104
+ next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."],
2105
+ advanced: ["Compatibility alias: `rig connect ...` remains callable."]
2106
+ },
2107
+ {
2108
+ name: "task",
2109
+ summary: "Find work, start Pi-backed runs, and validate task results.",
2110
+ usage: ["rig task <list|next|show|run> [options]"],
2111
+ commands: [
2112
+ { command: "list [--assignee <login|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
2113
+ { command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
2114
+ { command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
2115
+ { command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
2116
+ { command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
2117
+ { command: "details --task <id>", description: "Show full task info from the configured source." },
2118
+ { command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
2119
+ { command: "reset --task <id>", description: "Compatibility spelling of `reopen --task <id>`." },
2120
+ { command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
2121
+ { command: "report-bug", description: "Create a structured bug report/task." }
2122
+ ],
2123
+ examples: [
2124
+ "rig task list --assignee @me --limit 20",
2125
+ "rig task next",
2126
+ "rig task show 123 --raw",
2127
+ "rig task run --next",
2128
+ "rig task run #123 --runtime-adapter pi",
2129
+ "rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
2130
+ ],
2131
+ next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
2132
+ },
2133
+ {
2134
+ name: "run",
2135
+ summary: "Observe, attach to, and control Rig runs.",
2136
+ usage: ["rig run <list|status|show|attach|stop> [options]"],
2137
+ commands: [
2138
+ { command: "list", description: "List recent runs from the selected server or local state.", primary: true },
2139
+ { command: "status", description: "Render active and recent run groups.", primary: true },
2140
+ { command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
2141
+ { command: "attach <run-id>|--run <id> [--follow]", description: "Attach to the run; --follow opens the enriched bundled Pi (worker brain).", primary: true },
2142
+ { command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
2143
+ { command: "steer <run-id> --message <text>", description: "Queue a steering message into a live worker without attaching." },
2144
+ { command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events." },
2145
+ { command: "resume", description: "Resume the most recent interrupted local run." },
2146
+ { command: "restart", description: "Restart the most recent local run from a clean runtime." },
2147
+ { command: "delete|cleanup", description: "Remove completed run records/artifacts." }
2148
+ ],
2149
+ examples: [
2150
+ "rig run list",
2151
+ "rig run status",
2152
+ "rig run show <run-id>",
2153
+ "rig run attach <run-id> --follow",
2154
+ "rig run stop <run-id>"
2155
+ ],
2156
+ next: ["Use `rig task run --next` to create a new run.", "Use `--json` when scripts need the full structured record."]
2157
+ },
2158
+ {
2159
+ name: "inbox",
2160
+ summary: "Review approval and user-input requests that block worker runs.",
2161
+ usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
2162
+ commands: [
2163
+ { command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
2164
+ { command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
2165
+ { command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
2166
+ { command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
2167
+ ],
2168
+ examples: [
2169
+ "rig inbox approvals",
2170
+ "rig inbox inputs --run <run-id>",
2171
+ "rig inbox approve --run <run-id> --request <request-id> --decision approve"
2172
+ ],
2173
+ next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
2174
+ },
2175
+ {
2176
+ name: "review",
2177
+ summary: "Inspect or change completion review gate policy.",
2178
+ usage: ["rig review <show|set>"],
2179
+ commands: [
2180
+ { command: "show", description: "Show current review gate settings.", primary: true },
2181
+ { command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider.", primary: true }
2182
+ ],
2183
+ examples: ["rig review show", "rig review set required --provider greptile"],
2184
+ next: ["Use `rig inbox approvals` for blocked run handoffs."]
2185
+ },
2186
+ {
2187
+ name: "init",
2188
+ summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
2189
+ usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
2190
+ commands: [
2191
+ { command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
2192
+ { command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
2193
+ { command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
2194
+ { command: "init --repair", description: "Repair missing private state without replacing project config." }
2195
+ ],
2196
+ examples: [
2197
+ "rig init",
2198
+ "rig init --yes --repo humanity-org/humanwork",
2199
+ "rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
2200
+ ],
2201
+ next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
2202
+ },
2203
+ {
2204
+ name: "doctor",
2205
+ summary: "Diagnostics for project/server/GitHub/Pi state.",
2206
+ usage: ["rig doctor"],
2207
+ commands: [
2208
+ { command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
2209
+ { command: "check", description: "Compatibility spelling for diagnostics." }
2210
+ ],
2211
+ examples: ["rig doctor", "rig doctor --json"],
2212
+ next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
2213
+ },
2214
+ {
2215
+ name: "github",
2216
+ summary: "GitHub auth helpers for the selected Rig server.",
2217
+ usage: ["rig github auth <status|import-gh|token>"],
2218
+ commands: [
2219
+ { command: "auth status", description: "Show GitHub auth state.", primary: true },
2220
+ { command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
2221
+ { command: "auth token --token <token>", description: "Store a token on the selected server." }
2222
+ ],
2223
+ examples: ["rig github auth status", "rig github auth import-gh"],
2224
+ next: ["After auth is valid, use `rig task run --next`."]
2225
+ }
2226
+ ];
2227
+ var ADVANCED_GROUPS = [
2228
+ { name: "connect", summary: "Compatibility alias for `rig server` selection commands.", usage: ["rig connect <status|list|add|use>"], commands: [{ command: "status|list|add|use", description: "Use `rig server ...` for the primary UX." }] },
2229
+ { name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
2230
+ {
2231
+ name: "inspect",
2232
+ summary: "Inspect logs, artifacts, graphs, failures for a task.",
2233
+ usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
2234
+ commands: [
2235
+ { command: "logs --task <id>", description: "Latest run log for a task (local or selected server)." },
2236
+ { command: "artifacts --task <id>", description: "List the task's completion artifacts." },
2237
+ { command: "failures --task <id>", description: "Recorded failures for a task." },
2238
+ { command: "graph", description: "Task dependency graph." },
2239
+ { command: "audit", description: "Controlled-command audit trail." },
2240
+ { command: "diff --task <id>", description: "Changed files for a task." }
2241
+ ]
2242
+ },
2243
+ { name: "repo", summary: "Repository sync/baseline helpers.", usage: ["rig repo <sync|reset-baseline>"], commands: [{ command: "sync", description: "Sync project repository state." }] },
2244
+ { name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
2245
+ {
2246
+ name: "browser",
2247
+ summary: "Browser/app diagnostics for browser-required tasks.",
2248
+ usage: ["rig browser <help|explain|demo|app|hp-next> [options]"],
2249
+ commands: [
2250
+ { command: "help", description: "Rich browser command help (canonical: `rig browser help`)." },
2251
+ { command: "explain", description: "Explain the browser-required task contract." },
2252
+ { command: "demo", description: "Run browser demo flows against a local page." },
2253
+ { command: "app", description: "Launch the Rig Browser workstation app." },
2254
+ { command: "hp-next <dev|check|e2e|reset>", description: "Drive the hp-next browser test harness." }
2255
+ ]
2256
+ },
2257
+ {
2258
+ name: "pi",
2259
+ summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
2260
+ usage: ["rig pi <list|add|remove|search> [args]"],
2261
+ commands: [
2262
+ { command: "list", description: "Show project and user Pi extension packages." },
2263
+ { command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
2264
+ { command: "remove <source>", description: "Remove an operator-added Pi extension." },
2265
+ { command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
2266
+ ],
2267
+ examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
2268
+ next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
2269
+ },
2270
+ {
2271
+ name: "plugin",
2272
+ summary: "Plugin listing, validation, and plugin-contributed commands.",
2273
+ usage: ["rig plugin <list|validate|run> [options]"],
2274
+ commands: [
2275
+ { command: "list", description: "List plugins declared in rig.config.ts and their contributions." },
2276
+ { command: "validate --task <id>", description: "Run plugin-contributed validators for a task." },
2277
+ { command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
2278
+ ]
2279
+ },
2280
+ { name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
2281
+ { name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
2282
+ { name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
2283
+ { name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
2284
+ { name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
2285
+ { name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
2286
+ { name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
2287
+ { name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
2288
+ { name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
2289
+ ];
2290
+ var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
2291
+ function heading(title) {
2292
+ return pc2.bold(pc2.cyan(title));
2293
+ }
2294
+ function renderRigBanner(version) {
2295
+ const m = (s) => pc2.bold(pc2.magenta(s));
2296
+ const c = (s) => pc2.bold(pc2.cyan(s));
2297
+ const y = (s) => pc2.yellow(s);
2298
+ const d = (s) => pc2.dim(s);
2299
+ const lines = [
2300
+ m(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ") + d(" \u2591\u2592\u2593\u2588 "),
2301
+ m(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D ") + d("\u2593\u2592\u2591"),
2302
+ c(" \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557") + d(" \u2591\u2592"),
2303
+ c(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551") + d(" \u2588\u2593\u2591"),
2304
+ y(" \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D") + d(" \u2592\u2591"),
2305
+ y(" \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D "),
2306
+ "",
2307
+ ` ${c("\u25E2\u25E4")} ${pc2.bold("the control rig for autonomous coding agents")} ${m("//")} ${d("you are the operator")}`,
2308
+ version ? ` ${d(`v${version} \xB7 jack in: rig task run --next`)}` : ` ${d("jack in: rig task run --next")}`
2309
+ ];
2310
+ return lines.join(`
2311
+ `);
2312
+ }
2313
+ function commandLine(command, description) {
2314
+ const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
2315
+ return `${pc2.dim("\u2502")} ${pc2.bold(commandColumn)} ${description}`;
2316
+ }
2317
+ function renderCommandBlock(commands) {
2318
+ return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
2319
+ `);
2320
+ }
2321
+ function renderGroup(group) {
2322
+ const lines = [
2323
+ `${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
2324
+ "",
2325
+ pc2.bold("Usage"),
2326
+ ...group.usage.map((line) => ` ${line}`),
2327
+ "",
2328
+ pc2.bold("Commands"),
2329
+ ...group.commands.map((entry) => commandLine(entry.command, entry.description))
2330
+ ];
2331
+ if (group.examples?.length) {
2332
+ lines.push("", pc2.bold("Examples"), ...group.examples.map((line) => ` ${pc2.dim("$")} ${line}`));
2333
+ }
2334
+ if (group.next?.length) {
2335
+ lines.push("", pc2.bold("Next steps"), ...group.next.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
2336
+ }
2337
+ if (group.advanced?.length) {
2338
+ lines.push("", pc2.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
2339
+ }
2340
+ return lines.join(`
2341
+ `);
2342
+ }
2343
+ function renderTopLevelHelp() {
2344
+ return [
2345
+ `${heading("rig")} ${pc2.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
2346
+ pc2.dim("Current path: select a server, choose a task, submit a run, attach with native Pi, clear inbox/review gates."),
2347
+ "",
2348
+ ...TOP_LEVEL_SECTIONS.flatMap((section) => [
2349
+ `${pc2.bold(pc2.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc2.dim(section.subtitle)}`,
2350
+ renderCommandBlock(section.commands),
2351
+ ""
2352
+ ]),
2353
+ pc2.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
2354
+ "",
2355
+ pc2.bold("Global options"),
2356
+ commandLine("--project <path>", "Use a project root instead of auto-discovery."),
2357
+ commandLine("--json", "Emit structured output for scripts/agents."),
2358
+ commandLine("--dry-run", "Print the command plan without mutating state.")
2359
+ ].join(`
2360
+ `).trimEnd();
2361
+ }
2362
+ function renderGroupHelp(groupName) {
2363
+ const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
2364
+ return group ? renderGroup(group) : null;
2365
+ }
2366
+ function shouldUseClackOutput2() {
2367
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
2368
+ }
2369
+ function printTopLevelHelp(state = {}) {
2370
+ if (!shouldUseClackOutput2()) {
2371
+ console.log(renderTopLevelHelp());
2372
+ return;
2373
+ }
2374
+ console.log(renderRigBanner(state.version));
2375
+ console.log("");
2376
+ if (state.projectInitialized === false) {
2377
+ intro("no rig project in this directory");
2378
+ note2([
2379
+ commandLine("rig init", "Set this repo up: config, GitHub auth, task source, server, Pi."),
2380
+ commandLine("rig init --yes", "Same, non-interactive, sensible defaults."),
2381
+ commandLine("rig doctor", "Already initialized somewhere else? Check the wiring.")
2382
+ ].join(`
2383
+ `), "Get started");
2384
+ outro("After init: rig task run --next puts an agent on your next task.");
2385
+ return;
2386
+ }
2387
+ intro(state.selectedServer ? `server: ${state.selectedServer}` : "rig");
2388
+ for (const section of TOP_LEVEL_SECTIONS) {
2389
+ note2(renderCommandBlock(section.commands), `${section.title} \u2014 ${section.subtitle}`);
2390
+ }
2391
+ log2.info("More: rig help --advanced \xB7 rig <group> --help \xB7 rig --version");
2392
+ note2([
2393
+ commandLine("--project <path>", "Use a project root instead of auto-discovery."),
2394
+ commandLine("--json", "Emit structured output for scripts/agents."),
2395
+ commandLine("--dry-run", "Print the command plan without mutating state.")
2396
+ ].join(`
2397
+ `), "Global options");
2398
+ outro("init \u2192 task run \u2192 watch/steer \u2192 inbox/review \u2192 merged.");
2399
+ }
2400
+ function printGroupHelpDocument(groupName) {
2401
+ const rendered = renderGroupHelp(groupName) ?? renderTopLevelHelp();
2402
+ if (!shouldUseClackOutput2()) {
2403
+ console.log(rendered);
2404
+ return;
2405
+ }
2406
+ const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
2407
+ if (!group) {
2408
+ printTopLevelHelp();
2409
+ return;
2410
+ }
2411
+ intro(`rig ${group.name}`);
2412
+ note2(group.summary, "Purpose");
2413
+ note2(group.usage.join(`
2414
+ `), "Usage");
2415
+ note2(group.commands.map((entry) => commandLine(entry.command, entry.description)).join(`
2416
+ `), "Commands");
2417
+ if (group.examples?.length)
2418
+ note2(group.examples.map((line) => `$ ${line}`).join(`
2419
+ `), "Examples");
2420
+ if (group.next?.length)
2421
+ note2(group.next.map((line) => `\u203A ${line}`).join(`
2422
+ `), "Next steps");
2423
+ if (group.advanced?.length)
2424
+ log2.info(group.advanced.join(`
2425
+ `));
2426
+ outro("Run with --json when scripts need structured output.");
2427
+ }
2428
+
852
2429
  // packages/cli/src/commands/task.ts
853
2430
  import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
854
2431
  import { loadConfig } from "@rig/core/load-config";
@@ -924,7 +2501,7 @@ function normalizePrMode(value) {
924
2501
  throw new CliError2("--pr must be auto, ask, or off.", 2);
925
2502
  }
926
2503
  function detectLocalDirtyState(projectRoot) {
927
- const result = spawnSync2("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
2504
+ const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
928
2505
  if (result.status !== 0)
929
2506
  return { dirty: false, modified: 0, untracked: 0, lines: [] };
930
2507
  const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
@@ -958,13 +2535,15 @@ async function resolveDirtyBaselineForTaskRun(context, explicit) {
958
2535
  if (explicit)
959
2536
  return { mode: explicit, state };
960
2537
  if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
961
- const rl = createInterface3({ input: process.stdin, output: process.stdout });
962
- try {
963
- const answer = (await rl.question("Include current uncommitted changes in run baseline? [y/N] ")).trim().toLowerCase();
964
- return { mode: answer === "y" || answer === "yes" ? "dirty-snapshot" : "head", state };
965
- } finally {
966
- rl.close();
2538
+ const answer = await confirm({
2539
+ message: "Include current uncommitted changes in run baseline?",
2540
+ initialValue: false
2541
+ });
2542
+ if (isCancel2(answer)) {
2543
+ cancel2("Run cancelled.");
2544
+ throw new CliError2("Run cancelled by user.", 1);
967
2545
  }
2546
+ return { mode: answer ? "dirty-snapshot" : "head", state };
968
2547
  }
969
2548
  return { mode: "head", state };
970
2549
  }
@@ -998,38 +2577,30 @@ function summarizeTask(task, options = {}) {
998
2577
  ...options.raw ? { raw: raw ?? task } : {}
999
2578
  };
1000
2579
  }
1001
- function printTaskSummary(task) {
1002
- const id = readTaskId(task) ?? "<unknown>";
1003
- const title = readTaskString(task, "title") ?? "Untitled task";
1004
- const status = readTaskString(task, "status") ?? "unknown";
1005
- console.log(`- ${id} \xB7 ${status} \xB7 ${title}`);
1006
- }
1007
2580
  async function validatorRegistryForTaskCommands(projectRoot) {
1008
2581
  return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
1009
2582
  return;
1010
2583
  });
1011
2584
  }
1012
2585
  async function executeTask(context, args, options) {
1013
- const [command = "info", ...rest] = args;
2586
+ if (args.length === 0) {
2587
+ if (context.outputMode === "text") {
2588
+ printGroupHelpDocument("task");
2589
+ }
2590
+ return { ok: true, group: "task", command: "help" };
2591
+ }
2592
+ const [command = "help", ...rest] = args;
1014
2593
  switch (command) {
1015
2594
  case "list": {
1016
2595
  let pending = rest;
1017
2596
  const rawResult = takeFlag(pending, "--raw");
1018
2597
  pending = rawResult.rest;
1019
2598
  const { filters, rest: remaining } = parseTaskFilters(pending);
1020
- requireNoExtraArgs(remaining, "bun run rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
2599
+ requireNoExtraArgs(remaining, "rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1021
2600
  const tasks = await listWorkspaceTasksViaServer(context, filters);
1022
2601
  if (context.outputMode === "text") {
1023
- if (tasks.length === 0) {
1024
- console.log("No matching tasks.");
1025
- } else {
1026
- for (const task of tasks) {
1027
- if (rawResult.value)
1028
- console.log(JSON.stringify(summarizeTask(task, { raw: true })));
1029
- else
1030
- printTaskSummary(task);
1031
- }
1032
- }
2602
+ const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
2603
+ printFormattedOutput(formatTaskList(renderedTasks, { raw: rawResult.value }));
1033
2604
  }
1034
2605
  return {
1035
2606
  ok: true,
@@ -1039,30 +2610,34 @@ async function executeTask(context, args, options) {
1039
2610
  };
1040
2611
  }
1041
2612
  case "show": {
1042
- const taskOption = takeOption(rest, "--task");
2613
+ let pending = rest;
2614
+ const rawResult = takeFlag(pending, "--raw");
2615
+ pending = rawResult.rest;
2616
+ const taskOption = takeOption(pending, "--task");
1043
2617
  const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
1044
2618
  const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
1045
- requireNoExtraArgs(remaining, "bun run rig task show <id>|--task <id>");
1046
- const taskId2 = normalizeTaskRunTaskId(taskOption.value ?? positional);
1047
- if (!taskId2)
2619
+ requireNoExtraArgs(remaining, "rig task show <id>|--task <id> [--raw]");
2620
+ const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
2621
+ if (!taskId3)
1048
2622
  throw new CliError2("task show requires a task id.", 2);
1049
- const task = await getWorkspaceTaskViaServer(context, taskId2);
2623
+ const task = await getWorkspaceTaskViaServer(context, taskId3);
1050
2624
  if (!task)
1051
- throw new CliError2(`Task not found: ${taskId2}`, 3);
2625
+ throw new CliError2(`Task not found: ${taskId3}`, 3);
1052
2626
  const summary = summarizeTask(task, { raw: true });
1053
- if (context.outputMode === "text")
1054
- console.log(JSON.stringify(summary, null, 2));
1055
- return { ok: true, group: "task", command, details: { task: summary } };
2627
+ if (context.outputMode === "text") {
2628
+ printFormattedOutput(rawResult.value ? JSON.stringify(summary, null, 2) : formatTaskDetails(summary));
2629
+ }
2630
+ return { ok: true, group: "task", command, details: { task: summary, raw: rawResult.value } };
1056
2631
  }
1057
2632
  case "next": {
1058
2633
  const { filters, rest: remaining } = parseTaskFilters(rest);
1059
- requireNoExtraArgs(remaining, "bun run rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
2634
+ requireNoExtraArgs(remaining, "rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1060
2635
  const selected = await selectNextWorkspaceTaskViaServer(context, filters);
1061
2636
  if (context.outputMode === "text") {
1062
2637
  if (selected.task) {
1063
- printTaskSummary(selected.task);
2638
+ printFormattedOutput(formatTaskCard(summarizeTask(selected.task, { raw: true }), { title: "Selected task", selected: true }));
1064
2639
  } else {
1065
- console.log("No matching tasks.");
2640
+ printFormattedOutput("No matching tasks.\n\nNext\n\u203A Try `rig task list` to inspect available work.\n\u203A Check server: `rig server status`");
1066
2641
  }
1067
2642
  }
1068
2643
  return {
@@ -1078,31 +2653,31 @@ async function executeTask(context, args, options) {
1078
2653
  }
1079
2654
  case "info": {
1080
2655
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1081
- requireNoExtraArgs(remaining, "bun run rig task info [--task <beads-id>]");
2656
+ requireNoExtraArgs(remaining, "rig task info [--task <task-id>]");
1082
2657
  await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
1083
2658
  return { ok: true, group: "task", command, details: { task: task || null } };
1084
2659
  }
1085
2660
  case "scope": {
1086
2661
  const filesFlag = takeFlag(rest, "--files");
1087
2662
  const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
1088
- requireNoExtraArgs(remaining, "bun run rig task scope [--task <id>] [--files]");
2663
+ requireNoExtraArgs(remaining, "rig task scope [--task <id>] [--files]");
1089
2664
  await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
1090
2665
  return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
1091
2666
  }
1092
2667
  case "deps":
1093
- requireNoExtraArgs(rest, "bun run rig task deps");
2668
+ requireNoExtraArgs(rest, "rig task deps");
1094
2669
  await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
1095
2670
  return { ok: true, group: "task", command };
1096
2671
  case "status":
1097
- requireNoExtraArgs(rest, "bun run rig task status");
2672
+ requireNoExtraArgs(rest, "rig task status");
1098
2673
  withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
1099
2674
  return { ok: true, group: "task", command };
1100
2675
  case "artifacts":
1101
- requireNoExtraArgs(rest, "bun run rig task artifacts");
2676
+ requireNoExtraArgs(rest, "rig task artifacts");
1102
2677
  withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
1103
2678
  return { ok: true, group: "task", command };
1104
2679
  case "artifact-dir": {
1105
- requireNoExtraArgs(rest, "bun run rig task artifact-dir");
2680
+ requireNoExtraArgs(rest, "rig task artifact-dir");
1106
2681
  const path = taskArtifactDir(context.projectRoot);
1107
2682
  if (context.outputMode === "text") {
1108
2683
  console.log(path);
@@ -1111,7 +2686,7 @@ async function executeTask(context, args, options) {
1111
2686
  }
1112
2687
  case "artifact-write": {
1113
2688
  if (rest.length < 1) {
1114
- throw new CliError2(`Usage: bun run rig task artifact-write <filename> [--file <path>]
2689
+ throw new CliError2(`Usage: rig task artifact-write <filename> [--file <path>]
1115
2690
  ` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
1116
2691
  ` + " Example: echo '...' | rig task artifact-write collection-audit.md");
1117
2692
  }
@@ -1119,12 +2694,12 @@ async function executeTask(context, args, options) {
1119
2694
  const fileFlag = takeOption(rest.slice(1), "--file");
1120
2695
  let content;
1121
2696
  if (fileFlag.value) {
1122
- content = readFileSync4(resolve4(context.projectRoot, fileFlag.value), "utf-8");
2697
+ content = readFileSync3(resolve3(context.projectRoot, fileFlag.value), "utf-8");
1123
2698
  } else {
1124
2699
  content = await readStdin();
1125
2700
  }
1126
2701
  if (!artifactFilename) {
1127
- throw new CliError2("Usage: bun run rig task artifact-write <filename> [--file path]");
2702
+ throw new CliError2("Usage: rig task artifact-write <filename> [--file path]");
1128
2703
  }
1129
2704
  withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
1130
2705
  return { ok: true, group: "task", command, details: { filename: artifactFilename } };
@@ -1133,11 +2708,11 @@ async function executeTask(context, args, options) {
1133
2708
  return options.executeTaskReportBug(context, rest);
1134
2709
  case "lookup": {
1135
2710
  if (rest.length !== 1) {
1136
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
2711
+ throw new CliError2("Usage: rig task lookup <task-id>");
1137
2712
  }
1138
2713
  const lookupId = rest[0];
1139
2714
  if (!lookupId) {
1140
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
2715
+ throw new CliError2("Usage: rig task lookup <task-id>");
1141
2716
  }
1142
2717
  const result = taskLookup(context.projectRoot, lookupId);
1143
2718
  if (context.outputMode === "text") {
@@ -1147,17 +2722,17 @@ async function executeTask(context, args, options) {
1147
2722
  }
1148
2723
  case "record": {
1149
2724
  if (rest.length < 2) {
1150
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
2725
+ throw new CliError2("Usage: rig task record <decision|failure> <text>");
1151
2726
  }
1152
2727
  const type = rest[0];
1153
2728
  if (type !== "decision" && type !== "failure") {
1154
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
2729
+ throw new CliError2("Usage: rig task record <decision|failure> <text>");
1155
2730
  }
1156
2731
  withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
1157
2732
  return { ok: true, group: "task", command, details: { type: rest[0] } };
1158
2733
  }
1159
2734
  case "ready":
1160
- requireNoExtraArgs(rest, "bun run rig task ready");
2735
+ requireNoExtraArgs(rest, "rig task ready");
1161
2736
  await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
1162
2737
  return { ok: true, group: "task", command };
1163
2738
  case "run": {
@@ -1194,7 +2769,7 @@ async function executeTask(context, args, options) {
1194
2769
  if (positionalTaskId) {
1195
2770
  pending = pending.slice(1);
1196
2771
  }
1197
- 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]");
2772
+ requireNoExtraArgs(pending, "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]");
1198
2773
  if (nextResult.value && (taskResult.value || positionalTaskId)) {
1199
2774
  throw new CliError2("task run cannot combine --next with an explicit task id.", 2);
1200
2775
  }
@@ -1248,16 +2823,24 @@ async function executeTask(context, args, options) {
1248
2823
  });
1249
2824
  let attachDetails = null;
1250
2825
  if (!detachResult.value && context.outputMode === "text") {
1251
- console.log(`Run submitted: ${submitted.runId}`);
1252
- if (selectedTask) {
1253
- printTaskSummary(selectedTask);
1254
- }
2826
+ printFormattedOutput(formatSubmittedRun({
2827
+ runId: submitted.runId,
2828
+ task: selectedTask ? summarizeTask(selectedTask) : null,
2829
+ runtimeAdapter,
2830
+ runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2831
+ interactionMode: interactionModeResult.value || "default",
2832
+ detached: false
2833
+ }));
1255
2834
  attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
1256
2835
  } else if (context.outputMode === "text") {
1257
- console.log(`Run submitted: ${submitted.runId}`);
1258
- if (selectedTask) {
1259
- printTaskSummary(selectedTask);
1260
- }
2836
+ printFormattedOutput(formatSubmittedRun({
2837
+ runId: submitted.runId,
2838
+ task: selectedTask ? summarizeTask(selectedTask) : null,
2839
+ runtimeAdapter,
2840
+ runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2841
+ interactionMode: interactionModeResult.value || "default",
2842
+ detached: true
2843
+ }));
1261
2844
  }
1262
2845
  return {
1263
2846
  ok: true,
@@ -1281,7 +2864,7 @@ async function executeTask(context, args, options) {
1281
2864
  }
1282
2865
  case "validate": {
1283
2866
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1284
- requireNoExtraArgs(remaining, "bun run rig task validate [--task <beads-id>]");
2867
+ requireNoExtraArgs(remaining, "rig task validate [--task <task-id>]");
1285
2868
  if (context.dryRun) {
1286
2869
  await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
1287
2870
  return { ok: true, group: "task", command, details: { task: task || "active" } };
@@ -1294,12 +2877,12 @@ async function executeTask(context, args, options) {
1294
2877
  }
1295
2878
  case "verify": {
1296
2879
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1297
- requireNoExtraArgs(remaining, "bun run rig task verify [--task <beads-id>]");
2880
+ requireNoExtraArgs(remaining, "rig task verify [--task <task-id>]");
1298
2881
  if (context.dryRun) {
1299
2882
  await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
1300
2883
  return { ok: true, group: "task", command, details: { task: task || "active" } };
1301
2884
  }
1302
- const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, context.plugins, task || undefined));
2885
+ const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, task || undefined));
1303
2886
  if (!ok) {
1304
2887
  throw new CliError2(`Verification rejected for ${task || "active task"}.`, 2);
1305
2888
  }
@@ -1307,15 +2890,19 @@ async function executeTask(context, args, options) {
1307
2890
  }
1308
2891
  case "reset": {
1309
2892
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1310
- requireNoExtraArgs(remaining, "bun run rig task reset --task <beads-id>");
1311
- const requiredTask = requireTask(task, "bun run rig task reset --task <beads-id>");
1312
- await context.runCommand(["br", "--no-db", "update", requiredTask, "--status", "open"]);
1313
- return { ok: true, group: "task", command, details: { task: requiredTask } };
2893
+ requireNoExtraArgs(remaining, "rig task reset --task <task-id>");
2894
+ const requiredTask = requireTask(task, "rig task reset --task <task-id>");
2895
+ const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
2896
+ all: false,
2897
+ taskId: requiredTask,
2898
+ dryRun: false
2899
+ }));
2900
+ return { ok: true, group: "task", command, details: summary };
1314
2901
  }
1315
2902
  case "details": {
1316
2903
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1317
- requireNoExtraArgs(remaining, "bun run rig task details --task <beads-id>");
1318
- const requiredTask = requireTask(task, "bun run rig task details --task <beads-id>");
2904
+ requireNoExtraArgs(remaining, "rig task details --task <task-id>");
2905
+ const requiredTask = requireTask(task, "rig task details --task <task-id>");
1319
2906
  await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
1320
2907
  return { ok: true, group: "task", command, details: { task: requiredTask } };
1321
2908
  }
@@ -1323,9 +2910,9 @@ async function executeTask(context, args, options) {
1323
2910
  const { value: task, rest: rest1 } = takeOption(rest, "--task");
1324
2911
  const allFlag = takeFlag(rest1, "--all");
1325
2912
  const { rest: remaining } = takeOption(allFlag.rest, "--reason");
1326
- requireNoExtraArgs(remaining, "bun run rig task reopen [--task <id> | --all] [--reason <text>]");
2913
+ requireNoExtraArgs(remaining, "rig task reopen [--task <id> | --all] [--reason <text>]");
1327
2914
  if (!allFlag.value && !task) {
1328
- throw new CliError2("Usage: bun run rig task reopen [--task <id> | --all] [--reason <text>]");
2915
+ throw new CliError2("Usage: rig task reopen [--task <id> | --all] [--reason <text>]");
1329
2916
  }
1330
2917
  const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
1331
2918
  all: allFlag.value,