@h-rig/cli 0.0.6-alpha.7 → 0.0.6-alpha.70

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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/rig.js +4507 -1506
  3. package/dist/src/commands/_async-ui.js +152 -0
  4. package/dist/src/commands/_authority-runs.js +2 -3
  5. package/dist/src/commands/_cli-format.js +369 -0
  6. package/dist/src/commands/_connection-state.js +30 -11
  7. package/dist/src/commands/_doctor-checks.js +177 -43
  8. package/dist/src/commands/_help-catalog.js +485 -0
  9. package/dist/src/commands/_json-output.js +56 -0
  10. package/dist/src/commands/_operator-surface.js +220 -0
  11. package/dist/src/commands/_operator-view.js +595 -72
  12. package/dist/src/commands/_parsers.js +18 -11
  13. package/dist/src/commands/_pi-frontend.js +411 -0
  14. package/dist/src/commands/_pi-install.js +4 -3
  15. package/dist/src/commands/_policy.js +12 -5
  16. package/dist/src/commands/_preflight.js +187 -127
  17. package/dist/src/commands/_run-driver-helpers.js +75 -22
  18. package/dist/src/commands/_run-replay.js +142 -0
  19. package/dist/src/commands/_server-client.js +343 -60
  20. package/dist/src/commands/_snapshot-upload.js +160 -38
  21. package/dist/src/commands/_spinner.js +65 -0
  22. package/dist/src/commands/_task-picker.js +44 -16
  23. package/dist/src/commands/agent.js +39 -20
  24. package/dist/src/commands/browser.js +28 -21
  25. package/dist/src/commands/connect.js +146 -33
  26. package/dist/src/commands/dist.js +19 -12
  27. package/dist/src/commands/doctor.js +304 -44
  28. package/dist/src/commands/github.js +301 -52
  29. package/dist/src/commands/inbox.js +679 -72
  30. package/dist/src/commands/init.js +622 -118
  31. package/dist/src/commands/inspect.js +515 -32
  32. package/dist/src/commands/inspector.js +20 -13
  33. package/dist/src/commands/pi.js +177 -0
  34. package/dist/src/commands/plugin.js +95 -27
  35. package/dist/src/commands/profile-and-review.js +26 -19
  36. package/dist/src/commands/queue.js +32 -12
  37. package/dist/src/commands/remote.js +43 -36
  38. package/dist/src/commands/repo-git-harness.js +22 -15
  39. package/dist/src/commands/run.js +1162 -158
  40. package/dist/src/commands/server.js +373 -56
  41. package/dist/src/commands/setup.js +316 -62
  42. package/dist/src/commands/stats.js +1030 -0
  43. package/dist/src/commands/task-report-bug.js +29 -22
  44. package/dist/src/commands/task-run-driver.js +862 -129
  45. package/dist/src/commands/task.js +1423 -311
  46. package/dist/src/commands/test.js +15 -8
  47. package/dist/src/commands/workspace.js +18 -11
  48. package/dist/src/commands.js +4446 -1499
  49. package/dist/src/index.js +4502 -1504
  50. package/dist/src/launcher.js +77 -13
  51. package/dist/src/report-bug.js +3 -3
  52. package/dist/src/runner.js +16 -22
  53. package/package.json +10 -5
@@ -1,20 +1,23 @@
1
1
  // @bun
2
- // packages/cli/src/commands/_operator-view.ts
3
- import { createInterface } from "readline";
4
-
5
2
  // packages/cli/src/commands/_server-client.ts
6
- import { spawnSync } from "child_process";
7
3
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
8
4
  import { resolve as resolve2 } from "path";
9
5
 
10
6
  // packages/cli/src/runner.ts
11
7
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
12
- import { CliError } from "@rig/runtime/control-plane/errors";
8
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
13
9
  import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
14
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
15
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
16
10
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
17
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
11
+
12
+ class CliError extends RuntimeCliError {
13
+ hint;
14
+ constructor(message, exitCode = 1, options = {}) {
15
+ super(message, exitCode);
16
+ if (options.hint?.trim()) {
17
+ this.hint = options.hint.trim();
18
+ }
19
+ }
20
+ }
18
21
 
