@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,15 +1,11 @@
1
1
  // @bun
2
2
  // packages/cli/src/commands/run.ts
3
- import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
4
- import { resolve as resolve3 } from "path";
5
3
  import { createInterface as createInterface2 } from "readline/promises";
6
4
 
7
5
  // packages/cli/src/runner.ts
8
6
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
9
7
  import { CliError } from "@rig/runtime/control-plane/errors";
10
8
  import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
11
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
12
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
13
9
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
14
10
  import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
15
11
  function takeFlag(args, flag) {
@@ -54,9 +50,7 @@ Usage: ${usage}`);
54
50
  // packages/cli/src/commands/run.ts
55
51
  import {
56
52
  listAuthorityRuns,
57
- readAuthorityRun,
58
- readJsonlFile,
59
- resolveAuthorityRunDir
53
+ readAuthorityRun
60
54
  } from "@rig/runtime/control-plane/authority-files";
61
55
  import {
62
56
  cleanupRunState,
@@ -70,7 +64,7 @@ import {
70
64
  startRun,
71
65
  defaultStartRunOptions
72
66
  } from "@rig/runtime/control-plane/native/run-ops";
73
- import { loadRuntimeContextFromEnv as loadRuntimeContextFromEnv2 } from "@rig/runtime/control-plane/runtime/context";
67
+ import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
74
68
 
75
69
  // packages/cli/src/commands/_parsers.ts
76
70
  function parsePositiveInt(value, option, fallback) {
@@ -85,7 +79,6 @@ function parsePositiveInt(value, option, fallback) {
85
79
  }
86
80
 
87
81
  // packages/cli/src/commands/_server-client.ts
88
- import { spawnSync } from "child_process";
89
82
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
90
83
  import { resolve as resolve2 } from "path";
91
84
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
@@ -115,6 +108,11 @@ function readJsonFile(path) {
115
108
  throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
116
109
  }
117
110
  }
111
+ function writeJsonFile(path, value) {
112
+ mkdirSync(dirname(path), { recursive: true });
113
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
114
+ `, "utf8");
115
+ }
118
116
  function normalizeConnection(value) {
119
117
  if (!value || typeof value !== "object" || Array.isArray(value))
120
118
  return null;
@@ -155,25 +153,35 @@ function readRepoConnection(projectRoot) {
155
153
  return {
156
154
  selected,
157
155
  project: typeof record.project === "string" ? record.project : undefined,
158
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
156
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
157
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
159
158
  };
160
159
  }
160
+ function writeRepoConnection(projectRoot, state) {
161
+ writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
162
+ }
161
163
  function resolveSelectedConnection(projectRoot, options = {}) {
162
164
  const repo = readRepoConnection(projectRoot);
163
165
  if (!repo)
164
166
  return null;
165
167
  if (repo.selected === "local")
166
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
168
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
167
169
  const global = readGlobalConnections(options);
168
170
  const connection = global.connections[repo.selected];
169
171
  if (!connection) {
170
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
172
+ throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
171
173
  }
172
- return { alias: repo.selected, connection };
174
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
175
+ }
176
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
177
+ const repo = readRepoConnection(projectRoot);
178
+ if (!repo)
179
+ return;
180
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
173
181
  }
174
182
 
175
183
  // packages/cli/src/commands/_server-client.ts
176
- var cachedGitHubBearerToken;
184
+ var scopedGitHubBearerTokens = new Map;
177
185
  function cleanToken(value) {
178
186
  const trimmed = value?.trim();
179
187
  return trimmed ? trimmed : null;
@@ -190,41 +198,33 @@ function readPrivateRemoteSessionToken(projectRoot) {
190
198
  }
191
199
  }
192
200
  function readGitHubBearerTokenForRemote(projectRoot) {
193
- if (cachedGitHubBearerToken !== undefined)
194
- return cachedGitHubBearerToken;
201
+ const scopedKey = resolve2(projectRoot);
202
+ if (scopedGitHubBearerTokens.has(scopedKey))
203
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
195
204
  const privateSession = readPrivateRemoteSessionToken(projectRoot);
196
- if (privateSession) {
197
- cachedGitHubBearerToken = privateSession;
198
- return cachedGitHubBearerToken;
199
- }
200
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
201
- if (envToken) {
202
- cachedGitHubBearerToken = envToken;
203
- return cachedGitHubBearerToken;
204
- }
205
- const result = spawnSync("gh", ["auth", "token"], {
206
- encoding: "utf8",
207
- timeout: 5000,
208
- stdio: ["ignore", "pipe", "ignore"]
209
- });
210
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
211
- return cachedGitHubBearerToken;
205
+ if (privateSession)
206
+ return privateSession;
207
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
212
208
  }
213
209
  async function ensureServerForCli(projectRoot) {
214
210
  try {
215
211
  const selected = resolveSelectedConnection(projectRoot);
216
212
  if (selected?.connection.kind === "remote") {
213
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
214
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
217
215
  return {
218
216
  baseUrl: selected.connection.baseUrl,
219
- authToken: readGitHubBearerTokenForRemote(projectRoot),
220
- connectionKind: "remote"
217
+ authToken,
218
+ connectionKind: "remote",
219
+ serverProjectRoot
221
220
  };
222
221
  }
223
222
  const connection = await ensureLocalRigServerConnection(projectRoot);
224
223
  return {
225
224
  baseUrl: connection.baseUrl,
226
225
  authToken: connection.authToken,
227
- connectionKind: "local"
226
+ connectionKind: "local",
227
+ serverProjectRoot: resolve2(projectRoot)
228
228
  };
229
229
  } catch (error) {
230
230
  if (error instanceof Error) {
@@ -233,6 +233,29 @@ async function ensureServerForCli(projectRoot) {
233
233
  throw error;
234
234
  }
235
235
  }
236
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
237
+ const repo = readRepoConnection(projectRoot);
238
+ const slug = repo?.project?.trim();
239
+ if (!slug)
240
+ return null;
241
+ try {
242
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
243
+ headers: mergeHeaders(undefined, authToken)
244
+ });
245
+ if (!response.ok)
246
+ return null;
247
+ const payload = await response.json();
248
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
249
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
250
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
251
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
252
+ if (path)
253
+ writeRepoServerProjectRoot(projectRoot, path);
254
+ return path;
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
236
259
  function mergeHeaders(headers, authToken) {
237
260
  const merged = new Headers(headers);
238
261
  if (authToken) {
@@ -257,9 +280,12 @@ function diagnosticMessage(payload) {
257
280
  }
258
281
  async function requestServerJson(context, pathname, init = {}) {
259
282
  const server = await ensureServerForCli(context.projectRoot);
283
+ const headers = mergeHeaders(init.headers, server.authToken);
284
+ if (server.serverProjectRoot)
285
+ headers.set("x-rig-project-root", server.serverProjectRoot);
260
286
  const response = await fetch(`${server.baseUrl}${pathname}`, {
261
287
  ...init,
262
- headers: mergeHeaders(init.headers, server.authToken)
288
+ headers
263
289
  });
264
290
  const text = await response.text();
265
291
  const payload = text.trim().length > 0 ? (() => {
@@ -276,6 +302,14 @@ async function requestServerJson(context, pathname, init = {}) {
276
302
  }
277
303
  return payload;
278
304
  }
305
+ async function listRunsViaServer(context, options = {}) {
306
+ const url = new URL("http://rig.local/api/runs");
307
+ if (options.limit !== undefined)
308
+ url.searchParams.set("limit", String(options.limit));
309
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
310
+ const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
311
+ return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
312
+ }
279
313
  async function getRunDetailsViaServer(context, runId) {
280
314
  const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
281
315
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
@@ -289,6 +323,15 @@ async function getRunLogsViaServer(context, runId, options = {}) {
289
323
  const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
290
324
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
291
325
  }
326
+ async function getRunTimelineViaServer(context, runId, options = {}) {
327
+ const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
328
+ if (options.limit !== undefined)
329
+ url.searchParams.set("limit", String(options.limit));
330
+ if (options.cursor)
331
+ url.searchParams.set("cursor", options.cursor);
332
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
333
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
334
+ }
292
335
  async function stopRunViaServer(context, runId) {
293
336
  const payload = await requestServerJson(context, "/api/runs/stop", {
294
337
  method: "POST",
@@ -305,10 +348,75 @@ async function steerRunViaServer(context, runId, message) {
305
348
  });
306
349
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
307
350
  }
351
+ async function getRunPiSessionViaServer(context, runId) {
352
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
353
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
354
+ }
355
+ async function getRunPiMessagesViaServer(context, runId) {
356
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
357
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
358
+ }
359
+ async function getRunPiStatusViaServer(context, runId) {
360
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
361
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
362
+ }
363
+ async function getRunPiCommandsViaServer(context, runId) {
364
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
365
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
366
+ }
367
+ async function getRunPiCapabilitiesViaServer(context, runId) {
368
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
369
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
370
+ }
371
+ async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
372
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
373
+ method: "POST",
374
+ headers: { "content-type": "application/json" },
375
+ body: JSON.stringify({ text, streamingBehavior })
376
+ });
377
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
378
+ }
379
+ async function sendRunPiShellViaServer(context, runId, text) {
380
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
381
+ method: "POST",
382
+ headers: { "content-type": "application/json" },
383
+ body: JSON.stringify({ text })
384
+ });
385
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
386
+ }
387
+ async function runRunPiCommandViaServer(context, runId, text) {
388
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
389
+ method: "POST",
390
+ headers: { "content-type": "application/json" },
391
+ body: JSON.stringify({ text })
392
+ });
393
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
394
+ }
395
+ async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
396
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
397
+ method: "POST",
398
+ headers: { "content-type": "application/json" },
399
+ body: JSON.stringify({ requestId, ...valueOrCancel })
400
+ });
401
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
402
+ }
403
+ async function abortRunPiViaServer(context, runId) {
404
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
405
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
406
+ }
407
+ async function buildRunPiEventsWebSocketUrl(context, runId) {
408
+ const server = await ensureServerForCli(context.projectRoot);
409
+ const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
410
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
411
+ if (server.authToken)
412
+ url.searchParams.set("token", server.authToken);
413
+ if (server.serverProjectRoot)
414
+ url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
415
+ return url.toString();
416
+ }
308
417
 
