@h-rig/cli 0.0.6-alpha.24 → 0.0.6-alpha.240

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 (51) hide show
  1. package/README.md +6 -28
  2. package/package.json +13 -28
  3. package/dist/bin/build-rig-binaries.js +0 -107
  4. package/dist/bin/rig.js +0 -11112
  5. package/dist/src/commands/_authority-runs.js +0 -111
  6. package/dist/src/commands/_cli-format.js +0 -106
  7. package/dist/src/commands/_connection-state.js +0 -123
  8. package/dist/src/commands/_doctor-checks.js +0 -507
  9. package/dist/src/commands/_operator-surface.js +0 -204
  10. package/dist/src/commands/_operator-view.js +0 -1147
  11. package/dist/src/commands/_parsers.js +0 -107
  12. package/dist/src/commands/_paths.js +0 -50
  13. package/dist/src/commands/_pi-frontend.js +0 -843
  14. package/dist/src/commands/_pi-install.js +0 -185
  15. package/dist/src/commands/_pi-worker-bridge-extension.js +0 -761
  16. package/dist/src/commands/_policy.js +0 -79
  17. package/dist/src/commands/_preflight.js +0 -403
  18. package/dist/src/commands/_probes.js +0 -13
  19. package/dist/src/commands/_run-driver-helpers.js +0 -289
  20. package/dist/src/commands/_server-client.js +0 -514
  21. package/dist/src/commands/_snapshot-upload.js +0 -318
  22. package/dist/src/commands/_task-picker.js +0 -76
  23. package/dist/src/commands/agent.js +0 -499
  24. package/dist/src/commands/browser.js +0 -890
  25. package/dist/src/commands/connect.js +0 -180
  26. package/dist/src/commands/dist.js +0 -402
  27. package/dist/src/commands/doctor.js +0 -517
  28. package/dist/src/commands/github.js +0 -281
  29. package/dist/src/commands/inbox.js +0 -160
  30. package/dist/src/commands/init.js +0 -1563
  31. package/dist/src/commands/inspect.js +0 -174
  32. package/dist/src/commands/inspector.js +0 -256
  33. package/dist/src/commands/plugin.js +0 -167
  34. package/dist/src/commands/profile-and-review.js +0 -178
  35. package/dist/src/commands/queue.js +0 -198
  36. package/dist/src/commands/remote.js +0 -507
  37. package/dist/src/commands/repo-git-harness.js +0 -221
  38. package/dist/src/commands/run.js +0 -1674
  39. package/dist/src/commands/server.js +0 -373
  40. package/dist/src/commands/setup.js +0 -687
  41. package/dist/src/commands/task-report-bug.js +0 -1083
  42. package/dist/src/commands/task-run-driver.js +0 -2600
  43. package/dist/src/commands/task.js +0 -2178
  44. package/dist/src/commands/test.js +0 -39
  45. package/dist/src/commands/workspace.js +0 -123
  46. package/dist/src/commands.js +0 -10791
  47. package/dist/src/index.js +0 -11130
  48. package/dist/src/launcher.js +0 -133
  49. package/dist/src/report-bug.js +0 -260
  50. package/dist/src/runner.js +0 -273
  51. package/dist/src/withMutedConsole.js +0 -42