19
22
  // packages/cli/src/commands/_server-client.ts
20
23
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
@@ -41,9 +44,14 @@ function readJsonFile(path) {
41
44
  try {
42
45
  return JSON.parse(readFileSync(path, "utf8"));
43
46
  } catch (error) {
44
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
47
+ throw new CliError(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1, { hint: "Fix or delete that file, then re-select a server with `rig server use <alias|local>`." });
45
48
  }
46
49
  }
50
+ function writeJsonFile(path, value) {
51
+ mkdirSync(dirname(path), { recursive: true });
52
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
53
+ `, "utf8");
54
+ }
47
55
  function normalizeConnection(value) {
48
56
  if (!value || typeof value !== "object" || Array.isArray(value))
49
57
  return null;
@@ -84,25 +92,44 @@ function readRepoConnection(projectRoot) {
84
92
  return {
85
93
  selected,
86
94
  project: typeof record.project === "string" ? record.project : undefined,
87
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
95
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
96
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
88
97
  };
89
98
  }
99
+ function writeRepoConnection(projectRoot, state) {
100
+ writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
101
+ }
90
102
  function resolveSelectedConnection(projectRoot, options = {}) {
91
103
  const repo = readRepoConnection(projectRoot);
92
104
  if (!repo)
93
105
  return null;
94
106
  if (repo.selected === "local")
95
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
107
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
96
108
  const global = readGlobalConnections(options);
97
109
  const connection = global.connections[repo.selected];
98
110
  if (!connection) {
99
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
111
+ throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
100
112
  }
101
- return { alias: repo.selected, connection };
113
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
114
+ }
115
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
116
+ const repo = readRepoConnection(projectRoot);
117
+ if (!repo)
118
+ return;
119
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
102
120
  }
103
121
 
104
122
  // packages/cli/src/commands/_server-client.ts
105
- var cachedGitHubBearerToken;
123
+ var scopedGitHubBearerTokens = new Map;
124
+ var serverPhaseListener = null;
125
+ function setServerPhaseListener(listener) {
126
+ const previous = serverPhaseListener;
127
+ serverPhaseListener = listener;
128
+ return previous;
129
+ }
130
+ function reportServerPhase(label) {
131
+ serverPhaseListener?.(label);
132
+ }
106
133
  function cleanToken(value) {
107
134
  const trimmed = value?.trim();
108
135
  return trimmed ? trimmed : null;
@@ -119,49 +146,80 @@ function readPrivateRemoteSessionToken(projectRoot) {
119
146
  }
120
147
  }
121
148
  function readGitHubBearerTokenForRemote(projectRoot) {
122
- if (cachedGitHubBearerToken !== undefined)
123
- return cachedGitHubBearerToken;
149
+ const scopedKey = resolve2(projectRoot);
150
+ if (scopedGitHubBearerTokens.has(scopedKey))
151
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
124
152
  const privateSession = readPrivateRemoteSessionToken(projectRoot);
125
- if (privateSession) {
126
- cachedGitHubBearerToken = privateSession;
127
- return cachedGitHubBearerToken;
128
- }
129
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
130
- if (envToken) {
131
- cachedGitHubBearerToken = envToken;
132
- return cachedGitHubBearerToken;
153
+ if (privateSession)
154
+ return privateSession;
155
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
156
+ }
157
+ function readStoredGitHubAuthToken(projectRoot) {
158
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
159
+ if (!existsSync2(path))
160
+ return null;
161
+ try {
162
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
163
+ return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
164
+ } catch {
165
+ return null;
133
166
  }
134
- const result = spawnSync("gh", ["auth", "token"], {
135
- encoding: "utf8",
136
- timeout: 5000,
137
- stdio: ["ignore", "pipe", "ignore"]
138
- });
139
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
140
- return cachedGitHubBearerToken;
167
+ }
168
+ function readLocalConnectionFallbackToken(projectRoot) {
169
+ return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
141
170
  }
142
171
  async function ensureServerForCli(projectRoot) {
143
172
  try {
144
173
  const selected = resolveSelectedConnection(projectRoot);
145
174
  if (selected?.connection.kind === "remote") {
175
+ reportServerPhase(`Connecting to ${selected.alias}\u2026`);
176
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
177
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
146
178
  return {
147
179
  baseUrl: selected.connection.baseUrl,
148
- authToken: readGitHubBearerTokenForRemote(projectRoot),
149
- connectionKind: "remote"
180
+ authToken,
181
+ connectionKind: "remote",
182
+ serverProjectRoot
150
183
  };
151
184
  }
185
+ reportServerPhase("Starting local Rig server\u2026");
152
186
  const connection = await ensureLocalRigServerConnection(projectRoot);
153
187
  return {
154
188
  baseUrl: connection.baseUrl,
155
- authToken: connection.authToken,
156
- connectionKind: "local"
189
+ authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
190
+ connectionKind: "local",
191
+ serverProjectRoot: resolve2(projectRoot)
157
192
  };
158
193
  } catch (error) {
159
194
  if (error instanceof Error) {
160
- throw new CliError2(error.message, 1);
195
+ throw new CliError(error.message, 1);
161
196
  }
162
197
  throw error;
163
198
  }
164
199
  }
200
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
201
+ const repo = readRepoConnection(projectRoot);
202
+ const slug = repo?.project?.trim();
203
+ if (!slug)
204
+ return null;
205
+ try {
206
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
207
+ headers: mergeHeaders(undefined, authToken)
208
+ });
209
+ if (!response.ok)
210
+ return null;
211
+ const payload = await response.json();
212
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
213
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
214
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
215
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
216
+ if (path)
217
+ writeRepoServerProjectRoot(projectRoot, path);
218
+ return path;
219
+ } catch {
220
+ return null;
221
+ }
222
+ }
165
223
  function mergeHeaders(headers, authToken) {
166
224
  const merged = new Headers(headers);
167
225
  if (authToken) {
@@ -184,12 +242,65 @@ function diagnosticMessage(payload) {
184
242
  });
185
243
  return messages.length > 0 ? messages.join("; ") : null;
186
244
  }
245
+ var serverReachabilityCache = new Map;
246
+ async function probeServerReachability(baseUrl, authToken) {
247
+ try {
248
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
249
+ headers: mergeHeaders(undefined, authToken),
250
+ signal: AbortSignal.timeout(1500)
251
+ });
252
+ return response.ok;
253
+ } catch {
254
+ return false;
255
+ }
256
+ }
257
+ function cachedServerReachability(projectRoot, baseUrl, authToken) {
258
+ const key = resolve2(projectRoot);
259
+ const cached = serverReachabilityCache.get(key);
260
+ if (cached)
261
+ return cached;
262
+ const probe = probeServerReachability(baseUrl, authToken);
263
+ serverReachabilityCache.set(key, probe);
264
+ return probe;
265
+ }
266
+ function describeSelectedServer(projectRoot, server) {
267
+ try {
268
+ const selected = resolveSelectedConnection(projectRoot);
269
+ if (selected) {
270
+ return {
271
+ alias: selected.alias,
272
+ target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
273
+ };
274
+ }
275
+ } catch {}
276
+ return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
277
+ }
278
+ async function buildServerFailureContext(projectRoot, server) {
279
+ const { alias, target } = describeSelectedServer(projectRoot, server);
280
+ const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
281
+ const reachability = reachable ? "server is reachable" : "server is unreachable";
282
+ return {
283
+ contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
284
+ hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
285
+ };
286
+ }
187
287
  async function requestServerJson(context, pathname, init = {}) {
188
288
  const server = await ensureServerForCli(context.projectRoot);
189
- const response = await fetch(`${server.baseUrl}${pathname}`, {
190
- ...init,
191
- headers: mergeHeaders(init.headers, server.authToken)
192
- });
289
+ const headers = mergeHeaders(init.headers, server.authToken);
290
+ if (server.serverProjectRoot)
291
+ headers.set("x-rig-project-root", server.serverProjectRoot);
292
+ reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
293
+ let response;
294
+ try {
295
+ response = await fetch(`${server.baseUrl}${pathname}`, {
296
+ ...init,
297
+ headers
298
+ });
299
+ } catch (error) {
300
+ const failure = await buildServerFailureContext(context.projectRoot, server);
301
+ throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
302
+ ${failure.contextLine}`, 1, { hint: failure.hint });
303
+ }
193
304
  const text = await response.text();
