@h-rig/cli 0.0.6-alpha.9 → 0.0.6-alpha.90

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 (114) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/build-rig-binaries.d.ts +2 -0
  3. package/dist/bin/rig.d.ts +2 -0
  4. package/dist/bin/rig.js +11052 -6668
  5. package/dist/src/app/board.d.ts +23 -0
  6. package/dist/src/app/board.js +1786 -0
  7. package/dist/src/app/drone-ui.d.ts +37 -0
  8. package/dist/src/app/drone-ui.js +294 -0
  9. package/dist/src/app/theme.d.ts +47 -0
  10. package/dist/src/app/theme.js +150 -0
  11. package/dist/src/commands/_async-ui.d.ts +13 -0
  12. package/dist/src/commands/_async-ui.js +223 -0
  13. package/dist/src/commands/_authority-runs.d.ts +22 -0
  14. package/dist/src/commands/_authority-runs.js +2 -3
  15. package/dist/src/commands/_cli-format.d.ts +49 -0
  16. package/dist/src/commands/_cli-format.js +447 -0
  17. package/dist/src/commands/_connection-state.d.ts +44 -0
  18. package/dist/src/commands/_connection-state.js +30 -11
  19. package/dist/src/commands/_doctor-checks.d.ts +52 -0
  20. package/dist/src/commands/_doctor-checks.js +180 -44
  21. package/dist/src/commands/_help-catalog.d.ts +51 -0
  22. package/dist/src/commands/_help-catalog.js +442 -0
  23. package/dist/src/commands/_json-output.d.ts +11 -0
  24. package/dist/src/commands/_json-output.js +56 -0
  25. package/dist/src/commands/_operator-surface.d.ts +34 -0
  26. package/dist/src/commands/_operator-surface.js +220 -0
  27. package/dist/src/commands/_operator-view.d.ts +30 -0
  28. package/dist/src/commands/_operator-view.js +803 -73
  29. package/dist/src/commands/_parsers.d.ts +15 -0
  30. package/dist/src/commands/_parsers.js +18 -11
  31. package/dist/src/commands/_paths.d.ts +11 -0
  32. package/dist/src/commands/_pi-frontend.d.ts +27 -0
  33. package/dist/src/commands/_pi-frontend.js +742 -0
  34. package/dist/src/commands/_pi-install.d.ts +42 -0
  35. package/dist/src/commands/_pi-install.js +5 -4
  36. package/dist/src/commands/_policy.d.ts +8 -0
  37. package/dist/src/commands/_policy.js +12 -5
  38. package/dist/src/commands/_preflight.d.ts +22 -0
  39. package/dist/src/commands/_preflight.js +190 -128
  40. package/dist/src/commands/_probes.d.ts +1 -0
  41. package/dist/src/commands/_run-driver-helpers.d.ts +99 -0
  42. package/dist/src/commands/_run-driver-helpers.js +75 -22
  43. package/dist/src/commands/_run-replay.d.ts +24 -0
  44. package/dist/src/commands/_run-replay.js +142 -0
  45. package/dist/src/commands/_server-client.d.ts +186 -0
  46. package/dist/src/commands/_server-client.js +360 -61
  47. package/dist/src/commands/_snapshot-upload.d.ts +39 -0
  48. package/dist/src/commands/_snapshot-upload.js +163 -39
  49. package/dist/src/commands/_spinner.d.ts +25 -0
  50. package/dist/src/commands/_spinner.js +65 -0
  51. package/dist/src/commands/_task-picker.d.ts +9 -0
  52. package/dist/src/commands/_task-picker.js +172 -19
  53. package/dist/src/commands/agent.d.ts +3 -0
  54. package/dist/src/commands/agent.js +39 -20
  55. package/dist/src/commands/browser.d.ts +65 -0
  56. package/dist/src/commands/browser.js +334 -51
  57. package/dist/src/commands/connect.d.ts +7 -0
  58. package/dist/src/commands/connect.js +272 -33
  59. package/dist/src/commands/dist.d.ts +28 -0
  60. package/dist/src/commands/dist.js +19 -12
  61. package/dist/src/commands/doctor.d.ts +3 -0
  62. package/dist/src/commands/doctor.js +378 -45
  63. package/dist/src/commands/github.d.ts +3 -0
  64. package/dist/src/commands/github.js +375 -53
  65. package/dist/src/commands/inbox.d.ts +30 -0
  66. package/dist/src/commands/inbox.js +760 -70
  67. package/dist/src/commands/init.d.ts +74 -0
  68. package/dist/src/commands/init.js +963 -119
  69. package/dist/src/commands/inspect.d.ts +3 -0
  70. package/dist/src/commands/inspect.js +588 -32
  71. package/dist/src/commands/inspector.d.ts +3 -0
  72. package/dist/src/commands/inspector.js +20 -13
  73. package/dist/src/commands/pi.d.ts +3 -0
  74. package/dist/src/commands/pi.js +177 -0
  75. package/dist/src/commands/plugin.d.ts +16 -0
  76. package/dist/src/commands/plugin.js +95 -27
  77. package/dist/src/commands/profile-and-review.d.ts +4 -0
  78. package/dist/src/commands/profile-and-review.js +26 -19
  79. package/dist/src/commands/queue.d.ts +3 -0
  80. package/dist/src/commands/queue.js +32 -12
  81. package/dist/src/commands/remote.d.ts +3 -0
  82. package/dist/src/commands/remote.js +43 -36
  83. package/dist/src/commands/repo-git-harness.d.ts +5 -0
  84. package/dist/src/commands/repo-git-harness.js +22 -15
  85. package/dist/src/commands/run.d.ts +3 -0
  86. package/dist/src/commands/run.js +1379 -159
  87. package/dist/src/commands/server.d.ts +7 -0
  88. package/dist/src/commands/server.js +502 -57
  89. package/dist/src/commands/setup.d.ts +16 -0
  90. package/dist/src/commands/setup.js +390 -63
  91. package/dist/src/commands/stats.d.ts +12 -0
  92. package/dist/src/commands/stats.js +1051 -0
  93. package/dist/src/commands/task-report-bug.d.ts +19 -0
  94. package/dist/src/commands/task-report-bug.js +260 -62
  95. package/dist/src/commands/task-run-driver.d.ts +132 -0
  96. package/dist/src/commands/task-run-driver.js +886 -130
  97. package/dist/src/commands/task.d.ts +14 -0
  98. package/dist/src/commands/task.js +1644 -314
  99. package/dist/src/commands/test.d.ts +3 -0
  100. package/dist/src/commands/test.js +15 -8
  101. package/dist/src/commands/workspace.d.ts +3 -0
  102. package/dist/src/commands/workspace.js +18 -11
  103. package/dist/src/commands.d.ts +29 -0
  104. package/dist/src/commands.js +10967 -6637
  105. package/dist/src/index.d.ts +4 -0
  106. package/dist/src/index.js +10168 -5787
  107. package/dist/src/launcher.d.ts +61 -0
  108. package/dist/src/launcher.js +77 -13
  109. package/dist/src/report-bug.d.ts +44 -0
  110. package/dist/src/report-bug.js +3 -3
  111. package/dist/src/runner.d.ts +47 -0
  112. package/dist/src/runner.js +16 -22
  113. package/dist/src/withMutedConsole.d.ts +2 -0
  114. package/package.json +13 -6