@@ -1,1147 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/_server-client.ts
3
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
4
- import { resolve as resolve2 } from "path";
5
-
6
- // packages/cli/src/runner.ts
7
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
8
- import { CliError } from "@rig/runtime/control-plane/errors";
9
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
10
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
11
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
12
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
13
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
14
-
15
- // packages/cli/src/commands/_server-client.ts
16
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
17
-
18
- // packages/cli/src/commands/_connection-state.ts
19
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
20
- import { homedir } from "os";
21
- import { dirname, resolve } from "path";
22
- function resolveGlobalConnectionsPath(env = process.env) {
23
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
24
- if (explicit)
25
- return resolve(explicit);
26
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
27
- if (stateDir)
28
- return resolve(stateDir, "connections.json");
29
- return resolve(homedir(), ".rig", "connections.json");
30
- }
31
- function resolveRepoConnectionPath(projectRoot) {
32
- return resolve(projectRoot, ".rig", "state", "connection.json");
33
- }
34
- function readJsonFile(path) {
35
- if (!existsSync(path))
36
- return null;
37
- try {
38
- return JSON.parse(readFileSync(path, "utf8"));
39
- } catch (error) {
40
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
41
- }
42
- }
43
- function normalizeConnection(value) {
44
- if (!value || typeof value !== "object" || Array.isArray(value))
45
- return null;
46
- const record = value;
47
- if (record.kind === "local")
48
- return { kind: "local", mode: "auto" };
49
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
50
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
51
- return { kind: "remote", baseUrl };
52
- }
53
- return null;
54
- }
55
- function readGlobalConnections(options = {}) {
56
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
57
- const payload = readJsonFile(path);
58
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
59
- return { connections: {} };
60
- }
61
- const rawConnections = payload.connections;
62
- const connections = {};
63
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
64
- for (const [alias, raw] of Object.entries(rawConnections)) {
65
- const connection = normalizeConnection(raw);
66
- if (connection)
67
- connections[alias] = connection;
68
- }
69
- }
70
- return { connections };
71
- }
72
- function readRepoConnection(projectRoot) {
73
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
74
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
75
- return null;
76
- const record = payload;
77
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
78
- if (!selected)
79
- return null;
80
- return {
81
- selected,
82
- project: typeof record.project === "string" ? record.project : undefined,
83
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
84
- };
85
- }
86
- function resolveSelectedConnection(projectRoot, options = {}) {
87
- const repo = readRepoConnection(projectRoot);
88
- if (!repo)
89
- return null;
90
- if (repo.selected === "local")
91
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
92
- const global = readGlobalConnections(options);
93
- const connection = global.connections[repo.selected];
94
- if (!connection) {
95
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
96
- }
97
- return { alias: repo.selected, connection };
98
- }
99
-
100
- // packages/cli/src/commands/_server-client.ts
101
- var scopedGitHubBearerTokens = new Map;
102
- function cleanToken(value) {
103
- const trimmed = value?.trim();
104
- return trimmed ? trimmed : null;
105
- }
106
- function readPrivateRemoteSessionToken(projectRoot) {
107
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
108
- if (!existsSync2(path))
109
- return null;
110
- try {
111
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
112
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
113
- } catch {
114
- return null;
115
- }
116
- }
117
- function readGitHubBearerTokenForRemote(projectRoot) {
118
- const scopedKey = resolve2(projectRoot);
119
- if (scopedGitHubBearerTokens.has(scopedKey))
120
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
121
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
122
- if (privateSession)
123
- return privateSession;
124
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
125
- }
126
- async function ensureServerForCli(projectRoot) {
127
- try {
128
- const selected = resolveSelectedConnection(projectRoot);
129
- if (selected?.connection.kind === "remote") {
130
- return {
131
- baseUrl: selected.connection.baseUrl,
132
- authToken: readGitHubBearerTokenForRemote(projectRoot),
133
- connectionKind: "remote"
134
- };
135
- }
136
- const connection = await ensureLocalRigServerConnection(projectRoot);
137
- return {
138
- baseUrl: connection.baseUrl,
139
- authToken: connection.authToken,
140
- connectionKind: "local"
141
- };
142
- } catch (error) {
143
- if (error instanceof Error) {
144
- throw new CliError2(error.message, 1);
145
- }
146
- throw error;
147
- }
148
- }
149
- function mergeHeaders(headers, authToken) {
150
- const merged = new Headers(headers);
151
- if (authToken) {
152
- merged.set("authorization", `Bearer ${authToken}`);
153
- }
154
- return merged;
155
- }
156
- function diagnosticMessage(payload) {
157
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
158
- return null;
159
- const record = payload;
160
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
161
- const messages = diagnostics.flatMap((entry) => {
162
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
163
- return [];
164
- const diagnostic = entry;
165
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
166
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
167
- return message ? [`${kind}: ${message}`] : [];
168
- });
169
- return messages.length > 0 ? messages.join("; ") : null;
170
- }
171
- async function requestServerJson(context, pathname, init = {}) {
172
- const server = await ensureServerForCli(context.projectRoot);
173
- const response = await fetch(`${server.baseUrl}${pathname}`, {
174
- ...init,
175
- headers: mergeHeaders(init.headers, server.authToken)
176
- });
177
- const text = await response.text();
178
- const payload = text.trim().length > 0 ? (() => {
179
- try {
180
- return JSON.parse(text);
181
- } catch {
182
- return null;
183
- }
184
- })() : null;
185
- if (!response.ok) {
186
- const diagnostics = diagnosticMessage(payload);
187
- const detail = diagnostics ?? (text || response.statusText);
188
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
189
- }
190
- return payload;
191
- }
192
- async function getRunDetailsViaServer(context, runId) {
193
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
194
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
195
- }
196
- async function getRunLogsViaServer(context, runId, options = {}) {
197
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
198
- if (options.limit !== undefined)
199
- url.searchParams.set("limit", String(options.limit));
200
- if (options.cursor)
201
- url.searchParams.set("cursor", options.cursor);
202
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
203
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
204
- }
205
- async function getRunTimelineViaServer(context, runId, options = {}) {
206
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
207
- if (options.limit !== undefined)
208
- url.searchParams.set("limit", String(options.limit));
209
- if (options.cursor)
210
- url.searchParams.set("cursor", options.cursor);
211
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
212
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
213
- }
214
- async function stopRunViaServer(context, runId) {
215
- const payload = await requestServerJson(context, "/api/runs/stop", {
216
- method: "POST",
217
- headers: { "content-type": "application/json" },
218
- body: JSON.stringify({ runId })
219
- });
220
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
221
- }
222
- async function steerRunViaServer(context, runId, message) {
223
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
224
- method: "POST",
225
- headers: { "content-type": "application/json" },
226
- body: JSON.stringify({ message })
227
- });
228
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
229
- }
230
- async function getRunPiSessionViaServer(context, runId) {
231
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
232
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
233
- }
234
- async function getRunPiMessagesViaServer(context, runId) {
235
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
236
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
237
- }
238
- async function getRunPiStatusViaServer(context, runId) {
239
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
240
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
241
- }
242
- async function getRunPiCommandsViaServer(context, runId) {
243
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
244
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
245
- }
246
- async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
247
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
248
- method: "POST",
249
- headers: { "content-type": "application/json" },
250
- body: JSON.stringify({ text, streamingBehavior })
251
- });
252
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
253
- }
254
- async function sendRunPiShellViaServer(context, runId, text) {
255
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
256
- method: "POST",
257
- headers: { "content-type": "application/json" },
258
- body: JSON.stringify({ text })
259
- });
260
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
261
- }
262
- async function runRunPiCommandViaServer(context, runId, text) {
263
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
264
- method: "POST",
265
- headers: { "content-type": "application/json" },
266
- body: JSON.stringify({ text })
267
- });
268
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
269
- }
270
- async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
271
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
272
- method: "POST",
273
- headers: { "content-type": "application/json" },
274
- body: JSON.stringify({ requestId, ...valueOrCancel })
275
- });
276
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
277
- }
278
- async function abortRunPiViaServer(context, runId) {
279
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
280
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
281
- }
282
- async function buildRunPiEventsWebSocketUrl(context, runId) {
283
- const server = await ensureServerForCli(context.projectRoot);
284
- const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
285
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
286
- if (server.authToken)
287
- url.searchParams.set("token", server.authToken);
288
- return url.toString();
289
- }
290
-
291
- // packages/cli/src/commands/_operator-surface.ts
292
- import { createInterface } from "readline";
293
- var CANONICAL_STAGES = [
294
- "Connect",
295
- "GitHub/task sync",
296
- "Prepare workspace",
297
- "Launch Pi",
298
- "Plan",
299
- "Implement",
300
- "Validate",
301
- "Commit",
302
- "Open PR",
303
- "Review/CI",
304
- "Merge",
305
- "Complete"
306
- ];
307
- function logDetail(log) {
308
- return typeof log.detail === "string" ? log.detail.trim() : "";
309
- }
310
- function parseProviderProtocolLog(title, detail) {
311
- if (title.trim().toLowerCase() !== "agent output")
312
- return null;
313
- if (!detail.startsWith("{") || !detail.endsWith("}"))
314
- return null;
315
- try {
316
- const record = JSON.parse(detail);
317
- if (!record || typeof record !== "object" || Array.isArray(record))
318
- return null;
319
- const type = record.type;
320
- return typeof type === "string" && [
321
- "assistant",
322
- "message_start",
323
- "message_update",
324
- "message_end",
325
- "stream_event",
326
- "tool_result",
327
- "tool_execution_start",
328
- "tool_execution_update",
329
- "tool_execution_end",
330
- "turn_start",
331
- "turn_end"
332
- ].includes(type) ? record : null;
333
- } catch {
334
- return null;
335
- }
336
- }
337
- function renderProviderProtocolLog(record) {
338
- const type = typeof record.type === "string" ? record.type : "";
339
- if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
340
- const toolName = String(record.toolName ?? record.name ?? "tool");
341
- 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";
342
- return `[Pi tool] ${toolName} ${status}`;
343
- }
344
- return null;
345
- }
346
- function entryId(entry, fallback) {
347
- return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
348
- }
349
- function renderOperatorSnapshot(snapshot) {
350
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
351
- const runId = String(run.runId ?? run.id ?? "run");
352
- const status = String(run.status ?? "unknown");
353
- const logs = snapshot.logs ?? [];
354
- const latestByStage = new Map;
355
- for (const log of logs) {
356
- const title = String(log.title ?? "").toLowerCase();
357
- const stageName = String(log.stage ?? "").toLowerCase();
358
- const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
359
- if (stage)
360
- latestByStage.set(stage, log);
361
- }
362
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
363
- const match = latestByStage.get(stage);
364
- return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
365
- });
366
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
367
- `);
368
- }
369
- function createPiRunStreamRenderer(output = process.stdout) {
370
- let lastSnapshot = "";
371
- const assistantTextById = new Map;
372
- const seenTimeline = new Set;
373
- const seenLogs = new Set;
374
- const writeLine = (line) => output.write(`${line}
375
- `);
376
- return {
377
- renderSnapshot(snapshot) {
378
- const rendered = renderOperatorSnapshot(snapshot);
379
- if (rendered && rendered !== lastSnapshot) {
380
- writeLine(rendered);
381
- lastSnapshot = rendered;
382
- }
383
- },
384
- renderTimeline(entries) {
385
- for (const [index, entry] of entries.entries()) {
386
- const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
387
- if (entry.type === "assistant_message" && typeof entry.text === "string") {
388
- const text = entry.text;
389
- const previousText = assistantTextById.get(id) ?? "";
390
- if (!previousText && text.trim()) {
391
- writeLine("[Pi assistant]");
392
- }
393
- if (text.startsWith(previousText)) {
394
- const delta = text.slice(previousText.length);
395
- if (delta)
396
- output.write(delta);
397
- } else if (text.trim() && text !== previousText) {
398
- if (previousText)
399
- writeLine(`
400
- [Pi assistant]`);
401
- output.write(text);
402
- }
403
- assistantTextById.set(id, text);
404
- continue;
405
- }
406
- if (seenTimeline.has(id))
407
- continue;
408
- seenTimeline.add(id);
409
- if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
410
- writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
411
- continue;
412
- }
413
- if (entry.type === "timeline_warning") {
414
- writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
415
- }
416
- }
417
- },
418
- renderLogs(entries) {
419
- for (const [index, entry] of entries.entries()) {
420
- const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
421
- if (seenLogs.has(id))
422
- continue;
423
- seenLogs.add(id);
424
- const title = String(entry.title ?? "");
425
- if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
426
- continue;
427
- const detail = logDetail(entry);
428
- if (!detail)
429
- continue;
430
- const protocolRecord = parseProviderProtocolLog(title, detail);
431
- if (protocolRecord) {
432
- const protocolLine = renderProviderProtocolLog(protocolRecord);
433
- if (protocolLine)
434
- writeLine(protocolLine);
435
- continue;
436
- }
437
- writeLine(`[${title || "Rig log"}] ${detail}`);
438
- }
439
- }
440
- };
441
- }
442
- function createOperatorSurface(options = {}) {
443
- const input = options.input ?? process.stdin;
444
- const output = options.output ?? process.stdout;
445
- const errorOutput = options.errorOutput ?? process.stderr;
446
- const renderer = createPiRunStreamRenderer(output);
447
- const writeLine = (line) => output.write(`${line}
448
- `);
449
- return {
450
- mode: "pi-compatible-text",
451
- ...renderer,
452
- info: writeLine,
453
- error: (message) => errorOutput.write(`${message}
454
- `),
455
- attachCommandInput(handler) {
456
- if (options.interactive === false || !input.isTTY)
457
- return null;
458
- const rl = createInterface({ input, output: process.stdout, terminal: false });
459
- rl.on("line", (line) => {
460
- Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
461
- });
462
- return { close: () => rl.close() };
463
- }
464
- };
465
- }
466
-
467
- // packages/cli/src/commands/_pi-frontend.ts
468
- import { mkdtempSync, rmSync } from "fs";
469
- import { tmpdir } from "os";
470
- import { join } from "path";
471
- import { main as runPiMain } from "@earendil-works/pi-coding-agent";
472
-
473
- // packages/cli/src/commands/_pi-worker-bridge-extension.ts
474
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
475
- var MAX_TRANSCRIPT_LINES = 120;
476
- function recordOf(value) {
477
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
478
- }
479
- function asText(value) {
480
- if (typeof value === "string")
481
- return value;
482
- if (value === null || value === undefined)
483
- return "";
484
- if (typeof value === "number" || typeof value === "boolean")
485
- return String(value);
486
- try {
487
- return JSON.stringify(value);
488
- } catch {
489
- return String(value);
490
- }
491
- }
492
- function textFromContent(content) {
493
- if (typeof content === "string")
494
- return content;
495
- if (!Array.isArray(content))
496
- return asText(content);
497
- return content.flatMap((part) => {
498
- const item = recordOf(part);
499
- if (!item)
500
- return [];
501
- if (typeof item.text === "string")
502
- return [item.text];
503
- if (typeof item.content === "string")
504
- return [item.content];
505
- if (item.type === "toolCall")
506
- return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
507
- if (item.type === "toolResult")
508
- return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
509
- return [];
510
- }).join(`
511
- `);
512
- }
513
- function appendTranscript(state, label, text) {
514
- const trimmed = text.trimEnd();
515
- if (!trimmed)
516
- return;
517
- const lines = trimmed.split(/\r?\n/);
518
- state.transcript.push(`${label}: ${lines[0] ?? ""}`);
519
- for (const line of lines.slice(1))
520
- state.transcript.push(` ${line}`);
521
- if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
522
- state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
523
- }
524
- }
525
- function nativePiUi(ctx) {
526
- const ui = ctx.ui;
527
- return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
528
- }
529
- function syncNativeDisplayCwd(ctx, state) {
530
- const ui = nativePiUi(ctx);
531
- if (ui?.setDisplayCwd && state.cwd)
532
- ui.setDisplayCwd(state.cwd);
533
- }
534
- function parseExtensionUiRequest(value) {
535
- const request = recordOf(value) ?? {};
536
- const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
537
- const method = String(request.method ?? request.type ?? "input");
538
- const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
539
- const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
540
- const options = rawOptions.map((option) => {
541
- const record = recordOf(option);
542
- return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
543
- }).filter(Boolean);
544
- return { requestId, method, prompt, options };
545
- }
546
- function renderBridgeWidget(state) {
547
- const statusParts = [
548
- state.wsConnected ? "live WS" : "WS pending",
549
- state.status,
550
- state.model,
551
- state.cwd
552
- ].filter(Boolean);
553
- const lines = [`Worker Pi daemon bridge \xB7 ${statusParts.join(" \xB7 ")}`];
554
- if (state.activity)
555
- lines.push(state.activity);
556
- if (state.commands.length > 0) {
557
- lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
558
- }
559
- lines.push("");
560
- if (state.transcript.length > 0) {
561
- lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
562
- } else {
563
- lines.push("Waiting for worker Pi daemon transcript\u2026");
564
- }
565
- if (state.pendingUi) {
566
- lines.push("");
567
- lines.push(`Extension UI request \xB7 ${state.pendingUi.method}`);
568
- lines.push(state.pendingUi.prompt);
569
- state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
570
- lines.push("Reply in the Pi editor. /cancel cancels this request.");
571
- }
572
- return lines;
573
- }
574
- function updatePiUi(ctx, state) {
575
- ctx.ui.setTitle("Pi \xB7 Rig worker daemon");
576
- ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker Pi WS live" : state.status);
577
- syncNativeDisplayCwd(ctx, state);
578
- if (state.nativeStream && nativePiUi(ctx)) {
579
- ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
580
- return;
581
- }
582
- ctx.ui.setWorkingVisible(false);
583
- ctx.ui.setWidget("rig-worker-pi-transcript", [`Worker Pi daemon bridge \xB7 degraded widget transcript`, ...renderBridgeWidget(state)], { placement: "aboveEditor" });
584
- }
585
- function applyStatus(state, payload) {
586
- const status = recordOf(payload.status) ?? payload;
587
- state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
588
- state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
589
- state.model = typeof status.model === "string" ? status.model : state.model;
590
- const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
591
- state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
592
- }
593
- function applyMessage(state, message) {
594
- const record = recordOf(message);
595
- if (!record)
596
- return;
597
- const role = String(record.role ?? "system");
598
- const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
599
- appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
600
- }
601
- function applyPiEvent(ctx, state, eventValue) {
602
- const event = recordOf(eventValue);
603
- if (!event)
604
- return;
605
- const type = String(event.type ?? "event");
606
- if (type === "agent_start") {
607
- state.streaming = true;
608
- state.status = "streaming";
609
- } else if (type === "agent_end") {
610
- state.streaming = false;
611
- state.status = "idle";
612
- } else if (type === "queue_update") {
613
- const steering = Array.isArray(event.steering) ? event.steering.length : 0;
614
- const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
615
- state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
616
- }
617
- const native = nativePiUi(ctx);
618
- if (state.nativeStream && native?.emitSessionEvent) {
619
- native.emitSessionEvent(eventValue);
620
- return;
621
- }
622
- if (type === "agent_end") {
623
- appendTranscript(state, "System", "Agent turn complete.");
624
- return;
625
- }
626
- if (type === "message_start" || type === "message_end" || type === "turn_end") {
627
- applyMessage(state, event.message);
628
- return;
629
- }
630
- if (type === "message_update") {
631
- const assistantEvent = recordOf(event.assistantMessageEvent);
632
- const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
633
- if (delta)
634
- appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
635
- return;
636
- }
637
- if (type === "tool_execution_start") {
638
- appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
639
- return;
640
- }
641
- if (type === "tool_execution_update") {
642
- appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
643
- return;
644
- }
645
- if (type === "tool_execution_end") {
646
- appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
647
- }
648
- }
649
- function firstPendingShell(state) {
650
- return state.pendingShells[0];
651
- }
652
- function finishPendingShell(state, shell, result) {
653
- const index = state.pendingShells.indexOf(shell);
654
- if (index !== -1)
655
- state.pendingShells.splice(index, 1);
656
- shell.resolve(result);
657
- }
658
- function failPendingShell(state, shell, error) {
659
- const index = state.pendingShells.indexOf(shell);
660
- if (index !== -1)
661
- state.pendingShells.splice(index, 1);
662
- shell.reject(error);
663
- }
664
- function applyUiEvent(state, value) {
665
- const event = recordOf(value);
666
- if (!event)
667
- return;
668
- const type = String(event.type ?? "ui");
669
- if (type === "shell.chunk") {
670
- const pending = firstPendingShell(state);
671
- const chunk = asText(event.chunk);
672
- if (pending) {
673
- pending.sawChunk = true;
674
- pending.onData(Buffer.from(chunk));
675
- } else {
676
- appendTranscript(state, "Tool", chunk);
677
- }
678
- return;
679
- }
680
- if (type === "shell.end") {
681
- const pending = firstPendingShell(state);
682
- const output = asText(event.output ?? "");
683
- const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
684
- if (pending) {
685
- if (output && !pending.sawChunk)
686
- pending.onData(Buffer.from(output));
687
- finishPendingShell(state, pending, { exitCode });
688
- } else {
689
- appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
690
- }
691
- return;
692
- }
693
- if (type === "shell.start") {
694
- if (!firstPendingShell(state))
695
- appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
696
- return;
697
- }
698
- appendTranscript(state, "System", `${type}: ${asText(event)}`);
699
- }
700
- function applyEnvelope(ctx, state, envelopeValue) {
701
- const envelope = recordOf(envelopeValue);
702
- if (!envelope)
703
- return;
704
- const type = String(envelope.type ?? "");
705
- if (type === "ready") {
706
- const metadata = recordOf(envelope.metadata);
707
- state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
708
- state.status = "worker Pi daemon ready";
709
- if (!state.nativeStream)
710
- appendTranscript(state, "System", "Connected to worker Pi daemon.");
711
- } else if (type === "status.update") {
712
- applyStatus(state, envelope);
713
- } else if (type === "activity.update") {
714
- const activity = recordOf(envelope.activity);
715
- state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
716
- } else if (type === "extension_ui_request") {
717
- state.pendingUi = parseExtensionUiRequest(envelope.request);
718
- appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
719
- } else if (type === "pi.ui_event") {
720
- applyUiEvent(state, envelope.event);
721
- } else if (type === "pi.event") {
722
- applyPiEvent(ctx, state, envelope.event);
723
- } else if (type === "error") {
724
- appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
725
- }
726
- syncNativeDisplayCwd(ctx, state);
727
- }
728
- async function waitForWorkerReady(options, ctx, state) {
729
- while (true) {
730
- const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => ({
731
- ready: false,
732
- status: error instanceof Error ? error.message : String(error),
733
- retryAfterMs: 1000
734
- }));
735
- if (session.ready === false) {
736
- const status = String(session.status ?? "starting");
737
- state.status = `waiting for worker Pi daemon \xB7 ${status}`;
738
- updatePiUi(ctx, state);
739
- if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
740
- appendTranscript(state, "Error", `Run ended before worker Pi daemon became ready: ${status}`);
741
- return false;
742
- }
743
- await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
744
- continue;
745
- }
746
- const sessionRecord = recordOf(session) ?? {};
747
- applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
748
- updatePiUi(ctx, state);
749
- return true;
750
- }
751
- }
752
- function parseWsPayload(message) {
753
- if (typeof message.data === "string")
754
- return JSON.parse(message.data);
755
- return JSON.parse(Buffer.from(message.data).toString("utf8"));
756
- }
757
- async function connectWorkerStream(options, ctx, state) {
758
- const ready = await waitForWorkerReady(options, ctx, state);
759
- if (!ready)
760
- return;
761
- let catchupDone = false;
762
- const buffered = [];
763
- const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
764
- const socket = new WebSocket(wsUrl);
765
- const closePromise = new Promise((resolve3) => {
766
- socket.onopen = () => {
767
- state.wsConnected = true;
768
- state.status = "live worker Pi WebSocket connected";
769
- updatePiUi(ctx, state);
770
- };
771
- socket.onmessage = (message) => {
772
- try {
773
- const payload = parseWsPayload(message);
774
- if (!catchupDone)
775
- buffered.push(payload);
776
- else {
777
- applyEnvelope(ctx, state, payload);
778
- updatePiUi(ctx, state);
779
- }
780
- } catch (error) {
781
- appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
782
- updatePiUi(ctx, state);
783
- }
784
- };
785
- socket.onerror = () => socket.close();
786
- socket.onclose = () => {
787
- state.wsConnected = false;
788
- state.status = "worker Pi WebSocket disconnected";
789
- updatePiUi(ctx, state);
790
- resolve3();
791
- };
792
- });
793
- try {
794
- const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
795
- getRunPiMessagesViaServer(options.context, options.runId),
796
- getRunPiStatusViaServer(options.context, options.runId),
797
- getRunPiCommandsViaServer(options.context, options.runId)
798
- ]);
799
- const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
800
- const native = nativePiUi(ctx);
801
- if (state.nativeStream && native?.appendSessionMessages)
802
- native.appendSessionMessages(messages);
803
- else
804
- for (const message of messages)
805
- applyMessage(state, message);
806
- applyStatus(state, statusPayload);
807
- const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
808
- state.commands = commands.flatMap((command) => {
809
- const record = recordOf(command);
810
- return typeof record?.name === "string" ? [`/${record.name}`] : [];
811
- });
812
- catchupDone = true;
813
- for (const payload of buffered.splice(0))
814
- applyEnvelope(ctx, state, payload);
815
- updatePiUi(ctx, state);
816
- } catch (error) {
817
- appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
818
- catchupDone = true;
819
- updatePiUi(ctx, state);
820
- }
821
- await closePromise;
822
- }
823
- function createRemoteBashOperations(options, state, excludeFromContext) {
824
- return {
825
- exec(command, _cwd, execOptions) {
826
- return new Promise((resolve3, reject) => {
827
- const pending = {
828
- command,
829
- onData: execOptions.onData,
830
- resolve: resolve3,
831
- reject,
832
- sawChunk: false
833
- };
834
- const cleanup = () => {
835
- execOptions.signal?.removeEventListener("abort", onAbort);
836
- if (timer)
837
- clearTimeout(timer);
838
- };
839
- const onAbort = () => {
840
- cleanup();
841
- failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
842
- };
843
- const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
844
- const timer = timeoutMs > 0 ? setTimeout(() => {
845
- cleanup();
846
- failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
847
- }, timeoutMs) : null;
848
- const wrappedResolve = pending.resolve;
849
- const wrappedReject = pending.reject;
850
- pending.resolve = (result) => {
851
- cleanup();
852
- wrappedResolve(result);
853
- };
854
- pending.reject = (error) => {
855
- cleanup();
856
- wrappedReject(error);
857
- };
858
- execOptions.signal?.addEventListener("abort", onAbort, { once: true });
859
- state.pendingShells.push(pending);
860
- sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
861
- cleanup();
862
- failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
863
- });
864
- });
865
- }
866
- };
867
- }
868
- async function answerPendingUi(options, state, line) {
869
- const pending = state.pendingUi;
870
- if (!pending)
871
- return false;
872
- if (line === "/cancel") {
873
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
874
- } else if (pending.method === "confirm") {
875
- const confirmed = /^(y|yes|true|1)$/i.test(line);
876
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
877
- } else if (pending.options.length > 0 && /^\d+$/.test(line)) {
878
- const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
879
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
880
- } else {
881
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
882
- }
883
- appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
884
- state.pendingUi = null;
885
- return true;
886
- }
887
- async function routeInput(options, ctx, state, line) {
888
- const text = line.trim();
889
- if (!text)
890
- return;
891
- if (await answerPendingUi(options, state, text)) {
892
- updatePiUi(ctx, state);
893
- return;
894
- }
895
- if (text === "/detach" || text === "/quit" || text === "/q") {
896
- appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
897
- updatePiUi(ctx, state);
898
- ctx.shutdown();
899
- return;
900
- }
901
- if (text === "/stop") {
902
- await abortRunPiViaServer(options.context, options.runId);
903
- appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
904
- updatePiUi(ctx, state);
905
- ctx.shutdown();
906
- return;
907
- }
908
- if (text.startsWith("!")) {
909
- appendTranscript(state, "You", text);
910
- await sendRunPiShellViaServer(options.context, options.runId, text);
911
- } else if (text.startsWith("/")) {
912
- appendTranscript(state, "You", text);
913
- const result = await runRunPiCommandViaServer(options.context, options.runId, text);
914
- const message = typeof result.message === "string" ? result.message : "worker command accepted";
915
- appendTranscript(state, "System", message);
916
- } else {
917
- appendTranscript(state, "You", text);
918
- await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
919
- }
920
- updatePiUi(ctx, state);
921
- }
922
- function createRigWorkerPiBridgeExtension(options) {
923
- return (pi) => {
924
- const state = {
925
- transcript: [],
926
- status: "starting worker Pi daemon bridge",
927
- activity: "",
928
- cwd: "",
929
- model: "",
930
- commands: [],
931
- streaming: false,
932
- pendingUi: null,
933
- pendingShells: [],
934
- wsConnected: false,
935
- nativeStream: false
936
- };
937
- if (options.initialMessageSent)
938
- appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
939
- let nativePiUiContextAvailable = false;
940
- pi.on("user_bash", (event) => {
941
- state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
942
- return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
943
- });
944
- pi.on("session_start", async (_event, ctx) => {
945
- nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
946
- state.nativeStream = nativePiUiContextAvailable;
947
- updatePiUi(ctx, state);
948
- ctx.ui.notify(nativePiUiContextAvailable ? "Rig worker Pi native stream bridge loaded" : "Rig worker Pi bridge extension loaded (degraded widget fallback)", "info");
949
- ctx.ui.onTerminalInput((data) => {
950
- if (data.includes("\x04")) {
951
- ctx.shutdown();
952
- return { consume: true };
953
- }
954
- if (!data.includes("\r") && !data.includes(`
955
- `))
956
- return;
957
- const inlineText = data.replace(/[\r\n]+/g, "").trim();
958
- const editorText = ctx.ui.getEditorText().trim();
959
- const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
960
- if (!text)
961
- return;
962
- if (text.startsWith("!"))
963
- return;
964
- ctx.ui.setEditorText("");
965
- routeInput(options, ctx, state, text).catch((error) => {
966
- appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
967
- updatePiUi(ctx, state);
968
- });
969
- return { consume: true };
970
- });
971
- connectWorkerStream(options, ctx, state).catch((error) => {
972
- appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
973
- updatePiUi(ctx, state);
974
- });
975
- });
976
- pi.on("session_shutdown", () => {});
977
- };
978
- }
979
-
980
- // packages/cli/src/commands/_pi-frontend.ts
981
- function setTemporaryEnv(updates) {
982
- const previous = new Map;
983
- for (const [key, value] of Object.entries(updates)) {
984
- previous.set(key, process.env[key]);
985
- process.env[key] = value;
986
- }
987
- return () => {
988
- for (const [key, value] of previous) {
989
- if (value === undefined)
990
- delete process.env[key];
991
- else
992
- process.env[key] = value;
993
- }
994
- };
995
- }
996
- async function attachRunBundledPiFrontend(context, input) {
997
- const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
998
- const cwd = join(tempRoot, "workspace");
999
- const agentDir = join(tempRoot, "agent");
1000
- const sessionDir = join(tempRoot, "sessions");
1001
- const previousCwd = process.cwd();
1002
- const restoreEnv = setTemporaryEnv({
1003
- PI_CODING_AGENT_DIR: agentDir,
1004
- PI_CODING_AGENT_SESSION_DIR: sessionDir,
1005
- PI_OFFLINE: "1",
1006
- PI_SKIP_VERSION_CHECK: "1"
1007
- });
1008
- let detached = false;
1009
- try {
1010
- await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
1011
- process.chdir(cwd);
1012
- await runPiMain([
1013
- "--offline",
1014
- "--no-session",
1015
- "--no-tools",
1016
- "--no-builtin-tools",
1017
- "--no-skills",
1018
- "--no-prompt-templates",
1019
- "--no-themes",
1020
- "--no-context-files",
1021
- "--no-approve"
1022
- ], {
1023
- extensionFactories: [
1024
- createRigWorkerPiBridgeExtension({
1025
- context,
1026
- runId: input.runId,
1027
- initialMessageSent: input.steered === true
1028
- })
1029
- ]
1030
- });
1031
- detached = true;
1032
- } finally {
1033
- process.chdir(previousCwd);
1034
- restoreEnv();
1035
- rmSync(tempRoot, { recursive: true, force: true });
1036
- }
1037
- let run = { runId: input.runId, status: "unknown" };
1038
- try {
1039
- run = await getRunDetailsViaServer(context, input.runId);
1040
- } catch {}
1041
- return {
1042
- run,
1043
- logs: [],
1044
- timeline: [],
1045
- timelineCursor: null,
1046
- steered: input.steered === true,
1047
- detached,
1048
- rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
1049
- };
1050
- }
1051
-
1052
- // packages/cli/src/commands/_operator-view.ts
1053
- var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
1054
- function runStatusFromPayload(payload) {
1055
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
1056
- return String(run.status ?? "unknown").toLowerCase();
1057
- }
1058
- async function applyOperatorCommand(context, input, deps = {}) {
1059
- const line = input.line.trim();
1060
- if (!line)
1061
- return { action: "ignored" };
1062
- if (line === "/detach" || line === "/quit" || line === "/q") {
1063
- return { action: "detach", message: "Detached from run." };
1064
- }
1065
- if (line === "/stop") {
1066
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
1067
- return { action: "stopped", message: "Stop requested." };
1068
- }
1069
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
1070
- if (!userMessage)
1071
- return { action: "ignored" };
1072
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
1073
- return { action: "continue", message: "Steering message queued." };
1074
- }
1075
- async function readOperatorSnapshot(context, runId, options = {}) {
1076
- const run = await getRunDetailsViaServer(context, runId);
1077
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
1078
- const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
1079
- entries: [{
1080
- id: `timeline-unavailable:${runId}`,
1081
- type: "timeline_warning",
1082
- detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
1083
- createdAt: new Date().toISOString()
1084
- }],
1085
- nextCursor: options.timelineCursor ?? null
1086
- }));
1087
- const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
1088
- const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1089
- const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
1090
- return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
1091
- }
1092
- async function attachRunOperatorView(context, input) {
1093
- let steered = false;
1094
- if (input.message?.trim()) {
1095
- await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
1096
- steered = true;
1097
- }
1098
- if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
1099
- return attachRunBundledPiFrontend(context, {
1100
- runId: input.runId,
1101
- steered
1102
- });
1103
- }
1104
- const surface = createOperatorSurface({ interactive: input.interactive !== false });
1105
- let snapshot = await readOperatorSnapshot(context, input.runId);
1106
- if (context.outputMode === "text") {
1107
- surface.renderSnapshot(snapshot);
1108
- surface.renderTimeline(snapshot.timeline);
1109
- surface.renderLogs(snapshot.logs);
1110
- if (steered)
1111
- surface.info("Message submitted to worker Pi.");
1112
- }
1113
- let detached = false;
1114
- let commandInput = null;
1115
- if (input.follow && !input.once && context.outputMode === "text") {
1116
- if (input.interactive !== false && process.stdin.isTTY) {
1117
- surface.info("Controls: /user <message>, /stop, /detach");
1118
- commandInput = surface.attachCommandInput(async (line) => {
1119
- const result = await applyOperatorCommand(context, { runId: input.runId, line });
1120
- if (result.message)
1121
- surface.info(result.message);
1122
- if (result.action === "detach" || result.action === "stopped") {
1123
- detached = true;
1124
- commandInput?.close();
1125
- }
1126
- });
1127
- }
1128
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
1129
- let timelineCursor = snapshot.timelineCursor;
1130
- while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
1131
- await Bun.sleep(pollMs);
1132
- snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
1133
- timelineCursor = snapshot.timelineCursor;
1134
- surface.renderSnapshot(snapshot);
1135
- surface.renderTimeline(snapshot.timeline);
1136
- surface.renderLogs(snapshot.logs);
1137
- }
1138
- commandInput?.close();
1139
- }
1140
- return { ...snapshot, steered, detached };
1141
- }
1142
- export {
1143
- renderOperatorSnapshot,
1144
- createPiRunStreamRenderer,
1145
- attachRunOperatorView,
1146
- applyOperatorCommand
1147
- };