309
- // packages/cli/src/commands/_operator-view.ts
418
+ // packages/cli/src/commands/_operator-surface.ts
310
419
  import { createInterface } from "readline";
311
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
312
420
  var CANONICAL_STAGES = [
313
421
  "Connect",
314
422
  "GitHub/task sync",
@@ -323,18 +431,943 @@ var CANONICAL_STAGES = [
323
431
  "Merge",
324
432
  "Complete"
325
433
  ];
434
+ function logDetail(log) {
435
+ return typeof log.detail === "string" ? log.detail.trim() : "";
436
+ }
437
+ function parseProviderProtocolLog(title, detail) {
438
+ if (title.trim().toLowerCase() !== "agent output")
439
+ return null;
440
+ if (!detail.startsWith("{") || !detail.endsWith("}"))
441
+ return null;
442
+ try {
443
+ const record = JSON.parse(detail);
444
+ if (!record || typeof record !== "object" || Array.isArray(record))
445
+ return null;
446
+ const type = record.type;
447
+ return typeof type === "string" && [
448
+ "assistant",
449
+ "message_start",
450
+ "message_update",
451
+ "message_end",
452
+ "stream_event",
453
+ "tool_result",
454
+ "tool_execution_start",
455
+ "tool_execution_update",
456
+ "tool_execution_end",
457
+ "turn_start",
458
+ "turn_end"
459
+ ].includes(type) ? record : null;
460
+ } catch {
461
+ return null;
462
+ }
463
+ }
464
+ function renderProviderProtocolLog(record) {
465
+ const type = typeof record.type === "string" ? record.type : "";
466
+ if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
467
+ const toolName = String(record.toolName ?? record.name ?? "tool");
468
+ 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";
469
+ return `[Pi tool] ${toolName} ${status}`;
470
+ }
471
+ return null;
472
+ }
473
+ function entryId(entry, fallback) {
474
+ return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
475
+ }
326
476
  function renderOperatorSnapshot(snapshot) {
327
477
  const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
328
478
  const runId = String(run.runId ?? run.id ?? "run");
329
479
  const status = String(run.status ?? "unknown");
330
480
  const logs = snapshot.logs ?? [];
481
+ const latestByStage = new Map;
482
+ for (const log of logs) {
483
+ const title = String(log.title ?? "").toLowerCase();
484
+ const stageName = String(log.stage ?? "").toLowerCase();
485
+ const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
486
+ if (stage)
487
+ latestByStage.set(stage, log);
488
+ }
331
489
  const stageLines = CANONICAL_STAGES.flatMap((stage) => {
332
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
333
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
490
+ const match = latestByStage.get(stage);
491
+ return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
334
492
  });
335
493
  return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
336
494
  `);
337
495
  }
496
+ function createPiRunStreamRenderer(output = process.stdout) {
497
+ let lastSnapshot = "";
498
+ const assistantTextById = new Map;
499
+ const seenTimeline = new Set;
500
+ const seenLogs = new Set;
501
+ const writeLine = (line) => output.write(`${line}
502
+ `);
503
+ return {
504
+ renderSnapshot(snapshot) {
505
+ const rendered = renderOperatorSnapshot(snapshot);
506
+ if (rendered && rendered !== lastSnapshot) {
507
+ writeLine(rendered);
508
+ lastSnapshot = rendered;
509
+ }
510
+ },
511
+ renderTimeline(entries) {
512
+ for (const [index, entry] of entries.entries()) {
513
+ const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
514
+ if (entry.type === "assistant_message" && typeof entry.text === "string") {
515
+ const text = entry.text;
516
+ const previousText = assistantTextById.get(id) ?? "";
517
+ if (!previousText && text.trim()) {
518
+ writeLine("[Pi assistant]");
519
+ }
520
+ if (text.startsWith(previousText)) {
521
+ const delta = text.slice(previousText.length);
522
+ if (delta)
523
+ output.write(delta);
524
+ } else if (text.trim() && text !== previousText) {
525
+ if (previousText)
526
+ writeLine(`
527
+ [Pi assistant]`);
528
+ output.write(text);
529
+ }
530
+ assistantTextById.set(id, text);
531
+ continue;
532
+ }
533
+ if (seenTimeline.has(id))
534
+ continue;
535
+ seenTimeline.add(id);
536
+ if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
537
+ writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
538
+ continue;
539
+ }
540
+ if (entry.type === "timeline_warning") {
541
+ writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
542
+ continue;
543
+ }
544
+ if (entry.type === "action") {
545
+ const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
546
+ if (text)
547
+ writeLine(`[Rig action] ${text}`);
548
+ continue;
549
+ }
550
+ if (entry.type === "user_message") {
551
+ const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
552
+ if (text)
553
+ writeLine(`[Operator] ${text}`);
554
+ continue;
555
+ }
556
+ const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
557
+ if (fallback)
558
+ writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
559
+ }
560
+ },
561
+ renderLogs(entries) {
562
+ for (const [index, entry] of entries.entries()) {
563
+ const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
564
+ if (seenLogs.has(id))
565
+ continue;
566
+ seenLogs.add(id);
567
+ const title = String(entry.title ?? "");
568
+ if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
569
+ continue;
570
+ const detail = logDetail(entry);
571
+ if (!detail)
572
+ continue;
573
+ const protocolRecord = parseProviderProtocolLog(title, detail);
574
+ if (protocolRecord) {
575
+ const protocolLine = renderProviderProtocolLog(protocolRecord);
576
+ if (protocolLine)
577
+ writeLine(protocolLine);
578
+ continue;
579
+ }
580
+ writeLine(`[${title || "Rig log"}] ${detail}`);
581
+ }
582
+ }
583
+ };
584
+ }
585
+ function createOperatorSurface(options = {}) {
586
+ const input = options.input ?? process.stdin;
587
+ const output = options.output ?? process.stdout;
588
+ const errorOutput = options.errorOutput ?? process.stderr;
589
+ const renderer = createPiRunStreamRenderer(output);
590
+ const writeLine = (line) => output.write(`${line}
591
+ `);
592
+ return {
593
+ mode: "pi-compatible-text",
594
+ ...renderer,
595
+ info: writeLine,
596
+ error: (message) => errorOutput.write(`${message}
597
+ `),
598
+ attachCommandInput(handler) {
599
+ if (options.interactive === false || !input.isTTY)
600
+ return null;
601
+ const rl = createInterface({ input, output: process.stdout, terminal: false });
602
+ rl.on("line", (line) => {
603
+ Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
604
+ });
605
+ return { close: () => rl.close() };
606
+ }
607
+ };
608
+ }
609
+
610
+ // packages/cli/src/commands/_pi-frontend.ts
611
+ import { mkdtempSync, rmSync } from "fs";
612
+ import { tmpdir } from "os";
613
+ import { join } from "path";
614
+ import {
615
+ createAgentSessionFromServices,
616
+ createAgentSessionServices,
617
+ main as runPiMain
618
+ } from "@earendil-works/pi-coding-agent";
619
+
620
+ // packages/cli/src/commands/_pi-remote-session.ts
621
+ import { AgentSession as PiAgentSession, expandPromptTemplate } from "@earendil-works/pi-coding-agent";
622
+ var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
623
+ function defaultTransport() {
624
+ return {
625
+ getSession: getRunPiSessionViaServer,
626
+ getMessages: getRunPiMessagesViaServer,
627
+ getStatus: getRunPiStatusViaServer,
628
+ getCommands: getRunPiCommandsViaServer,
629
+ getCapabilities: getRunPiCapabilitiesViaServer,
630
+ sendPrompt: sendRunPiPromptViaServer,
631
+ sendShell: sendRunPiShellViaServer,
632
+ runCommand: runRunPiCommandViaServer,
633
+ abort: abortRunPiViaServer,
634
+ buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
635
+ };
636
+ }
637
+ function recordOf(value) {
638
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
639
+ }
640
+ function emptyRemoteStatus() {
641
+ return {
642
+ isStreaming: false,
643
+ isCompacting: false,
644
+ isBashRunning: false,
645
+ pendingMessageCount: 0,
646
+ steeringMessages: [],
647
+ followUpMessages: [],
648
+ model: null,
649
+ thinkingLevel: null,
650
+ sessionName: null,
651
+ cwd: null,
652
+ stats: null,
653
+ contextUsage: null
654
+ };
655
+ }
656
+ function resolveAttachReadyTimeoutMs() {
657
+ const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
658
+ return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
659
+ }
660
+
661
+ class RigRemoteSessionController {
662
+ context;
663
+ runId;
664
+ status = emptyRemoteStatus();
665
+ transport;
666
+ hooks = {};
667
+ session = null;
668
+ socket = null;
669
+ closed = false;
670
+ pendingShells = [];
671
+ pendingCompactions = [];
672
+ constructor(input) {
673
+ this.context = input.context;
674
+ this.runId = input.runId;
675
+ this.transport = input.transport ?? defaultTransport();
676
+ }
677
+ ingestEnvelope(envelopeValue) {
678
+ this.applyEnvelope(envelopeValue);
679
+ }
680
+ bindSession(session) {
681
+ this.session = session;
682
+ }
683
+ setUiHooks(hooks) {
684
+ this.hooks = hooks;
685
+ }
686
+ async connect() {
687
+ const ready = await this.waitForReady();
688
+ if (!ready || this.closed)
689
+ return;
690
+ let catchupDone = false;
691
+ const buffered = [];
692
+ const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
693
+ const socket = new WebSocket(wsUrl);
694
+ this.socket = socket;
695
+ socket.onopen = () => {
696
+ this.hooks.onConnectionChange?.(true);
697
+ this.hooks.onStatusText?.("worker session live");
698
+ };
699
+ socket.onmessage = (message) => {
700
+ try {
701
+ const payload = typeof message.data === "string" ? JSON.parse(message.data) : JSON.parse(Buffer.from(message.data).toString("utf8"));
702
+ if (!catchupDone)
703
+ buffered.push(payload);
704
+ else
705
+ this.applyEnvelope(payload);
706
+ } catch (error) {
707
+ this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
708
+ }
709
+ };
710
+ socket.onerror = () => socket.close();
711
+ socket.onclose = () => {
712
+ this.hooks.onConnectionChange?.(false);
713
+ if (!this.closed)
714
+ this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
715
+ };
716
+ try {
717
+ const [messagesPayload, statusPayload, commandsPayload, capabilitiesPayload] = await Promise.all([
718
+ this.transport.getMessages(this.context, this.runId),
719
+ this.transport.getStatus(this.context, this.runId),
720
+ this.transport.getCommands(this.context, this.runId),
721
+ this.transport.getCapabilities(this.context, this.runId).catch(() => ({ capabilities: null }))
722
+ ]);
723
+ const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
724
+ this.applyStatusPayload(statusPayload);
725
+ this.session?.replaceRemoteMessages(messages);
726
+ const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
727
+ const capabilities = capabilitiesPayload.capabilities && typeof capabilitiesPayload.capabilities === "object" && !Array.isArray(capabilitiesPayload.capabilities) ? capabilitiesPayload.capabilities : null;
728
+ this.hooks.onCatchUp?.(messages, commands, capabilities);
729
+ catchupDone = true;
730
+ for (const payload of buffered.splice(0))
731
+ this.applyEnvelope(payload);
732
+ } catch (error) {
733
+ catchupDone = true;
734
+ this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
735
+ }
736
+ }
737
+ close() {
738
+ this.closed = true;
739
+ this.socket?.close();
740
+ for (const shell of this.pendingShells.splice(0))
741
+ shell.reject(new Error("Remote session closed."));
742
+ for (const compaction of this.pendingCompactions.splice(0))
743
+ compaction.reject(new Error("Remote session closed."));
744
+ }
745
+ async sendPrompt(text, streamingBehavior) {
746
+ await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
747
+ }
748
+ async sendCommand(text) {
749
+ const result = await this.transport.runCommand(this.context, this.runId, text);
750
+ return typeof result.message === "string" ? result.message : "worker command accepted";
751
+ }
752
+ async sendShell(text) {
753
+ await this.transport.sendShell(this.context, this.runId, text);
754
+ }
755
+ async abort() {
756
+ await this.transport.abort(this.context, this.runId);
757
+ }
758
+ registerPendingShell(shell) {
759
+ this.pendingShells.push(shell);
760
+ }
761
+ failPendingShell(shell, error) {
762
+ const index = this.pendingShells.indexOf(shell);
763
+ if (index !== -1)
764
+ this.pendingShells.splice(index, 1);
765
+ shell.reject(error);
766
+ }
767
+ registerPendingCompaction(pending) {
768
+ this.pendingCompactions.push(pending);
769
+ }
770
+ async waitForReady() {
771
+ const startedAt = Date.now();
772
+ const deadline = startedAt + resolveAttachReadyTimeoutMs();
773
+ let consecutiveFailures = 0;
774
+ while (!this.closed) {
775
+ let requestFailed = false;
776
+ const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
777
+ requestFailed = true;
778
+ return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
779
+ });
780
+ if (session.ready !== false)
781
+ return true;
782
+ consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
783
+ const status = String(session.status ?? "starting");
784
+ if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
785
+ this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
786
+ return false;
787
+ }
788
+ 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`);
789
+ if (Date.now() >= deadline) {
790
+ this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
791
+ return false;
792
+ }
793
+ await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
794
+ }
795
+ return false;
796
+ }
797
+ applyEnvelope(envelopeValue) {
798
+ const envelope = recordOf(envelopeValue);
799
+ if (!envelope)
800
+ return;
801
+ const type = String(envelope.type ?? "");
802
+ if (type === "status.update") {
803
+ this.applyStatusPayload(envelope);
804
+ return;
805
+ }
806
+ if (type === "activity.update") {
807
+ const activity = recordOf(envelope.activity);
808
+ this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
809
+ return;
810
+ }
811
+ if (type === "extension_ui_request") {
812
+ const request = recordOf(envelope.request);
813
+ if (request)
814
+ this.hooks.onExtensionUiRequest?.(request);
815
+ return;
816
+ }
817
+ if (type === "pi.ui_event") {
818
+ this.applyShellUiEvent(envelope.event);
819
+ return;
820
+ }
821
+ if (type === "pi.event") {
822
+ this.session?.handleRemoteSessionEvent(envelope.event);
823
+ this.settlePendingCompaction(envelope.event);
824
+ return;
825
+ }
826
+ if (type === "error") {
827
+ this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
828
+ }
829
+ }
830
+ applyStatusPayload(payload) {
831
+ const status = recordOf(payload.status) ?? payload;
832
+ const next = this.status;
833
+ next.isStreaming = status.isStreaming === true;
834
+ next.isCompacting = status.isCompacting === true;
835
+ next.isBashRunning = status.isBashRunning === true;
836
+ next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
837
+ next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
838
+ next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
839
+ next.model = recordOf(status.model) ?? next.model;
840
+ next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
841
+ next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
842
+ next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
843
+ next.stats = recordOf(status.stats) ?? next.stats;
844
+ next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
845
+ }
846
+ applyShellUiEvent(value) {
847
+ const event = recordOf(value);
848
+ if (!event)
849
+ return;
850
+ const type = String(event.type ?? "");
851
+ const pending = this.pendingShells[0];
852
+ if (type === "shell.chunk" && pending) {
853
+ pending.sawChunk = true;
854
+ pending.onData(Buffer.from(String(event.chunk ?? "")));
855
+ return;
856
+ }
857
+ if (type === "shell.end" && pending) {
858
+ const output = String(event.output ?? "");
859
+ if (output && !pending.sawChunk)
860
+ pending.onData(Buffer.from(output));
861
+ const index = this.pendingShells.indexOf(pending);
862
+ if (index !== -1)
863
+ this.pendingShells.splice(index, 1);
864
+ pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
865
+ }
866
+ }
867
+ settlePendingCompaction(eventValue) {
868
+ const event = recordOf(eventValue);
869
+ if (!event)
870
+ return;
871
+ const type = String(event.type ?? "");
872
+ if (type !== "compaction_end" || this.pendingCompactions.length === 0)
873
+ return;
874
+ const pending = this.pendingCompactions.shift();
875
+ const result = recordOf(event.result);
876
+ if (result)
877
+ pending.resolve(result);
878
+ else if (event.aborted === true)
879
+ pending.reject(new Error("Compaction aborted on the worker."));
880
+ else
881
+ pending.resolve({});
882
+ }
883
+ }
884
+
885
+ class RigRemoteAgentSession extends PiAgentSession {
886
+ remote;
887
+ constructor(config, remote) {
888
+ super(config);
889
+ this.remote = remote;
890
+ remote.bindSession(this);
891
+ }
892
+ handleRemoteSessionEvent(eventValue) {
893
+ const event = recordOf(eventValue);
894
+ if (!event)
895
+ return;
896
+ const type = String(event.type ?? "");
897
+ if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
898
+ this.agent.state.messages = [...this.agent.state.messages, event.message];
899
+ }
900
+ this._emit(eventValue);
901
+ }
902
+ replaceRemoteMessages(messages) {
903
+ this.agent.state.messages = messages;
904
+ }
905
+ async expandLocalInput(text) {
906
+ let current = text;
907
+ const runner = this.extensionRunner;
908
+ if (runner.hasHandlers("input")) {
909
+ const result = await runner.emitInput(current, undefined, "interactive");
910
+ if (result.action === "handled")
911
+ return null;
912
+ if (result.action === "transform")
913
+ current = result.text;
914
+ }
915
+ current = this._expandSkillCommand(current);
916
+ current = expandPromptTemplate(current, [...this.promptTemplates]);
917
+ return current;
918
+ }
919
+ async prompt(text, options) {
920
+ const trimmed = text.trim();
921
+ if (!trimmed)
922
+ return;
923
+ if (trimmed.startsWith("/")) {
924
+ if (await this._tryExecuteExtensionCommand(trimmed))
925
+ return;
926
+ const expanded2 = await this.expandLocalInput(trimmed);
927
+ if (expanded2 === null)
928
+ return;
929
+ if (expanded2 !== trimmed) {
930
+ const behavior2 = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
931
+ options?.preflightResult?.(true);
932
+ await this.remote.sendPrompt(expanded2, behavior2);
933
+ return;
934
+ }
935
+ await this.remote.sendCommand(trimmed);
936
+ return;
937
+ }
938
+ if (trimmed.startsWith("!")) {
939
+ await this.remote.sendShell(trimmed);
940
+ return;
941
+ }
942
+ const expanded = await this.expandLocalInput(trimmed);
943
+ if (expanded === null)
944
+ return;
945
+ const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
946
+ options?.preflightResult?.(true);
947
+ await this.remote.sendPrompt(expanded, behavior);
948
+ }
949
+ async steer(text) {
950
+ const trimmed = text.trim();
951
+ if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
952
+ return;
953
+ const expanded = await this.expandLocalInput(trimmed);
954
+ if (expanded === null)
955
+ return;
956
+ await this.remote.sendPrompt(expanded, "steer");
957
+ }
958
+ async followUp(text) {
959
+ const trimmed = text.trim();
960
+ if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
961
+ return;
962
+ const expanded = await this.expandLocalInput(trimmed);
963
+ if (expanded === null)
964
+ return;
965
+ await this.remote.sendPrompt(expanded, "followUp");
966
+ }
967
+ async abort() {
968
+ await this.remote.abort();
969
+ }
970
+ async compact(customInstructions) {
971
+ const pending = new Promise((resolve3, reject) => {
972
+ this.remote.registerPendingCompaction({ resolve: resolve3, reject });
973
+ });
974
+ await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
975
+ return pending;
976
+ }
977
+ clearQueue() {
978
+ const cleared = {
979
+ steering: [...this.remote.status.steeringMessages],
980
+ followUp: [...this.remote.status.followUpMessages]
981
+ };
982
+ this.remote.status.steeringMessages = [];
983
+ this.remote.status.followUpMessages = [];
984
+ this.remote.status.pendingMessageCount = 0;
985
+ this.remote.sendCommand("/queue-clear").catch(() => {});
986
+ return cleared;
987
+ }
988
+ get isStreaming() {
989
+ return this.remote.status.isStreaming;
990
+ }
991
+ get isCompacting() {
992
+ return this.remote.status.isCompacting;
993
+ }
994
+ get isBashRunning() {
995
+ return this.remote.status.isBashRunning;
996
+ }
997
+ get pendingMessageCount() {
998
+ return this.remote.status.pendingMessageCount;
999
+ }
1000
+ getSteeringMessages() {
1001
+ return this.remote.status.steeringMessages;
1002
+ }
1003
+ getFollowUpMessages() {
1004
+ return this.remote.status.followUpMessages;
1005
+ }
1006
+ get model() {
1007
+ return this.remote.status.model ?? super.model;
1008
+ }
1009
+ async setModel(model) {
1010
+ await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
1011
+ this.remote.status.model = model;
1012
+ }
1013
+ get thinkingLevel() {
1014
+ return this.remote.status.thinkingLevel ?? super.thinkingLevel;
1015
+ }
1016
+ setThinkingLevel(level) {
1017
+ this.remote.status.thinkingLevel = level;
1018
+ this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
1019
+ }
1020
+ get sessionName() {
1021
+ return this.remote.status.sessionName ?? super.sessionName;
1022
+ }
1023
+ setSessionName(name) {
1024
+ this.remote.status.sessionName = name;
1025
+ this.remote.sendCommand(`/name ${name}`).catch(() => {});
1026
+ }
1027
+ getSessionStats() {
1028
+ return this.remote.status.stats ?? super.getSessionStats();
1029
+ }
1030
+ getContextUsage() {
1031
+ return this.remote.status.contextUsage ?? super.getContextUsage();
1032
+ }
1033
+ dispose() {
1034
+ this.remote.close();
1035
+ super.dispose();
1036
+ }
1037
+ }
1038
+ function createRemoteBashOperations(controller, excludeFromContext) {
1039
+ return {
1040
+ exec(command, _cwd, execOptions) {
1041
+ return new Promise((resolve3, reject) => {
1042
+ const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
1043
+ const cleanup = () => {
1044
+ execOptions.signal?.removeEventListener("abort", onAbort);
1045
+ if (timer)
1046
+ clearTimeout(timer);
1047
+ };
1048
+ const onAbort = () => {
1049
+ cleanup();
1050
+ controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
1051
+ };
1052
+ const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
1053
+ const timer = timeoutMs > 0 ? setTimeout(() => {
1054
+ cleanup();
1055
+ controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
1056
+ }, timeoutMs) : null;
1057
+ const wrappedResolve = pending.resolve;
1058
+ const wrappedReject = pending.reject;
1059
+ pending.resolve = (result) => {
1060
+ cleanup();
1061
+ wrappedResolve(result);
1062
+ };
1063
+ pending.reject = (error) => {
1064
+ cleanup();
1065
+ wrappedReject(error);
1066
+ };
1067
+ execOptions.signal?.addEventListener("abort", onAbort, { once: true });
1068
+ controller.registerPendingShell(pending);
1069
+ controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
1070
+ cleanup();
1071
+ controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
1072
+ });
1073
+ });
1074
+ }
1075
+ };
1076
+ }
1077
+
1078
+ // packages/cli/src/commands/_spinner.ts
1079
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1080
+
1081
+ // packages/cli/src/commands/_pi-worker-bridge-extension.ts
1082
+ function recordOf2(value) {
1083
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1084
+ }
1085
+ function asText(value) {
1086
+ if (typeof value === "string")
1087
+ return value;
1088
+ if (value === null || value === undefined)
1089
+ return "";
1090
+ if (typeof value === "number" || typeof value === "boolean")
1091
+ return String(value);
1092
+ try {
1093
+ return JSON.stringify(value);
1094
+ } catch {
1095
+ return String(value);
1096
+ }
1097
+ }
1098
+ function names(value, key = "name") {
1099
+ if (!Array.isArray(value))
1100
+ return [];
1101
+ return value.flatMap((entry) => {
1102
+ if (typeof entry === "string")
1103
+ return [entry];
1104
+ const record = recordOf2(entry);
1105
+ const name = record?.[key];
1106
+ return typeof name === "string" ? [name] : [];
1107
+ });
1108
+ }
1109
+ function renderWorkerCapabilities(capabilities) {
1110
+ const lines = ["Worker session capabilities (in effect for this run)"];
1111
+ const tools = Array.isArray(capabilities.tools) ? capabilities.tools : [];
1112
+ const activeTools = tools.flatMap((tool) => {
1113
+ const record = recordOf2(tool);
1114
+ return record && record.active === true && typeof record.name === "string" ? [record.name] : [];
1115
+ });
1116
+ const inactiveCount = tools.length - activeTools.length;
1117
+ lines.push(` tools ${activeTools.join(", ") || "(none)"}${inactiveCount > 0 ? ` (+${inactiveCount} inactive)` : ""}`);
1118
+ const extensions = Array.isArray(capabilities.extensions) ? capabilities.extensions : [];
1119
+ const extensionLabels = extensions.flatMap((entry) => {
1120
+ const record = recordOf2(entry);
1121
+ if (!record)
1122
+ return [];
1123
+ const path = typeof record.path === "string" ? record.path : "";
1124
+ const short = path.split("/").filter(Boolean).slice(-2).join("/") || path || "extension";
1125
+ return [short];
1126
+ });
1127
+ lines.push(` extensions ${extensionLabels.join(", ") || "(none)"}`);
1128
+ const hookEvents = names(capabilities.hookEvents);
1129
+ const hookList = Array.isArray(capabilities.hookEvents) ? capabilities.hookEvents.map(asText).filter(Boolean) : hookEvents;
1130
+ lines.push(` hooks ${hookList.join(", ") || "(none)"}`);
1131
+ lines.push(` skills ${names(capabilities.skills).join(", ") || "(none)"}`);
1132
+ lines.push(` prompts ${names(capabilities.prompts).join(", ") || "(none)"}`);
1133
+ const model = typeof capabilities.model === "string" ? capabilities.model : "(unknown)";
1134
+ const thinking = typeof capabilities.thinkingLevel === "string" ? capabilities.thinkingLevel : "";
1135
+ const cwd = typeof capabilities.cwd === "string" ? capabilities.cwd : "";
1136
+ lines.push(` model ${model}${thinking ? ` \xB7 ${thinking}` : ""}`);
1137
+ if (cwd)
1138
+ lines.push(` cwd ${cwd}`);
1139
+ lines.push(" (worker commands are in your palette as [worker \u2026] \xB7 /worker shows this again)");
1140
+ return lines;
1141
+ }
1142
+ async function answerExtensionUiRequest(options, ctx, request) {
1143
+ const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
1144
+ const method = String(request.method ?? request.type ?? "input");
1145
+ const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
1146
+ const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
1147
+ const choices = rawOptions.map((option) => {
1148
+ const record = recordOf2(option);
1149
+ return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
1150
+ }).filter(Boolean);
1151
+ try {
1152
+ if (method === "confirm") {
1153
+ const confirmed = await ctx.ui.confirm("Worker request", prompt);
1154
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
1155
+ return;
1156
+ }
1157
+ if (choices.length > 0) {
1158
+ const selected = await ctx.ui.select(prompt, choices);
1159
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
1160
+ return;
1161
+ }
1162
+ const value = await ctx.ui.input("Worker request", prompt);
1163
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
1164
+ } catch (error) {
1165
+ ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
1166
+ }
1167
+ }
1168
+ var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "worker", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
1169
+ function registerDaemonCommands(pi, options, ctx, commands, registered) {
1170
+ for (const command of commands) {
1171
+ const record = recordOf2(command);
1172
+ const name = typeof record?.name === "string" ? record.name : "";
1173
+ const source = typeof record?.source === "string" ? record.source : "worker";
1174
+ if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
1175
+ continue;
1176
+ registered.add(name);
1177
+ const description = typeof record?.description === "string" ? record.description : undefined;
1178
+ try {
1179
+ pi.registerCommand(name, {
1180
+ description: `[worker ${source}] ${description ?? ""}`.trim(),
1181
+ handler: async (args) => {
1182
+ try {
1183
+ const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
1184
+ ctx.ui.notify(message, "info");
1185
+ } catch (error) {
1186
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1187
+ }
1188
+ }
1189
+ });
1190
+ } catch {}
1191
+ }
1192
+ }
1193
+ function createRigWorkerPiBridgeExtension(options) {
1194
+ return (pi) => {
1195
+ const registeredDaemonCommands = new Set;
1196
+ let capabilityLines = null;
1197
+ let statusText = "connecting to worker session";
1198
+ let busy = true;
1199
+ let connected = false;
1200
+ let frame = 0;
1201
+ let spinnerTimer = null;
1202
+ const renderStatus = (ctx) => {
1203
+ const prefix = busy ? `${SPINNER_FRAMES[frame]} ` : connected ? "\u25CF " : "\u25CB ";
1204
+ ctx.ui.setStatus("rig-worker-pi", `${prefix}${statusText}`);
1205
+ };
1206
+ const setStatus = (ctx, text, isBusy) => {
1207
+ statusText = text;
1208
+ busy = isBusy;
1209
+ renderStatus(ctx);
1210
+ };
1211
+ pi.registerCommand("detach", {
1212
+ description: "Detach from this run; the worker keeps going",
1213
+ handler: async (_args, ctx) => {
1214
+ ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
1215
+ ctx.shutdown();
1216
+ }
1217
+ });
1218
+ pi.registerCommand("stop", {
1219
+ description: "Stop the worker Pi run and detach",
1220
+ handler: async (_args, ctx) => {
1221
+ await options.controller.abort();
1222
+ ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
1223
+ ctx.shutdown();
1224
+ }
1225
+ });
1226
+ pi.registerCommand("worker", {
1227
+ description: "Show the worker session's real capabilities (tools, extensions, hooks, skills)",
1228
+ handler: async (_args, ctx) => {
1229
+ if (capabilityLines)
1230
+ ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
1231
+ else
1232
+ ctx.ui.notify("Worker capabilities are not available yet (still connecting).", "info");
1233
+ }
1234
+ });
1235
+ pi.on("user_bash", (event) => ({
1236
+ operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
1237
+ }));
1238
+ pi.on("session_start", async (_event, ctx) => {
1239
+ ctx.ui.setTitle("Rig \xB7 enriched bundled Pi");
1240
+ setStatus(ctx, "waiting for worker Pi daemon", true);
1241
+ spinnerTimer = setInterval(() => {
1242
+ frame = (frame + 1) % SPINNER_FRAMES.length;
1243
+ if (busy)
1244
+ renderStatus(ctx);
1245
+ }, 150);
1246
+ 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");
1247
+ if (options.initialMessageSent)
1248
+ ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
1249
+ const nativeUi = ctx.ui;
1250
+ options.controller.setUiHooks({
1251
+ onStatusText: (text) => setStatus(ctx, text, !connected),
1252
+ onActivity: (label, detail) => {
1253
+ const active = label !== "idle" && !/complete|ready/i.test(label);
1254
+ setStatus(ctx, [label, detail].filter(Boolean).join(" \u2014 "), active);
1255
+ if (/agent running|tool:/.test(label))
1256
+ ctx.ui.setWidget("rig-worker-capabilities", undefined);
1257
+ },
1258
+ onConnectionChange: (nextConnected) => {
1259
+ connected = nextConnected;
1260
+ setStatus(ctx, nextConnected ? "worker session live" : "worker session disconnected", false);
1261
+ },
1262
+ onError: (message) => ctx.ui.notify(message, "error"),
1263
+ onExtensionUiRequest: (request) => {
1264
+ answerExtensionUiRequest(options, ctx, request);
1265
+ },
1266
+ onCatchUp: (messages, commands, capabilities) => {
1267
+ if (nativeUi.appendSessionMessages)
1268
+ nativeUi.appendSessionMessages(messages);
1269
+ const cwd = options.controller.status.cwd;
1270
+ if (nativeUi.setDisplayCwd && cwd)
1271
+ nativeUi.setDisplayCwd(cwd);
1272
+ registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
1273
+ if (capabilities) {
1274
+ capabilityLines = renderWorkerCapabilities(capabilities);
1275
+ ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
1276
+ }
1277
+ }
1278
+ });
1279
+ options.controller.connect().catch((error) => {
1280
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1281
+ });
1282
+ });
1283
+ pi.on("session_shutdown", () => {
1284
+ if (spinnerTimer)
1285
+ clearInterval(spinnerTimer);
1286
+ options.controller.close();
1287
+ });
1288
+ };
1289
+ }
1290
+
1291
+ // packages/cli/src/commands/_pi-frontend.ts
1292
+ function setTemporaryEnv(updates) {
1293
+ const previous = new Map;
1294
+ for (const [key, value] of Object.entries(updates)) {
1295
+ previous.set(key, process.env[key]);
1296
+ process.env[key] = value;
1297
+ }
1298
+ return () => {
1299
+ for (const [key, value] of previous) {
1300
+ if (value === undefined)
1301
+ delete process.env[key];
1302
+ else
1303
+ process.env[key] = value;
1304
+ }
1305
+ };
1306
+ }
1307
+ async function attachRunBundledPiFrontend(context, input) {
1308
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1309
+ const restoreEnv = setTemporaryEnv({
1310
+ PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
1311
+ PI_SKIP_VERSION_CHECK: "1",
1312
+ PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust"
1313
+ });
1314
+ const controller = new RigRemoteSessionController({ context, runId: input.runId });
1315
+ const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
1316
+ const services = await createAgentSessionServices({
1317
+ cwd,
1318
+ agentDir,
1319
+ resourceLoaderOptions: {
1320
+ extensionFactories: [
1321
+ createRigWorkerPiBridgeExtension({
1322
+ context,
1323
+ controller,
1324
+ runId: input.runId,
1325
+ initialMessageSent: input.steered === true
1326
+ })
1327
+ ],
1328
+ noExtensions: true,
1329
+ noSkills: true,
1330
+ noPromptTemplates: true,
1331
+ noContextFiles: true
1332
+ }
1333
+ });
1334
+ const created = await createAgentSessionFromServices({
1335
+ services,
1336
+ sessionManager,
1337
+ sessionStartEvent,
1338
+ noTools: "all",
1339
+ sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
1340
+ });
1341
+ return { ...created, services, diagnostics: services.diagnostics };
1342
+ };
1343
+ let detached = false;
1344
+ try {
1345
+ await runPiMain([], {
1346
+ createRuntimeOverride: () => createRemoteRuntime
1347
+ });
1348
+ detached = true;
1349
+ } finally {
1350
+ restoreEnv();
1351
+ controller.close();
1352
+ rmSync(tempSessionDir, { recursive: true, force: true });
1353
+ }
1354
+ let run = { runId: input.runId, status: "unknown" };
1355
+ try {
1356
+ run = await getRunDetailsViaServer(context, input.runId);
1357
+ } catch {}
1358
+ return {
1359
+ run,
1360
+ logs: [],
1361
+ timeline: [],
1362
+ timelineCursor: null,
1363
+ steered: input.steered === true,
1364
+ detached,
1365
+ rendered: "enriched bundled Pi frontend with remote worker session runtime"
1366
+ };
1367
+ }
1368
+
1369
+ // packages/cli/src/commands/_operator-view.ts
1370
+ var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
338
1371
  function runStatusFromPayload(payload) {
339
1372
  const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
340
1373
  return String(run.status ?? "unknown").toLowerCase();
@@ -356,56 +1389,268 @@ async function applyOperatorCommand(context, input, deps = {}) {
356
1389
  await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
357
1390
  return { action: "continue", message: "Steering message queued." };
358
1391
  }
359
- async function readOperatorSnapshot(context, runId) {
1392
+ async function readOperatorSnapshot(context, runId, options = {}) {
360
1393
  const run = await getRunDetailsViaServer(context, runId);
361
1394
  const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
362
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
363
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
1395
+ const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
1396
+ entries: [{
1397
+ id: `timeline-unavailable:${runId}`,
1398
+ type: "timeline_warning",
1399
+ detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
1400
+ createdAt: new Date().toISOString()
1401
+ }],
1402
+ nextCursor: options.timelineCursor ?? null
1403
+ }));
1404
+ const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
1405
+ const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1406
+ const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
1407
+ return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
364
1408
  }