@@ -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 {
@@ -200,8 +311,12 @@ async function requestServerJson(context, pathname, init = {}) {
200
311
  })() : null;
201
312
  if (!response.ok) {
202
313
  const diagnostics = diagnosticMessage(payload);
203
- const detail = diagnostics ?? (text || response.statusText);
204
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
314
+ const rawDetail = diagnostics ?? (text || response.statusText);
315
+ const detail = diagnostics ? rawDetail : rawDetail.split(`
316
+ `).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
317
+ const failure = await buildServerFailureContext(context.projectRoot, server);
318
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
319
+ ${failure.contextLine}`, 1, { hint: failure.hint });
205
320
  }
206
321
  return payload;
207
322
  }
@@ -218,6 +333,26 @@ async function getRunLogsViaServer(context, runId, options = {}) {
218
333
  const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
219
334
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
220
335
  }
336
+ async function getRunTimelineViaServer(context, runId, options = {}) {
337
+ const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
338
+ if (options.limit !== undefined)
339
+ url.searchParams.set("limit", String(options.limit));
340
+ if (options.cursor)
341
+ url.searchParams.set("cursor", options.cursor);
342
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
343
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
344
+ }
345
+ var RESUMABLE_RUN_STATUSES = new Set([
346
+ "created",
347
+ "preparing",
348
+ "running",
349
+ "validating",
350
+ "reviewing",
351
+ "stopped",
352
+ "failed",
353
+ "needs-attention",
354
+ "needs_attention"
355
+ ]);
221
356
  async function stopRunViaServer(context, runId) {
222
357
  const payload = await requestServerJson(context, "/api/runs/stop", {
223
358
  method: "POST",
@@ -234,9 +369,17 @@ async function steerRunViaServer(context, runId, message) {
234
369
  });
235
370
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
236
371
  }
372
+ async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
373
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
374
+ method: "POST",
375
+ headers: { "content-type": "application/json" },
376
+ body: JSON.stringify({ text, streamingBehavior })
377
+ });
378
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
379
+ }
237
380
 
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"]);
381
+ // packages/cli/src/commands/_operator-surface.ts
382
+ import { createInterface } from "readline";
240
383
  var CANONICAL_STAGES = [
241
384
  "Connect",
242
385
  "GitHub/task sync",
@@ -251,18 +394,585 @@ var CANONICAL_STAGES = [
251
394
  "Merge",
252
395
  "Complete"
253
396
  ];
397
+ function logDetail(log) {
398
+ return typeof log.detail === "string" ? log.detail.trim() : "";
399
+ }
400
+ function parseProviderProtocolLog(title, detail) {
401
+ if (title.trim().toLowerCase() !== "agent output")
402
+ return null;
403
+ if (!detail.startsWith("{") || !detail.endsWith("}"))
404
+ return null;
405
+ try {
406
+ const record = JSON.parse(detail);
407
+ if (!record || typeof record !== "object" || Array.isArray(record))
408
+ return null;
409
+ const type = record.type;
410
+ return typeof type === "string" && [
411
+ "assistant",
412
+ "message_start",
413
+ "message_update",
414
+ "message_end",
415
+ "stream_event",
416
+ "tool_result",
417
+ "tool_execution_start",
418
+ "tool_execution_update",
419
+ "tool_execution_end",
420
+ "turn_start",
421
+ "turn_end"
422
+ ].includes(type) ? record : null;
423
+ } catch {
424
+ return null;
425
+ }
426
+ }
427
+ function renderProviderProtocolLog(record) {
428
+ const type = typeof record.type === "string" ? record.type : "";
429
+ if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
430
+ const toolName = String(record.toolName ?? record.name ?? "tool");
431
+ 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";
432
+ return `[Pi tool] ${toolName} ${status}`;
433
+ }
434
+ return null;
435
+ }
436
+ function entryId(entry, fallback) {
437
+ return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
438
+ }
254
439
  function renderOperatorSnapshot(snapshot) {
255
440
  const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
256
441
  const runId = String(run.runId ?? run.id ?? "run");
257
442
  const status = String(run.status ?? "unknown");
258
443
  const logs = snapshot.logs ?? [];
444
+ const latestByStage = new Map;
445
+ for (const log of logs) {
446
+ const title = String(log.title ?? "").toLowerCase();
447
+ const stageName = String(log.stage ?? "").toLowerCase();
448
+ const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
449
+ if (stage)
450
+ latestByStage.set(stage, log);
451
+ }
259
452
  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)}`] : [];