194
305
  const payload = text.trim().length > 0 ? (() => {
195
306
  try {
@@ -201,7 +312,9 @@ async function requestServerJson(context, pathname, init = {}) {
201
312
  if (!response.ok) {
202
313
  const diagnostics = diagnosticMessage(payload);
203
314
  const detail = diagnostics ?? (text || response.statusText);
204
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
315
+ const failure = await buildServerFailureContext(context.projectRoot, server);
316
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
317
+ ${failure.contextLine}`, 1, { hint: failure.hint });
205
318
  }
206
319
  return payload;
207
320
  }
@@ -218,6 +331,26 @@ async function getRunLogsViaServer(context, runId, options = {}) {
218
331
  const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
219
332
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
220
333
  }
334
+ async function getRunTimelineViaServer(context, runId, options = {}) {
335
+ const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
336
+ if (options.limit !== undefined)
337
+ url.searchParams.set("limit", String(options.limit));
338
+ if (options.cursor)
339
+ url.searchParams.set("cursor", options.cursor);
340
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
341
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
342
+ }
343
+ var RESUMABLE_RUN_STATUSES = new Set([
344
+ "created",
345
+ "preparing",
346
+ "running",
347
+ "validating",
348
+ "reviewing",
349
+ "stopped",
350
+ "failed",
351
+ "needs-attention",
352
+ "needs_attention"
353
+ ]);
221
354
  async function stopRunViaServer(context, runId) {
222
355
  const payload = await requestServerJson(context, "/api/runs/stop", {
223
356
  method: "POST",
@@ -234,9 +367,17 @@ async function steerRunViaServer(context, runId, message) {
234
367
  });
235
368
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
236
369
  }
370
+ async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
371
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
372
+ method: "POST",
373
+ headers: { "content-type": "application/json" },
374
+ body: JSON.stringify({ text, streamingBehavior })
375
+ });
376
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
377
+ }
237
378
 
238
- // packages/cli/src/commands/_operator-view.ts
239
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
379
+ // packages/cli/src/commands/_operator-surface.ts
380
+ import { createInterface } from "readline";
240
381
  var CANONICAL_STAGES = [
241
382
  "Connect",
242
383
  "GitHub/task sync",
@@ -251,18 +392,380 @@ var CANONICAL_STAGES = [
251
392
  "Merge",
252
393
  "Complete"
253
394
  ];
395
+ function logDetail(log) {
396
+ return typeof log.detail === "string" ? log.detail.trim() : "";
397
+ }
398
+ function parseProviderProtocolLog(title, detail) {
399
+ if (title.trim().toLowerCase() !== "agent output")
400
+ return null;
401
+ if (!detail.startsWith("{") || !detail.endsWith("}"))
402
+ return null;
403
+ try {
404
+ const record = JSON.parse(detail);
405
+ if (!record || typeof record !== "object" || Array.isArray(record))
406
+ return null;
407
+ const type = record.type;
408
+ return typeof type === "string" && [
409
+ "assistant",
410
+ "message_start",
411
+ "message_update",
412
+ "message_end",
413
+ "stream_event",
414
+ "tool_result",
415
+ "tool_execution_start",
416
+ "tool_execution_update",
417
+ "tool_execution_end",
418
+ "turn_start",
419
+ "turn_end"
420
+ ].includes(type) ? record : null;
421
+ } catch {
422
+ return null;
423
+ }
424
+ }
425
+ function renderProviderProtocolLog(record) {
426
+ const type = typeof record.type === "string" ? record.type : "";
427
+ if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
428
+ const toolName = String(record.toolName ?? record.name ?? "tool");
429
+ 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";
430
+ return `[Pi tool] ${toolName} ${status}`;
431
+ }
432
+ return null;
433
+ }
434
+ function entryId(entry, fallback) {
435
+ return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
436
+ }
254
437
  function renderOperatorSnapshot(snapshot) {
255
438
  const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
256
439
  const runId = String(run.runId ?? run.id ?? "run");
257
440
  const status = String(run.status ?? "unknown");
258
441
  const logs = snapshot.logs ?? [];
442
+ const latestByStage = new Map;
443
+ for (const log of logs) {
444
+ const title = String(log.title ?? "").toLowerCase();
445
+ const stageName = String(log.stage ?? "").toLowerCase();
446
+ const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
447
+ if (stage)
448
+ latestByStage.set(stage, log);
449
+ }
259
450
  const stageLines = CANONICAL_STAGES.flatMap((stage) => {
260
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
261
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
451
+ const match = latestByStage.get(stage);
452
+ return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
262
453
  });
263
454
  return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
264
455
  `);
265
456
  }
457
+ function createPiRunStreamRenderer(output = process.stdout) {
458
+ let lastSnapshot = "";
459
+ const assistantTextById = new Map;
460
+ const seenTimeline = new Set;
461
+ const seenLogs = new Set;
462
+ const writeLine = (line) => output.write(`${line}
463
+ `);
464
+ return {
465
+ renderSnapshot(snapshot) {
466
+ const rendered = renderOperatorSnapshot(snapshot);
467
+ if (rendered && rendered !== lastSnapshot) {
468
+ writeLine(rendered);
469
+ lastSnapshot = rendered;
470
+ }
471
+ },
472
+ renderTimeline(entries) {
473
+ for (const [index, entry] of entries.entries()) {
474
+ const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
475
+ if (entry.type === "assistant_message" && typeof entry.text === "string") {
476
+ const text = entry.text;
477
+ const previousText = assistantTextById.get(id) ?? "";
478
+ if (!previousText && text.trim()) {
479
+ writeLine("[Pi assistant]");
480
+ }
481
+ if (text.startsWith(previousText)) {
482
+ const delta = text.slice(previousText.length);
483
+ if (delta)
484
+ output.write(delta);
485
+ } else if (text.trim() && text !== previousText) {
486
+ if (previousText)
487
+ writeLine(`
488
+ [Pi assistant]`);
489
+ output.write(text);
490
+ }
491
+ assistantTextById.set(id, text);
492
+ continue;
493
+ }
494
+ if (seenTimeline.has(id))
495
+ continue;
496
+ seenTimeline.add(id);
497
+ if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
498
+ writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
499
+ continue;
500
+ }
501
+ if (entry.type === "timeline_warning") {
502
+ writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
503
+ continue;
504
+ }
505
+ if (entry.type === "action") {
506
+ const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
507
+ if (text)
508
+ writeLine(`[Rig action] ${text}`);
509
+ continue;
510
+ }
511
+ if (entry.type === "user_message") {
512
+ const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
513
+ if (text)
514
+ writeLine(`[Operator] ${text}`);
515
+ continue;
516
+ }
517
+ const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
518
+ if (fallback)
519
+ writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
520
+ }
521
+ },
522
+ renderLogs(entries) {
523
+ for (const [index, entry] of entries.entries()) {
524
+ const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
525
+ if (seenLogs.has(id))
526
+ continue;
527
+ seenLogs.add(id);
528
+ const title = String(entry.title ?? "");
529
+ if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
530
+ continue;
531
+ const detail = logDetail(entry);
532
+ if (!detail)
533
+ continue;
534
+ const protocolRecord = parseProviderProtocolLog(title, detail);
535
+ if (protocolRecord) {
536
+ const protocolLine = renderProviderProtocolLog(protocolRecord);
537
+ if (protocolLine)
538
+ writeLine(protocolLine);
539
+ continue;
540
+ }
541
+ writeLine(`[${title || "Rig log"}] ${detail}`);
542
+ }
543
+ }
544
+ };
545
+ }
546
+ function createOperatorSurface(options = {}) {
547
+ const input = options.input ?? process.stdin;
548
+ const output = options.output ?? process.stdout;
549
+ const errorOutput = options.errorOutput ?? process.stderr;
550
+ const renderer = createPiRunStreamRenderer(output);
551
+ const writeLine = (line) => output.write(`${line}
552
+ `);
553
+ return {
554
+ mode: "pi-compatible-text",
555
+ ...renderer,
556
+ info: writeLine,
557
+ error: (message) => errorOutput.write(`${message}
558
+ `),
559
+ attachCommandInput(handler) {
560
+ if (options.interactive === false || !input.isTTY)
561
+ return null;
562
+ const rl = createInterface({ input, output: process.stdout, terminal: false });
563
+ rl.on("line", (line) => {
564
+ Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
565
+ });
566
+ return { close: () => rl.close() };
567
+ }
568
+ };
569
+ }
570
+
571
+ // packages/cli/src/commands/_pi-frontend.ts
572
+ import { mkdtempSync, rmSync } from "fs";
573
+ import { tmpdir } from "os";
574
+ import { join } from "path";
575
+ import { main as runPiMain } from "@earendil-works/pi-coding-agent";
576
+ import createPiRigExtension from "@rig/pi-rig";
577
+ function setTemporaryEnv(updates) {
578
+ const previous = new Map;
579
+ for (const [key, value] of Object.entries(updates)) {
580
+ previous.set(key, process.env[key]);
581
+ process.env[key] = value;
582
+ }
583
+ return () => {
584
+ for (const [key, value] of previous) {
585
+ if (value === undefined)
586
+ delete process.env[key];
587
+ else
588
+ process.env[key] = value;
589
+ }
590
+ };
591
+ }
592
+ function buildOperatorPiEnv(input) {
593
+ return {
594
+ PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
595
+ PI_SKIP_VERSION_CHECK: "1",
596
+ RIG_PI_OPERATOR_SESSION: "1",
597
+ RIG_RUN_ID: input.runId,
598
+ RIG_SERVER_URL: input.serverUrl,
599
+ ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
600
+ ...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
601
+ };
602
+ }
603
+ async function attachRunBundledPiFrontend(context, input) {
604
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
605
+ const server = await ensureServerForCli(context.projectRoot);
606
+ const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
607
+ runId: input.runId,
608
+ serverUrl: server.baseUrl,
609
+ authToken: server.authToken,
610
+ serverProjectRoot: server.serverProjectRoot,
611
+ sessionDir: tempSessionDir
612
+ }));
613
+ const piRigExtensionFactory = (pi) => {
614
+ createPiRigExtension(pi);
615
+ };
616
+ let detached = false;
617
+ try {
618
+ await runPiMain([
619
+ "--no-extensions",
620
+ "--no-skills",
621
+ "--no-prompt-templates",
622
+ "--no-context-files"
623
+ ], {
624
+ extensionFactories: [piRigExtensionFactory]
625
+ });
626
+ detached = true;
627
+ } finally {
628
+ restoreEnv();
629
+ rmSync(tempSessionDir, { recursive: true, force: true });
630
+ }
631
+ let run = { runId: input.runId, status: "unknown" };
632
+ try {
633
+ run = await getRunDetailsViaServer(context, input.runId);
634
+ } catch {}
635
+ return {
636
+ run,
637
+ logs: [],
638
+ timeline: [],
639
+ timelineCursor: null,
640
+ steered: input.steered === true,
641
+ detached,
642
+ rendered: "stock Pi operator console with the pi-rig extension"
643
+ };
644
+ }
645
+
646
+ // packages/cli/src/commands/_async-ui.ts
647
+ import pc from "picocolors";
648
+
649
+ // packages/cli/src/commands/_spinner.ts
650
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
651
+ function createTtySpinner(input) {
652
+ const output = input.output ?? process.stdout;
653
+ const isTty = output.isTTY === true;
654
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
655
+ let label = input.label;
656
+ let frame = 0;
657
+ let paused = false;
658
+ let stopped = false;
659
+ let lastPrintedLabel = "";
660
+ const render = () => {
661
+ if (stopped || paused)
662
+ return;
663
+ if (!isTty) {
664
+ if (label !== lastPrintedLabel) {
665
+ output.write(`${label}
666
+ `);
667
+ lastPrintedLabel = label;
668
+ }
669
+ return;
670
+ }
671
+ frame = (frame + 1) % frames.length;
672
+ const glyph = frames[frame] ?? frames[0] ?? "";
673
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
674
+ };
675
+ const clearLine = () => {
676
+ if (isTty)
677
+ output.write("\r\x1B[2K");
678
+ };
679
+ render();
680
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
681
+ return {
682
+ setLabel(next) {
683
+ label = next;
684
+ render();
685
+ },
686
+ pause() {
687
+ paused = true;
688
+ clearLine();
689
+ },
690
+ resume() {
691
+ if (stopped)
692
+ return;
693
+ paused = false;
694
+ render();
695
+ },
696
+ stop(finalLine) {
697
+ if (stopped)
698
+ return;
699
+ stopped = true;
700
+ if (timer)
701
+ clearInterval(timer);
702
+ clearLine();
703
+ if (finalLine)
704
+ output.write(`${finalLine}
705
+ `);
706
+ }
707
+ };
708
+ }
709
+
710
+ // packages/cli/src/commands/_async-ui.ts
711
+ var CLACK_SPINNER_FRAMES = ["\u25D2", "\u25D0", "\u25D3", "\u25D1"];
712
+ var DONE_SYMBOL = pc.green("\u25C7");
713
+ var FAIL_SYMBOL = pc.red("\u25A0");
714
+ var activeUpdate = null;
715
+ async function withSpinner(label, work, options = {}) {
716
+ if (options.outputMode === "json") {
717
+ return work(() => {});
718
+ }
719
+ if (activeUpdate) {
720
+ const outer = activeUpdate;
721
+ outer(label);
722
+ return work(outer);
723
+ }
724
+ const output = options.output ?? process.stderr;
725
+ const isTty = output.isTTY === true;
726
+ let lastLabel = label;
727
+ if (!isTty) {
728
+ output.write(`${label}
729
+ `);
730
+ const update2 = (next) => {
731
+ lastLabel = next;
732
+ };
733
+ activeUpdate = update2;
734
+ const previousListener2 = setServerPhaseListener(update2);
735
+ try {
736
+ return await work(update2);
737
+ } finally {
738
+ activeUpdate = null;
739
+ setServerPhaseListener(previousListener2);
740
+ }
741
+ }
742
+ const spinner = createTtySpinner({
743
+ label,
744
+ output,
745
+ frames: CLACK_SPINNER_FRAMES,
746
+ styleFrame: (frame) => pc.magenta(frame)
747
+ });
748
+ const update = (next) => {
749
+ lastLabel = next;
750
+ spinner.setLabel(next);
751
+ };
752
+ activeUpdate = update;
753
+ const previousListener = setServerPhaseListener(update);
754
+ try {
755
+ const result = await work(update);
756
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
757
+ return result;
758
+ } catch (error) {
759
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
760
+ throw error;
761
+ } finally {
762
+ activeUpdate = null;
763
+ setServerPhaseListener(previousListener);
764
+ }
765
+ }
766
+
767
+ // packages/cli/src/commands/_operator-view.ts
768
+ var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
266
769
  function runStatusFromPayload(payload) {
267
770
  const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
268
771
  return String(run.status ?? "unknown").toLowerCase();
@@ -284,57 +787,77 @@ async function applyOperatorCommand(context, input, deps = {}) {
284
787
  await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
285
788
  return { action: "continue", message: "Steering message queued." };
286
789
  }
287
- async function readOperatorSnapshot(context, runId) {
790
+ async function readOperatorSnapshot(context, runId, options = {}) {
288
791
  const run = await getRunDetailsViaServer(context, runId);
289
792
  const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
290
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
291
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
793
+ const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
794
+ entries: [{
795
+ id: `timeline-unavailable:${runId}`,
796
+ type: "timeline_warning",
797
+ detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
798
+ createdAt: new Date().toISOString()
799
+ }],
800
+ nextCursor: options.timelineCursor ?? null
801
+ }));
802
+ const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
803
+ const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
804
+ const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
805
+ return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
292
806
  }