365
1409
  async function attachRunOperatorView(context, input) {
366
1410
  let steered = false;
367
1411
  if (input.message?.trim()) {
368
- await steerRunViaServer(context, input.runId, input.message.trim());
1412
+ await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
369
1413
  steered = true;
370
1414
  }
1415
+ if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
1416
+ return attachRunBundledPiFrontend(context, {
1417
+ runId: input.runId,
1418
+ steered
1419
+ });
1420
+ }
1421
+ const surface = createOperatorSurface({ interactive: input.interactive !== false });
371
1422
  let snapshot = await readOperatorSnapshot(context, input.runId);
372
1423
  if (context.outputMode === "text") {
373
- console.log(snapshot.rendered);
1424
+ surface.renderSnapshot(snapshot);
1425
+ surface.renderTimeline(snapshot.timeline);
1426
+ surface.renderLogs(snapshot.logs);
374
1427
  if (steered)
375
- console.log("Steering message queued.");
1428
+ surface.info("Message submitted to worker Pi.");
376
1429
  }
377
1430
  let detached = false;
378
- let rl = null;
1431
+ let commandInput = null;
379
1432
  if (input.follow && !input.once && context.outputMode === "text") {
380
1433
  if (input.interactive !== false && process.stdin.isTTY) {
381
- console.log("Controls: /user <message>, /stop, /detach");
382
- rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
383
- rl.on("line", (line) => {
384
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
385
- if (result.message)
386
- console.log(result.message);
387
- if (result.action === "detach" || result.action === "stopped") {
388
- detached = true;
389
- rl?.close();
390
- }
391
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
1434
+ surface.info("Controls: /user <message>, /stop, /detach");
1435
+ commandInput = surface.attachCommandInput(async (line) => {
1436
+ const result = await applyOperatorCommand(context, { runId: input.runId, line });
1437
+ if (result.message)
1438
+ surface.info(result.message);
1439
+ if (result.action === "detach" || result.action === "stopped") {
1440
+ detached = true;
1441
+ commandInput?.close();
1442
+ }
392
1443
  });
393
1444
  }
394
- let lastRendered = snapshot.rendered;
395
1445
  const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
396
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
1446
+ let timelineCursor = snapshot.timelineCursor;
1447
+ while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
397
1448
  await Bun.sleep(pollMs);
398
- snapshot = await readOperatorSnapshot(context, input.runId);
399
- if (snapshot.rendered !== lastRendered) {
400
- console.log(snapshot.rendered);
401
- lastRendered = snapshot.rendered;
402
- }
1449
+ snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
1450
+ timelineCursor = snapshot.timelineCursor;
1451
+ surface.renderSnapshot(snapshot);
1452
+ surface.renderTimeline(snapshot.timeline);
1453
+ surface.renderLogs(snapshot.logs);
403
1454
  }
404
- rl?.close();
1455
+ commandInput?.close();
405
1456
  }
406
1457
  return { ...snapshot, steered, detached };
407
1458
  }