453
+ const match = latestByStage.get(stage);
454
+ return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
262
455
  });
263
456
  return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
264
457
  `);
265
458
  }
459
+ function createPiRunStreamRenderer(output = process.stdout) {
460
+ let lastSnapshot = "";
461
+ const assistantTextById = new Map;
462
+ const seenTimeline = new Set;
463
+ const seenLogs = new Set;
464
+ const writeLine = (line) => output.write(`${line}
465
+ `);
466
+ return {
467
+ renderSnapshot(snapshot) {
468
+ const rendered = renderOperatorSnapshot(snapshot);
469
+ if (rendered && rendered !== lastSnapshot) {
470
+ writeLine(rendered);
471
+ lastSnapshot = rendered;
472
+ }
473
+ },
474
+ renderTimeline(entries) {
475
+ for (const [index, entry] of entries.entries()) {
476
+ const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
477
+ if (entry.type === "assistant_message" && typeof entry.text === "string") {
478
+ const text = entry.text;
479
+ const previousText = assistantTextById.get(id) ?? "";
480
+ if (!previousText && text.trim()) {
481
+ writeLine("[Pi assistant]");
482
+ }
483
+ if (text.startsWith(previousText)) {
484
+ const delta = text.slice(previousText.length);
485
+ if (delta)
486
+ output.write(delta);
487
+ } else if (text.trim() && text !== previousText) {
488
+ if (previousText)
489
+ writeLine(`
490
+ [Pi assistant]`);
491
+ output.write(text);
492
+ }
493
+ assistantTextById.set(id, text);
494
+ continue;
495
+ }
496
+ if (seenTimeline.has(id))
497
+ continue;
498
+ seenTimeline.add(id);
499
+ if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
500
+ writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
501
+ continue;
502
+ }
503
+ if (entry.type === "timeline_warning") {
504
+ writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
505
+ continue;
506
+ }
507
+ if (entry.type === "action") {
508
+ const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
509
+ if (text)
510
+ writeLine(`[Rig action] ${text}`);
511
+ continue;
512
+ }
513
+ if (entry.type === "user_message") {
514
+ const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
515
+ if (text)
516
+ writeLine(`[Operator] ${text}`);
517
+ continue;
518
+ }
519
+ const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
520
+ if (fallback)
521
+ writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
522
+ }
523
+ },
524
+ renderLogs(entries) {
525
+ for (const [index, entry] of entries.entries()) {
526
+ const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
527
+ if (seenLogs.has(id))
528
+ continue;
529
+ seenLogs.add(id);
530
+ const title = String(entry.title ?? "");
531
+ if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
532
+ continue;
533
+ const detail = logDetail(entry);
534
+ if (!detail)
535
+ continue;
536
+ const protocolRecord = parseProviderProtocolLog(title, detail);
537
+ if (protocolRecord) {
538
+ const protocolLine = renderProviderProtocolLog(protocolRecord);
539
+ if (protocolLine)
540
+ writeLine(protocolLine);
541
+ continue;
542
+ }
543
+ writeLine(`[${title || "Rig log"}] ${detail}`);
544
+ }
545
+ }
546
+ };
547
+ }
548
+ function createOperatorSurface(options = {}) {
549
+ const input = options.input ?? process.stdin;
550
+ const output = options.output ?? process.stdout;
551
+ const errorOutput = options.errorOutput ?? process.stderr;
552
+ const renderer = createPiRunStreamRenderer(output);
553
+ const writeLine = (line) => output.write(`${line}
554
+ `);
555
+ return {
556
+ mode: "pi-compatible-text",
557
+ ...renderer,
558
+ info: writeLine,
559
+ error: (message) => errorOutput.write(`${message}
560
+ `),
561
+ attachCommandInput(handler) {
562
+ if (options.interactive === false || !input.isTTY)
563
+ return null;
564
+ const rl = createInterface({ input, output: process.stdout, terminal: false });
565
+ rl.on("line", (line) => {
566
+ Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
567
+ });
568
+ return { close: () => rl.close() };
569
+ }
570
+ };
571
+ }
572
+
573
+ // packages/cli/src/commands/_pi-frontend.ts
574
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
575
+ import { homedir as homedir2, tmpdir } from "os";
576
+ import { join } from "path";
577
+ import { main as runPiMain } from "@earendil-works/pi-coding-agent";
578
+ import createPiRigExtension from "@rig/pi-rig";
579
+
580
+ // packages/cli/src/commands/_async-ui.ts
581
+ import pc from "picocolors";
582
+
583
+ // packages/cli/src/commands/_spinner.ts
584
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
585
+ function createTtySpinner(input) {
586
+ const output = input.output ?? process.stdout;
587
+ const isTty = output.isTTY === true;
588
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
589
+ let label = input.label;
590
+ let frame = 0;
591
+ let paused = false;
592
+ let stopped = false;
593
+ let lastPrintedLabel = "";
594
+ const render = () => {
595
+ if (stopped || paused)
596
+ return;
597
+ if (!isTty) {
598
+ if (label !== lastPrintedLabel) {
599
+ output.write(`${label}
600
+ `);
601
+ lastPrintedLabel = label;
602
+ }
603
+ return;
604
+ }
605
+ frame = (frame + 1) % frames.length;
606
+ const glyph = frames[frame] ?? frames[0] ?? "";
607
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
608
+ };
609
+ const clearLine = () => {
610
+ if (isTty)
611
+ output.write("\r\x1B[2K");
612
+ };
613
+ render();
614
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
615
+ return {
616
+ setLabel(next) {
617
+ label = next;
618
+ render();
619
+ },
620
+ pause() {
621
+ paused = true;
622
+ clearLine();
623
+ },
624
+ resume() {
625
+ if (stopped)
626
+ return;
627
+ paused = false;
628
+ render();
629
+ },
630
+ stop(finalLine) {
631
+ if (stopped)
632
+ return;
633
+ stopped = true;
634
+ if (timer)
635
+ clearInterval(timer);
636
+ clearLine();
637
+ if (finalLine)
638
+ output.write(`${finalLine}
639
+ `);
640
+ }
641
+ };
642
+ }
643
+
644
+ // packages/cli/src/app/theme.ts
645
+ var RIG_PALETTE = {
646
+ ink: "#f2f3f6",
647
+ ink2: "#aeb0ba",
648
+ ink3: "#6c6e79",
649
+ ink4: "#44464f",
650
+ accent: "#ccff4d",
651
+ accentDim: "#a9d63f",
652
+ cyan: "#56d8ff",
653
+ red: "#ff5d5d",
654
+ yellow: "#ffd24d"
655
+ };
656
+ function hexToRgb(hex) {
657
+ const value = hex.replace("#", "");
658
+ return [
659
+ Number.parseInt(value.slice(0, 2), 16),
660
+ Number.parseInt(value.slice(2, 4), 16),
661
+ Number.parseInt(value.slice(4, 6), 16)
662
+ ];
663
+ }
664
+ function fg(hex) {
665
+ const [r, g, b] = hexToRgb(hex);
666
+ return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
667
+ }
668
+ var ink = fg(RIG_PALETTE.ink);
669
+ var ink2 = fg(RIG_PALETTE.ink2);
670
+ var ink3 = fg(RIG_PALETTE.ink3);
671
+ var ink4 = fg(RIG_PALETTE.ink4);
672
+ var accent = fg(RIG_PALETTE.accent);
673
+ var accentDim = fg(RIG_PALETTE.accentDim);
674
+ var cyan = fg(RIG_PALETTE.cyan);
675
+ var red = fg(RIG_PALETTE.red);
676
+ var yellow = fg(RIG_PALETTE.yellow);
677
+ function bold(text) {
678
+ return `\x1B[1m${text}\x1B[22m`;
679
+ }
680
+ var DRONE_ART = [
681
+ " .-=-. .-=-. ",
682
+ " ( !!! ) ( !!! ) ",
683
+ " '-=-'._ _.'-=-' ",
684
+ " '._ _.' ",
685
+ " '=$$$$$$$=.' ",
686
+ " =$$$$$$$$$$$= ",
687
+ " $$$@@@@@@@@@@$$$ ",
688
+ " $$$@@ @@$$$ ",
689
+ " $$@ ? @$$$ ",
690
+ " $$$@ '-' @$$$ ",
691
+ " $$$@@ @@$$$ ",
692
+ " $$$@@@@@@@@@@$$$ ",
693
+ " =$$$$$$$$$$$= ",
694
+ " '=$$$$$$$=.' ",
695
+ " _.' '._ ",
696
+ " .-=-.' '.-=-. ",
697
+ " ( !!! ) ( !!! ) ",
698
+ " '-=-' '-=-' "
699
+ ];
700
+ var EYE_FRAMES = ["@", "o", "."];
701
+ var DRONE_WIDTH = DRONE_ART[0].length;
702
+ var DRONE_HEIGHT = DRONE_ART.length;
703
+ var MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
704
+ function microDroneFrame(tick) {
705
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
706
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
707
+ return `(${blade})${eye}(${blade})`;
708
+ }
709
+ var MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
710
+ function renderMicroDroneFrame(tick) {
711
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
712
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
713
+ return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
714
+ }
715
+
716
+ // packages/cli/src/commands/_async-ui.ts
717
+ var DONE_SYMBOL = pc.green("\u25C7");
718
+ var FAIL_SYMBOL = pc.red("\u25A0");
719
+ var activeUpdate = null;
720
+ async function withSpinner(label, work, options = {}) {
721
+ if (options.outputMode === "json") {
722
+ return work(() => {});
723
+ }
724
+ if (activeUpdate) {
725
+ const outer = activeUpdate;
726
+ outer(label);
727
+ return work(outer);
728
+ }
729
+ const output = options.output ?? process.stderr;
730
+ const isTty = output.isTTY === true;
731
+ let lastLabel = label;
732
+ if (!isTty) {
733
+ output.write(`${label}
734
+ `);
735
+ const update2 = (next) => {
736
+ lastLabel = next;
737
+ };
738
+ activeUpdate = update2;
739
+ const previousListener2 = setServerPhaseListener(update2);
740
+ try {
741
+ return await work(update2);
742
+ } finally {
743
+ activeUpdate = null;
744
+ setServerPhaseListener(previousListener2);
745
+ }
746
+ }
747
+ const spinner = createTtySpinner({
748
+ label,
749
+ output,
750
+ frames: MICRO_DRONE_FRAMES,
751
+ styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
752
+ });
753
+ const update = (next) => {
754
+ lastLabel = next;
755
+ spinner.setLabel(next);
756
+ };
757
+ activeUpdate = update;
758
+ const previousListener = setServerPhaseListener(update);
759
+ try {
760
+ const result = await work(update);
761
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
762
+ return result;
763
+ } catch (error) {
764
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
765
+ throw error;
766
+ } finally {
767
+ activeUpdate = null;
768
+ setServerPhaseListener(previousListener);
769
+ }
770
+ }
771
+
772
+ // packages/cli/src/commands/_pi-frontend.ts
773
+ function setTemporaryEnv(updates) {
774
+ const previous = new Map;
775
+ for (const [key, value] of Object.entries(updates)) {
776
+ previous.set(key, process.env[key]);
777
+ process.env[key] = value;
778
+ }
779
+ return () => {
780
+ for (const [key, value] of previous) {
781
+ if (value === undefined)
782
+ delete process.env[key];
783
+ else
784
+ process.env[key] = value;
785
+ }
786
+ };
787
+ }
788
+ function buildOperatorPiEnv(input) {
789
+ return {
790
+ PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
791
+ PI_SKIP_VERSION_CHECK: "1",
792
+ PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
793
+ RIG_PI_OPERATOR_SESSION: "1",
794
+ RIG_RUN_ID: input.runId,
795
+ RIG_SERVER_URL: input.serverUrl,
796
+ ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
797
+ ...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
798
+ };
799
+ }
800
+ async function prepareOperatorConsole(context, runId, tempSessionDir) {
801
+ const server = await ensureServerForCli(context.projectRoot);
802
+ const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
803
+ mkdirSync2(localCwd, { recursive: true });
804
+ trustDroneCwd(localCwd);
805
+ installRigPiTheme();
806
+ let sessionFileArg = [];
807
+ try {
808
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
809
+ if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
810
+ const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
811
+ const localSessionPath = join(tempSessionDir, fileName);
812
+ const content = payload.content.split(`
813
+ `).map((line, index) => {
814
+ if (index > 0 || !line.trim())
815
+ return line;
816
+ try {
817
+ const header = JSON.parse(line);
818
+ if (header.type === "session" && typeof header.cwd === "string") {
819
+ return JSON.stringify({ ...header, cwd: localCwd });
820
+ }
821
+ } catch {}
822
+ return line;
823
+ }).join(`
824
+ `);
825
+ writeFileSync2(localSessionPath, content);
826
+ sessionFileArg = ["--session", localSessionPath];
827
+ }
828
+ } catch {}
829
+ return { server, sessionFileArg };
830
+ }
831
+ var RIG_PI_THEME = {
832
+ $schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
833
+ name: "rig",
834
+ vars: {
835
+ acid: "#ccff4d",
836
+ acidDim: "#a9d63f",
837
+ cyan: "#56d8ff",
838
+ red: "#ff5d5d",
839
+ yellow: "#ffd24d",
840
+ ink: "#f2f3f6",
841
+ ink2: "#aeb0ba",
842
+ ink3: "#6c6e79",
843
+ ink4: "#44464f",
844
+ panel: "#101115",
845
+ panelUser: "#14161b",
846
+ toolPending: "#0e1013",
847
+ toolSuccess: "#10150c",
848
+ toolError: "#1a0f0f",
849
+ customMsg: "#0f1410"
850
+ },
851
+ colors: {
852
+ accent: "acid",
853
+ border: "ink4",
854
+ borderAccent: "acid",
855
+ borderMuted: "ink4",
856
+ success: "acid",
857
+ error: "red",
858
+ warning: "yellow",
859
+ muted: "ink3",
860
+ dim: "ink4",
861
+ text: "ink",
862
+ thinkingText: "ink3",
863
+ selectedBg: "panel",
864
+ userMessageBg: "panelUser",
865
+ userMessageText: "ink",
866
+ customMessageBg: "customMsg",
867
+ customMessageText: "ink2",
868
+ customMessageLabel: "acidDim",
869
+ toolPendingBg: "toolPending",
870
+ toolSuccessBg: "toolSuccess",
871
+ toolErrorBg: "toolError",
872
+ toolTitle: "ink",
873
+ toolOutput: "ink3",
874
+ mdHeading: "acid",
875
+ mdLink: "cyan",
876
+ mdLinkUrl: "ink4",
877
+ mdCode: "acidDim",
878
+ mdCodeBlock: "ink2",
879
+ mdCodeBlockBorder: "ink4",
880
+ mdQuote: "ink3",
881
+ mdQuoteBorder: "ink4",
882
+ mdHr: "ink4",
883
+ mdListBullet: "acid",
884
+ toolDiffAdded: "acid",
885
+ toolDiffRemoved: "red",
886
+ toolDiffContext: "ink3",
887
+ syntaxComment: "ink3",
888
+ syntaxKeyword: "cyan",
889
+ syntaxFunction: "acid",
890
+ syntaxVariable: "ink",
891
+ syntaxString: "acidDim",
892
+ syntaxNumber: "yellow",
893
+ syntaxType: "cyan",
894
+ syntaxOperator: "ink2",
895
+ syntaxPunctuation: "ink3",
896
+ thinkingOff: "ink4",
897
+ thinkingMinimal: "ink3",
898
+ thinkingLow: "ink2",
899
+ thinkingMedium: "cyan",
900
+ thinkingHigh: "acidDim",
901
+ thinkingXhigh: "acid",
902
+ bashMode: "cyan"
903
+ }
904
+ };
905
+ function trustDroneCwd(localCwd) {
906
+ try {
907
+ const agentDir = join(homedir2(), ".pi", "agent");
908
+ mkdirSync2(agentDir, { recursive: true });
909
+ const trustPath = join(agentDir, "trust.json");
910
+ const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
911
+ if (store[localCwd] !== true) {
912
+ store[localCwd] = true;
913
+ writeFileSync2(trustPath, `${JSON.stringify(store, null, "\t")}
914
+ `);
915
+ }
916
+ } catch {}
917
+ }
918
+ function installRigPiTheme() {
919
+ try {
920
+ const themesDir = join(homedir2(), ".pi", "agent", "themes");
921
+ mkdirSync2(themesDir, { recursive: true });
922
+ const themePath = join(themesDir, "rig.json");
923
+ const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
924
+ `;
925
+ if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
926
+ writeFileSync2(themePath, next);
927
+ }
928
+ } catch {}
929
+ }
930
+ async function attachRunBundledPiFrontend(context, input) {
931
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
932
+ const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
933
+ const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
934
+ runId: input.runId,
935
+ serverUrl: server.baseUrl,
936
+ authToken: server.authToken,
937
+ serverProjectRoot: server.serverProjectRoot,
938
+ sessionDir: tempSessionDir
939
+ }));
940
+ const piRigExtensionFactory = (pi) => {
941
+ createPiRigExtension(pi);
942
+ };
943
+ let detached = false;
944
+ try {
945
+ await runPiMain([
946
+ "--no-extensions",
947
+ "--no-skills",
948
+ "--no-prompt-templates",
949
+ "--no-context-files",
950
+ ...sessionFileArg
951
+ ], {
952
+ extensionFactories: [piRigExtensionFactory]
953
+ });
954
+ detached = true;
955
+ } finally {
956
+ restoreEnv();
957
+ rmSync(tempSessionDir, { recursive: true, force: true });
958
+ }
959
+ let run = { runId: input.runId, status: "unknown" };
960
+ try {
961
+ run = await getRunDetailsViaServer(context, input.runId);
962
+ } catch {}
963
+ return {
964
+ run,
965
+ logs: [],
966
+ timeline: [],
967
+ timelineCursor: null,
968
+ steered: input.steered === true,
969
+ detached,
970
+ rendered: "stock Pi operator console with the pi-rig extension"
971
+ };
972
+ }
973
+
974
+ // packages/cli/src/commands/_operator-view.ts
975
+ var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
266
976
  function runStatusFromPayload(payload) {
267
977
  const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
268
978
  return String(run.status ?? "unknown").toLowerCase();
@@ -284,57 +994,77 @@ async function applyOperatorCommand(context, input, deps = {}) {
284
994
  await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
285
995
  return { action: "continue", message: "Steering message queued." };
286
996
  }
287
- async function readOperatorSnapshot(context, runId) {
997
+ async function readOperatorSnapshot(context, runId, options = {}) {
288
998
  const run = await getRunDetailsViaServer(context, runId);
289
999
  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 }) };