293
807
  async function attachRunOperatorView(context, input) {
294
808
  let steered = false;
295
- if (input.message?.trim()) {
296
- await steerRunViaServer(context, input.runId, input.message.trim());
809
+ const attachMessage = input.message?.trim();
810
+ if (attachMessage) {
811
+ await withSpinner("Queueing steering message\u2026", () => sendRunPiPromptViaServer(context, input.runId, attachMessage, "steer").catch(() => steerRunViaServer(context, input.runId, attachMessage)), { outputMode: context.outputMode });
297
812
  steered = true;
298
813
  }
299
- let snapshot = await readOperatorSnapshot(context, input.runId);
814
+ if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
815
+ return attachRunBundledPiFrontend(context, {
816
+ runId: input.runId,
817
+ steered
818
+ });
819
+ }
820
+ const surface = createOperatorSurface({ interactive: input.interactive !== false });
821
+ let snapshot = await withSpinner(`Connecting to run ${input.runId}\u2026`, () => readOperatorSnapshot(context, input.runId), { outputMode: context.outputMode });
300
822
  if (context.outputMode === "text") {
301
- console.log(snapshot.rendered);
823
+ surface.renderSnapshot(snapshot);
824
+ surface.renderTimeline(snapshot.timeline);
825
+ surface.renderLogs(snapshot.logs);
302
826
  if (steered)
303
- console.log("Steering message queued.");
827
+ surface.info("Message submitted to worker Pi.");
304
828
  }
305
829
  let detached = false;
306
- let rl = null;
830
+ let commandInput = null;
307
831
  if (input.follow && !input.once && context.outputMode === "text") {
308
832
  if (input.interactive !== false && process.stdin.isTTY) {
309
- console.log("Controls: /user <message>, /stop, /detach");
310
- rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
311
- rl.on("line", (line) => {
312
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
313
- if (result.message)
314
- console.log(result.message);
315
- if (result.action === "detach" || result.action === "stopped") {
316
- detached = true;
317
- rl?.close();
318
- }
319
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
833
+ surface.info("Controls: /user <message>, /stop, /detach");
834
+ commandInput = surface.attachCommandInput(async (line) => {
835
+ const result = await applyOperatorCommand(context, { runId: input.runId, line });
836
+ if (result.message)
837
+ surface.info(result.message);
838
+ if (result.action === "detach" || result.action === "stopped") {
839
+ detached = true;
840
+ commandInput?.close();
841
+ }
320
842
  });
321
843
  }
322
- let lastRendered = snapshot.rendered;
323
844
  const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
845
+ let timelineCursor = snapshot.timelineCursor;
324
846
  while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
325
847
  await Bun.sleep(pollMs);
326
- snapshot = await readOperatorSnapshot(context, input.runId);
327
- if (snapshot.rendered !== lastRendered) {
328
- console.log(snapshot.rendered);
329
- lastRendered = snapshot.rendered;
330
- }
848
+ snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
849
+ timelineCursor = snapshot.timelineCursor;
850
+ surface.renderSnapshot(snapshot);
851
+ surface.renderTimeline(snapshot.timeline);
852
+ surface.renderLogs(snapshot.logs);
331
853
  }
332
- rl?.close();
854
+ commandInput?.close();
333
855
  }
334
856
  return { ...snapshot, steered, detached };
335
857
  }
336
858
  export {
337
859
  renderOperatorSnapshot,
860
+ createPiRunStreamRenderer,
338
861
  attachRunOperatorView,
339
862
  applyOperatorCommand
340
863
  };