408
1459
 
1460
+ // packages/cli/src/commands/_cli-format.ts
1461
+ import { log, note } from "@clack/prompts";
1462
+ import pc from "picocolors";
1463
+ function stringField(record, key, fallback = "") {
1464
+ const value = record[key];
1465
+ return typeof value === "string" && value.trim() ? value.trim() : fallback;
1466
+ }
1467
+ function rawObject(record) {
1468
+ const raw = record.raw;
1469
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
1470
+ }
1471
+ function truncate(value, width) {
1472
+ if (value.length <= width)
1473
+ return value;
1474
+ if (width <= 1)
1475
+ return "\u2026";
1476
+ return `${value.slice(0, width - 1)}\u2026`;
1477
+ }
1478
+ function pad(value, width) {
1479
+ return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
1480
+ }
1481
+ function statusColor(status) {
1482
+ const normalized = status.toLowerCase();
1483
+ if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved"].includes(normalized))
1484
+ return pc.green;
1485
+ if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
1486
+ return pc.red;
1487
+ if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
1488
+ return pc.cyan;
1489
+ if (["ready", "open", "queued", "created", "preparing", "local", "pending"].includes(normalized))
1490
+ return pc.yellow;
1491
+ return pc.dim;
1492
+ }
1493
+ function compactDate(value) {
1494
+ if (!value.trim())
1495
+ return "";
1496
+ const parsed = Date.parse(value);
1497
+ if (!Number.isFinite(parsed))
1498
+ return value;
1499
+ return new Date(parsed).toISOString().replace("T", " ").replace(/\.\d{3}Z$/, "Z");
1500
+ }
1501
+ function firstString(record, keys, fallback = "") {
1502
+ for (const key of keys) {
1503
+ const value = stringField(record, key);
1504
+ if (value)
1505
+ return value;
1506
+ }
1507
+ return fallback;
1508
+ }
1509
+ function runIdOf(run) {
1510
+ return firstString(run, ["runId", "id"], "(unknown-run)");
1511
+ }
1512
+ function taskIdOf(run) {
1513
+ return firstString(run, ["taskId", "task", "task_id"]);
1514
+ }
1515
+ function runTitleOf(run) {
1516
+ return firstString(run, ["title", "summary", "name"], taskIdOf(run) || "(untitled)");
1517
+ }
1518
+ function shouldUseClackOutput() {
1519
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
1520
+ }
1521
+ function printFormattedOutput(message, options = {}) {
1522
+ if (!shouldUseClackOutput()) {
1523
+ console.log(message);
1524
+ return;
1525
+ }
1526
+ if (options.title)
1527
+ note(message, options.title);
1528
+ else
1529
+ log.message(message);
1530
+ }
1531
+ function formatStatusPill(status) {
1532
+ const label = status || "unknown";
1533
+ return statusColor(label)(`\u25CF ${label}`);
1534
+ }
1535
+ function formatSection(title, subtitle) {
1536
+ return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
1537
+ }
1538
+ function formatSuccessCard(title, rows = []) {
1539
+ 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}`);
1540
+ return [formatSection(title), ...body].join(`
1541
+ `);
1542
+ }
1543
+ function formatNextSteps(steps) {
1544
+ if (steps.length === 0)
1545
+ return [];
1546
+ return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
1547
+ }
1548
+ function formatRunList(runs, options = {}) {
1549
+ if (runs.length === 0) {
1550
+ return [
1551
+ formatSection("Runs", "none recorded"),
1552
+ options.source === "server" ? pc.dim("No runs recorded on the selected Rig server.") : pc.dim("No runs recorded in .rig/runs."),
1553
+ "",
1554
+ ...formatNextSteps(["Start one: `rig task run --next`", "Check server: `rig server status`"])
1555
+ ].join(`
1556
+ `);
1557
+ }
1558
+ const rows = runs.map((run) => {
1559
+ const runId = stringField(run, "runId", stringField(run, "id", "(unknown-run)"));
1560
+ const status = stringField(run, "status", "unknown");
1561
+ const taskId = stringField(run, "taskId", "");
1562
+ const title = stringField(run, "title", taskId || "(untitled)");
1563
+ const runtime = stringField(run, "runtimeAdapter", "");
1564
+ return { runId, status, title, runtime };
1565
+ });
1566
+ const idWidth = Math.min(36, Math.max(6, ...rows.map((row) => row.runId.length)));
1567
+ const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
1568
+ const header = `${pc.bold(pad("RUN", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
1569
+ const body = rows.map((row) => [
1570
+ pc.bold(pad(truncate(row.runId, idWidth), idWidth)),
1571
+ statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
1572
+ `${row.title}${row.runtime ? pc.dim(` ${row.runtime}`) : ""}`
1573
+ ].join(" "));
1574
+ return [formatSection("Runs", options.source === "server" ? "selected server" : "local state"), header, ...body, "", ...formatNextSteps(["Follow live: `rig run attach <run-id> --follow`", "Details: `rig run show <run-id>`"])].join(`
1575
+ `);
1576
+ }
1577
+ function formatRunCard(run, options = {}) {
1578
+ const raw = rawObject(run);
1579
+ const merged = { ...raw, ...run };
1580
+ const runId = runIdOf(merged);
1581
+ const status = firstString(merged, ["status"], "unknown");
1582
+ const taskId = taskIdOf(merged);
1583
+ const title = runTitleOf(merged);
1584
+ const runtime = firstString(merged, ["runtimeAdapter", "runtime", "adapter"]);
1585
+ const mode = firstString(merged, ["runtimeMode", "mode"]);
1586
+ const interaction = firstString(merged, ["interactionMode"]);
1587
+ const created = compactDate(firstString(merged, ["createdAt"]));
1588
+ const started = compactDate(firstString(merged, ["startedAt"]));
1589
+ const updated = compactDate(firstString(merged, ["updatedAt"]));
1590
+ const completed = compactDate(firstString(merged, ["completedAt", "finishedAt"]));
1591
+ const worktree = firstString(merged, ["worktreePath", "cwd", "projectRoot"]);
1592
+ const piSession = merged.piSession && typeof merged.piSession === "object" && !Array.isArray(merged.piSession) ? firstString(merged.piSession, ["sessionId", "id"]) : "";
1593
+ const timeline = Array.isArray(merged.timeline) ? merged.timeline.length : null;
1594
+ const approvals = Array.isArray(merged.approvals) ? merged.approvals.length : null;
1595
+ const inputs = Array.isArray(merged.userInputs) ? merged.userInputs.length : null;
1596
+ const rows = [
1597
+ ["run", pc.bold(runId)],
1598
+ ["status", formatStatusPill(status)],
1599
+ ["task", taskId],
1600
+ ["title", title],
1601
+ ["runtime", [runtime, mode, interaction].filter(Boolean).join(" \xB7 ")],
1602
+ ["created", created],
1603
+ ["started", started],
1604
+ ["updated", updated],
1605
+ ["completed", completed],
1606
+ ["worktree", worktree],
1607
+ ["pi", piSession],
1608
+ ["timeline", timeline],
1609
+ ["approvals", approvals],
1610
+ ["inputs", inputs]
1611
+ ];
1612
+ return [
1613
+ formatSuccessCard(options.title ?? "Run details", rows),
1614
+ "",
1615
+ ...formatNextSteps([`Follow live: \`rig run attach ${runId} --follow\``, `Raw payload: \`rig run show ${runId} --raw\``])
1616
+ ].join(`
1617
+ `);
1618
+ }
1619
+ function formatRunStatus(summary, options = {}) {
1620
+ const activeRuns = summary.activeRuns ?? [];
1621
+ const recentRuns = summary.recentRuns ?? [];
1622
+ const lines = [formatSection("Run status", options.source === "server" ? "selected server" : "local state")];
1623
+ lines.push("", pc.bold(`Active runs (${activeRuns.length})`));
1624
+ if (activeRuns.length === 0) {
1625
+ lines.push(pc.dim("No active runs."));
1626
+ } else {
1627
+ for (const run of activeRuns) {
1628
+ lines.push(formatRunSummaryLine(run));
1629
+ }
1630
+ }
1631
+ lines.push("", pc.bold(`Recent runs (${recentRuns.length})`));
1632
+ if (recentRuns.length === 0) {
1633
+ lines.push(pc.dim("No recent terminal runs."));
1634
+ } else {
1635
+ for (const run of recentRuns.slice(0, 10)) {
1636
+ lines.push(formatRunSummaryLine(run));
1637
+ }
1638
+ }
1639
+ lines.push("", ...formatNextSteps(["Start work: `rig task run --next`", "Attach: `rig run attach <run-id> --follow`", "Details: `rig run show <run-id>`"]));
1640
+ return lines.join(`
1641
+ `);
1642
+ }
1643
+ function formatRunSummaryLine(run) {
1644
+ const record = run;
1645
+ const runId = runIdOf(record);
1646
+ const status = firstString(record, ["status"], "unknown");
1647
+ const taskId = taskIdOf(record);
1648
+ const title = runTitleOf(record);
1649
+ const runtime = firstString(record, ["runtimeAdapter", "runtime", "adapter"]);
1650
+ const descriptor = [taskId, title].filter(Boolean).join(" \xB7 ");
1651
+ return `${pc.dim("\u2502")} ${pc.bold(runId)} ${formatStatusPill(status)} ${descriptor}${runtime ? pc.dim(` ${runtime}`) : ""}`;
1652
+ }
1653
+
409
1654
  // packages/cli/src/commands/run.ts
410
1655
  function normalizeRemoteRunDetails(payload) {
411
1656
  const run = payload.run;
@@ -418,6 +1663,25 @@ function normalizeRemoteRunDetails(payload) {
418
1663
  ...Array.isArray(payload.userInputs) ? { userInputs: payload.userInputs } : {}
419
1664
  };
420
1665
  }
1666
+ var REMOTE_TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged"]);
1667
+ function isRemoteConnectionSelected(projectRoot) {
1668
+ return resolveSelectedConnection(projectRoot)?.connection.kind === "remote";
1669
+ }
1670
+ async function listRunsForSelectedConnection(context, options = {}) {
1671
+ if (isRemoteConnectionSelected(context.projectRoot)) {
1672
+ return { runs: await listRunsViaServer(context, options), source: "server" };
1673
+ }
1674
+ return { runs: listAuthorityRuns(context.projectRoot), source: "local" };
1675
+ }
1676
+ function runStringField(run, key, fallback = "") {
1677
+ const value = run[key];
1678
+ return typeof value === "string" && value.trim() ? value : fallback;
1679
+ }
1680
+ function buildServerRunStatus(runs) {
1681
+ const activeRuns = runs.filter((run) => !REMOTE_TERMINAL_RUN_STATUSES.has(runStringField(run, "status").toLowerCase()));
1682
+ const recentRuns = runs.filter((run) => REMOTE_TERMINAL_RUN_STATUSES.has(runStringField(run, "status").toLowerCase()));
1683
+ return { activeRuns, recentRuns, runs };
1684
+ }
421
1685
  function shouldPromptForEpicSelection(context, command, promptEpic, noEpicPrompt) {
422
1686
  if (noEpicPrompt) {
423
1687
  return false;
@@ -479,21 +1743,15 @@ async function promptForEpicSelection(projectRoot, command) {
479
1743
  }
480
1744
  async function executeRun(context, args) {
481
1745
  const [command = "status", ...rest] = args;
482
- const runtimeContext = loadRuntimeContextFromEnv2() ?? undefined;
1746
+ const runtimeContext = loadRuntimeContextFromEnv() ?? undefined;
483
1747
  switch (command) {
484
1748
  case "list": {
485
- requireNoExtraArgs(rest, "bun run rig run list");
486
- const runs = listAuthorityRuns(context.projectRoot);
1749
+ requireNoExtraArgs(rest, "rig run list");
1750
+ const { runs, source } = await listRunsForSelectedConnection(context, { limit: 100 });
487
1751
  if (context.outputMode === "text") {
488
- if (runs.length === 0) {
489
- console.log("No runs recorded in .rig/runs.");
490
- } else {
491
- for (const run of runs) {
492
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.title}`);
493
- }
494
- }
1752
+ printFormattedOutput(formatRunList(runs, { source }));
495
1753
  }
496
- return { ok: true, group: "run", command, details: { runs } };
1754
+ return { ok: true, group: "run", command, details: { runs, source } };
497
1755
  }
498
1756
  case "delete": {
499
1757
  let pending = rest;
@@ -501,7 +1759,7 @@ async function executeRun(context, args) {
501
1759
  pending = run.rest;
502
1760
  const purgeArtifacts = takeFlag(pending, "--purge-artifacts");
503
1761
  pending = purgeArtifacts.rest;
504
- requireNoExtraArgs(pending, "bun run rig run delete --run <id> [--purge-artifacts]");
1762
+ requireNoExtraArgs(pending, "rig run delete --run <id> [--purge-artifacts]");
505
1763
  if (!run.value) {
506
1764
  throw new CliError2("run delete requires --run <id>.");
507
1765
  }
@@ -531,7 +1789,7 @@ async function executeRun(context, args) {
531
1789
  pending = keepRuntimes.rest;
532
1790
  const keepQueue = takeFlag(pending, "--keep-queue");
533
1791
  pending = keepQueue.rest;
534
- requireNoExtraArgs(pending, "bun run rig run cleanup --all [--keep-artifacts] [--keep-runtimes] [--keep-queue]");
1792
+ requireNoExtraArgs(pending, "rig run cleanup --all [--keep-artifacts] [--keep-runtimes] [--keep-queue]");
535
1793
  if (!all.value) {
536
1794
  throw new CliError2("run cleanup currently requires --all.");
537
1795
  }
@@ -550,20 +1808,25 @@ async function executeRun(context, args) {
550
1808
  }
551
1809
  case "show": {
552
1810
  let pending = rest;
1811
+ const rawResult = takeFlag(pending, "--raw");
1812
+ pending = rawResult.rest;
553
1813
  const run = takeOption(pending, "--run");
554
1814
  pending = run.rest;
555
- requireNoExtraArgs(pending, "bun run rig run show --run <id>");
556
- if (!run.value) {
557
- throw new CliError2("run show requires --run <id>.");
1815
+ const positionalRunId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? pending[0] : undefined;
1816
+ const extra = positionalRunId ? pending.slice(1) : pending;
1817
+ requireNoExtraArgs(extra, "rig run show <id>|--run <id> [--raw]");
1818
+ const runId = run.value ?? positionalRunId;
1819
+ if (!runId) {
1820
+ throw new CliError2("run show requires a run id.");
558
1821
  }
559
- const record = readAuthorityRun(context.projectRoot, run.value) ?? normalizeRemoteRunDetails(await getRunDetailsViaServer(context, run.value).catch(() => ({})));
1822
+ const record = readAuthorityRun(context.projectRoot, runId) ?? normalizeRemoteRunDetails(await getRunDetailsViaServer(context, runId).catch(() => ({})));
560
1823
  if (!record) {
561
- throw new CliError2(`Run not found: ${run.value}`, 2);
1824
+ throw new CliError2(`Run not found: ${runId}`, 2);
562
1825
  }
563
1826
  if (context.outputMode === "text") {
564
- console.log(JSON.stringify(record, null, 2));
1827
+ printFormattedOutput(rawResult.value ? JSON.stringify(record, null, 2) : formatRunCard(record));
565
1828
  }
566
- return { ok: true, group: "run", command, details: record };
1829
+ return { ok: true, group: "run", command, details: { ...record, rawOutput: rawResult.value } };
567
1830
  }
568
1831
  case "timeline": {
569
1832
  let pending = rest;
@@ -571,38 +1834,28 @@ async function executeRun(context, args) {
571
1834
  pending = run.rest;
572
1835
  const follow = takeFlag(pending, "--follow");
573
1836
  pending = follow.rest;
574
- requireNoExtraArgs(pending, "bun run rig run timeline --run <id> [--follow]");
1837
+ requireNoExtraArgs(pending, "rig run timeline --run <id> [--follow]");
575
1838
  if (!run.value) {
576
1839
  throw new CliError2("run timeline requires --run <id>.");
577
1840
  }
578
- const timelinePath = resolve3(resolveAuthorityRunDir(context.projectRoot, run.value), "timeline.jsonl");
579
- const printEvents = () => {
580
- const events2 = readJsonlFile(timelinePath);
581
- if (context.outputMode === "text") {
582
- for (const event of events2) {
583
- console.log(JSON.stringify(event));
584
- }
585
- }
586
- return events2;
587
- };
588
- const events = printEvents();
1841
+ const renderer = createPiRunStreamRenderer();
1842
+ let cursor = null;
1843
+ const page = await getRunTimelineViaServer(context, run.value, { limit: 500 });
1844
+ const events = Array.isArray(page.entries) ? page.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1845
+ cursor = typeof page.nextCursor === "string" ? page.nextCursor : null;
1846
+ if (context.outputMode === "text") {
1847
+ renderer.renderTimeline(events);
1848
+ }
589
1849
  if (follow.value && context.outputMode === "text") {
590
- let lastLength = existsSync3(timelinePath) ? readFileSync3(timelinePath, "utf8").length : 0;
591
1850
  while (true) {
592
1851
  await Bun.sleep(1000);
593
- if (!existsSync3(timelinePath))
594
- continue;
595
- const next = readFileSync3(timelinePath, "utf8");
596
- if (next.length <= lastLength)
597
- continue;
598
- const delta = next.slice(lastLength);
599
- lastLength = next.length;
600
- for (const line of delta.split(/\r?\n/).map((entry) => entry.trim()).filter(Boolean)) {
601
- console.log(line);
602
- }
1852
+ const nextPage = await getRunTimelineViaServer(context, run.value, { limit: 500, ...cursor ? { cursor } : {} });
1853
+ const nextEvents = Array.isArray(nextPage.entries) ? nextPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1854
+ cursor = typeof nextPage.nextCursor === "string" ? nextPage.nextCursor : cursor;
1855
+ renderer.renderTimeline(nextEvents);
603
1856
  }
604
1857
  }
605
- return { ok: true, group: "run", command, details: { runId: run.value, events } };
1858
+ return { ok: true, group: "run", command, details: { runId: run.value, events, cursor } };
606
1859
  }
607
1860
  case "attach": {
608
1861
  let pending = rest;
@@ -618,41 +1871,38 @@ async function executeRun(context, args) {
618
1871
  pending = pollMs.rest;
619
1872
  const positionalRunId = pending.length > 0 ? pending[0] : undefined;
620
1873
  const extra = positionalRunId ? pending.slice(1) : pending;
621
- requireNoExtraArgs(extra, "bun run rig run attach <run-id>|--run <run-id> [--message <text>] [--once|--follow] [--poll-ms <ms>]");
1874
+ requireNoExtraArgs(extra, "rig run attach <run-id>|--run <run-id> [--message <text>] [--once|--follow] [--poll-ms <ms>]");
622
1875
  const runId = runOption.value ?? positionalRunId;
623
1876
  if (!runId) {
624
1877
  throw new CliError2("run attach requires a run id.", 2);
625
1878
  }
1879
+ let steered = false;
1880
+ if (messageOption.value?.trim()) {
1881
+ await steerRunViaServer(context, runId, messageOption.value.trim());
1882
+ steered = true;
1883
+ }
626
1884
  const attached = await attachRunOperatorView(context, {
627
1885
  runId,
628
- message: messageOption.value ?? null,
1886
+ message: null,
629
1887
  once: once.value,
630
1888
  follow: follow.value,
631
1889
  pollMs: parsePositiveInt(pollMs.value, "--poll-ms", 2000)
632
1890
  });
633
- return { ok: true, group: "run", command, details: attached };
1891
+ return { ok: true, group: "run", command, details: { ...attached, steered: attached.steered || steered } };
634
1892
  }
635
1893
  case "status": {
636
- requireNoExtraArgs(rest, "bun run rig run status");
1894
+ requireNoExtraArgs(rest, "rig run status");
637
1895
  if (context.dryRun) {
638
1896
  if (context.outputMode === "text") {
639
1897
  console.log("[dry-run] rig run status");
640
1898
  }
641
1899
  return { ok: true, group: "run", command };
642
1900
  }
643
- const summary = runStatus(context.projectRoot, runtimeContext);
1901
+ const summary = isRemoteConnectionSelected(context.projectRoot) ? buildServerRunStatus(await listRunsViaServer(context, { limit: 100 })) : runStatus(context.projectRoot, runtimeContext);
1902
+ const activeRuns = Array.isArray(summary.activeRuns) ? summary.activeRuns.filter((run) => Boolean(run && typeof run === "object" && !Array.isArray(run))) : [];
1903
+ const recentRuns = Array.isArray(summary.recentRuns) ? summary.recentRuns.filter((run) => Boolean(run && typeof run === "object" && !Array.isArray(run))) : [];
644
1904
  if (context.outputMode === "text") {
645
- console.log(`Active runs: ${summary.activeRuns.length}`);
646
- for (const run of summary.activeRuns) {
647
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.taskId ?? run.title}`);
648
- }
649
- if (summary.recentRuns.length > 0) {
650
- console.log("");
651
- console.log("Recent runs:");
652
- for (const run of summary.recentRuns) {
653
- console.log(`- ${run.runId} \xB7 ${run.status} \xB7 ${run.taskId ?? run.title}`);
654
- }
655
- }
1905
+ printFormattedOutput(formatRunStatus({ activeRuns, recentRuns, runs: Array.isArray(summary.runs) ? summary.runs : [...activeRuns, ...recentRuns] }, { source: isRemoteConnectionSelected(context.projectRoot) ? "server" : "local" }));
656
1906
  }
657
1907
  return { ok: true, group: "run", command, details: summary };
658
1908
  }
@@ -676,7 +1926,7 @@ async function executeRun(context, args) {
676
1926
  pending = pollResult.rest;
677
1927
  const noServerResult = takeFlag(pending, "--no-server");
678
1928
  pending = noServerResult.rest;
679
- requireNoExtraArgs(pending, "bun run rig run start [--epic <id>] [--prompt-epic|--no-epic-prompt] [--ws-port <n>] [--server-host <host>] [--server-port <n>] [--poll-ms <n>] [--no-server]");
1929
+ requireNoExtraArgs(pending, "rig run start [--epic <id>] [--prompt-epic|--no-epic-prompt] [--ws-port <n>] [--server-host <host>] [--server-port <n>] [--poll-ms <n>] [--no-server]");
680
1930
  if (promptEpicResult.value && noEpicPromptResult.value) {
681
1931
  throw new CliError2("Cannot use --prompt-epic and --no-epic-prompt together.");
682
1932
  }
@@ -724,7 +1974,7 @@ async function executeRun(context, args) {
724
1974
  };
725
1975
  }
726
1976
  case "resume": {
727
- requireNoExtraArgs(rest, "bun run rig run resume");
1977
+ requireNoExtraArgs(rest, "rig run resume");
728
1978
  if (context.dryRun) {
729
1979
  if (context.outputMode === "text") {
730
1980
  console.log("[dry-run] rig run resume");
@@ -738,7 +1988,7 @@ async function executeRun(context, args) {
738
1988
  return { ok: true, group: "run", command, details: resumed };
739
1989
  }
740
1990
  case "restart": {
741
- requireNoExtraArgs(rest, "bun run rig run restart");
1991
+ requireNoExtraArgs(rest, "rig run restart");
742
1992
  if (context.dryRun) {
743
1993
  if (context.outputMode === "text") {
744
1994
  console.log("[dry-run] rig run restart");
@@ -751,11 +2001,38 @@ async function executeRun(context, args) {
751
2001
  }
752
2002
  return { ok: true, group: "run", command, details: restarted };
753
2003
  }
2004
+ case "steer": {
2005
+ const runOption = takeOption(rest, "--run");
2006
+ const messageOption = takeOption(runOption.rest, "--message");
2007
+ const shortMessageOption = takeOption(messageOption.rest, "-m");
2008
+ const positionalRunId = shortMessageOption.rest.length > 0 ? shortMessageOption.rest[0] : undefined;
2009
+ const extra = positionalRunId ? shortMessageOption.rest.slice(1) : shortMessageOption.rest;
2010
+ requireNoExtraArgs(extra, "rig run steer [<run-id>|--run <id>] --message <text>");
2011
+ const runId = runOption.value ?? positionalRunId;
2012
+ const message = messageOption.value ?? shortMessageOption.value;
2013
+ if (!runId) {
2014
+ throw new CliError2("run steer requires a run id (positional or --run <id>).", 2);
2015
+ }
2016
+ if (!message?.trim()) {
2017
+ throw new CliError2("run steer requires --message <text>.", 2);
2018
+ }
2019
+ if (context.dryRun) {
2020
+ if (context.outputMode === "text") {
2021
+ console.log(`[dry-run] rig run steer ${runId} --message ${JSON.stringify(message)}`);
2022
+ }
2023
+ return { ok: true, group: "run", command, details: { runId, dryRun: true } };
2024
+ }
2025
+ await steerRunViaServer(context, runId, message.trim());
2026
+ if (context.outputMode === "text") {
2027
+ console.log(`Steering message queued for ${runId}.`);
2028
+ }
2029
+ return { ok: true, group: "run", command, details: { runId, queued: true } };
2030
+ }
754
2031
  case "stop": {
755
2032
  const runOption = takeOption(rest, "--run");
756
2033
  const positionalRunId = runOption.rest.length > 0 ? runOption.rest[0] : undefined;
757
2034
  const extra = positionalRunId ? runOption.rest.slice(1) : runOption.rest;
758
- requireNoExtraArgs(extra, "bun run rig run stop [<run-id>|--run <id>]");
2035
+ requireNoExtraArgs(extra, "rig run stop [<run-id>|--run <id>]");
759
2036
  const runId = runOption.value ?? positionalRunId;
760
2037
  if (context.dryRun) {
761
2038
  return {