1000
+ const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
1001
+ entries: [{
1002
+ id: `timeline-unavailable:${runId}`,
1003
+ type: "timeline_warning",
1004
+ detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
1005
+ createdAt: new Date().toISOString()
1006
+ }],
1007
+ nextCursor: options.timelineCursor ?? null
1008
+ }));
1009
+ const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
1010
+ const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1011
+ const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
1012
+ return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
292
1013
  }
293
1014
  async function attachRunOperatorView(context, input) {
294
1015
  let steered = false;
295
- if (input.message?.trim()) {
296
- await steerRunViaServer(context, input.runId, input.message.trim());
1016
+ const attachMessage = input.message?.trim();
1017
+ if (attachMessage) {
1018
+ await withSpinner("Queueing steering message\u2026", () => sendRunPiPromptViaServer(context, input.runId, attachMessage, "steer").catch(() => steerRunViaServer(context, input.runId, attachMessage)), { outputMode: context.outputMode });
297
1019
  steered = true;
298
1020
  }
299
- let snapshot = await readOperatorSnapshot(context, input.runId);
1021
+ if (!input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
1022
+ return attachRunBundledPiFrontend(context, {
1023
+ runId: input.runId,
1024
+ steered
1025
+ });
1026
+ }
1027
+ const surface = createOperatorSurface({ interactive: input.interactive !== false });
1028
+ let snapshot = await withSpinner(`Connecting to run ${input.runId}\u2026`, () => readOperatorSnapshot(context, input.runId), { outputMode: context.outputMode });
300
1029
  if (context.outputMode === "text") {
301
- console.log(snapshot.rendered);
1030
+ surface.renderSnapshot(snapshot);
1031
+ surface.renderTimeline(snapshot.timeline);
1032
+ surface.renderLogs(snapshot.logs);
302
1033
  if (steered)
303
- console.log("Steering message queued.");
1034
+ surface.info("Message submitted to worker Pi.");
304
1035
  }
305
1036
  let detached = false;
306
- let rl = null;
1037
+ let commandInput = null;
307
1038
  if (input.follow && !input.once && context.outputMode === "text") {
308
1039
  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)}`));
1040
+ surface.info("Controls: /user <message>, /stop, /detach");
1041
+ commandInput = surface.attachCommandInput(async (line) => {
1042
+ const result = await applyOperatorCommand(context, { runId: input.runId, line });
1043
+ if (result.message)
1044
+ surface.info(result.message);
1045
+ if (result.action === "detach" || result.action === "stopped") {
1046
+ detached = true;
1047
+ commandInput?.close();
1048
+ }
320
1049
  });
321
1050
  }
322
- let lastRendered = snapshot.rendered;
323
1051
  const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
1052
+ let timelineCursor = snapshot.timelineCursor;
324
1053
  while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
325
1054
  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
- }
1055
+ snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
1056
+ timelineCursor = snapshot.timelineCursor;
1057
+ surface.renderSnapshot(snapshot);
1058
+ surface.renderTimeline(snapshot.timeline);
1059
+ surface.renderLogs(snapshot.logs);
331
1060
  }
332
- rl?.close();
1061
+ commandInput?.close();
333
1062
  }
334
1063
  return { ...snapshot, steered, detached };
335
1064
  }
336
1065
  export {
337
1066
  renderOperatorSnapshot,
1067
+ createPiRunStreamRenderer,
338
1068
  attachRunOperatorView,
339
1069
  applyOperatorCommand
340
1070
  };