@h-rig/cli 0.0.6-alpha.22 → 0.0.6-alpha.221

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +6 -28
  2. package/package.json +9 -29
  3. package/dist/bin/build-rig-binaries.js +0 -107
  4. package/dist/bin/rig.js +0 -10655
  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 -731
  11. package/dist/src/commands/_parsers.js +0 -107
  12. package/dist/src/commands/_paths.js +0 -50
  13. package/dist/src/commands/_pi-install.js +0 -185
  14. package/dist/src/commands/_policy.js +0 -79
  15. package/dist/src/commands/_preflight.js +0 -483
  16. package/dist/src/commands/_probes.js +0 -13
  17. package/dist/src/commands/_run-driver-helpers.js +0 -289
  18. package/dist/src/commands/_server-client.js +0 -435
  19. package/dist/src/commands/_snapshot-upload.js +0 -318
  20. package/dist/src/commands/_task-picker.js +0 -76
  21. package/dist/src/commands/agent.js +0 -499
  22. package/dist/src/commands/browser.js +0 -890
  23. package/dist/src/commands/connect.js +0 -180
  24. package/dist/src/commands/dist.js +0 -402
  25. package/dist/src/commands/doctor.js +0 -517
  26. package/dist/src/commands/github.js +0 -281
  27. package/dist/src/commands/inbox.js +0 -160
  28. package/dist/src/commands/init.js +0 -1563
  29. package/dist/src/commands/inspect.js +0 -174
  30. package/dist/src/commands/inspector.js +0 -256
  31. package/dist/src/commands/plugin.js +0 -167
  32. package/dist/src/commands/profile-and-review.js +0 -178
  33. package/dist/src/commands/queue.js +0 -198
  34. package/dist/src/commands/remote.js +0 -507
  35. package/dist/src/commands/repo-git-harness.js +0 -221
  36. package/dist/src/commands/run.js +0 -1258
  37. package/dist/src/commands/server.js +0 -373
  38. package/dist/src/commands/setup.js +0 -687
  39. package/dist/src/commands/task-report-bug.js +0 -1083
  40. package/dist/src/commands/task-run-driver.js +0 -2554
  41. package/dist/src/commands/task.js +0 -1842
  42. package/dist/src/commands/test.js +0 -39
  43. package/dist/src/commands/workspace.js +0 -123
  44. package/dist/src/commands.js +0 -10334
  45. package/dist/src/index.js +0 -10673
  46. package/dist/src/launcher.js +0 -133
  47. package/dist/src/report-bug.js +0 -260
  48. package/dist/src/runner.js +0 -273
  49. package/dist/src/withMutedConsole.js +0 -42
@@ -1,731 +0,0 @@
1
- // @bun
2
- var __require = import.meta.require;
3
-
4
- // packages/cli/src/commands/_server-client.ts
5
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
6
- import { resolve as resolve2 } from "path";
7
-
8
- // packages/cli/src/runner.ts
9
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
- import { CliError } from "@rig/runtime/control-plane/errors";
11
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
12
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
13
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
14
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
16
-
17
- // packages/cli/src/commands/_server-client.ts
18
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
19
-
20
- // packages/cli/src/commands/_connection-state.ts
21
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
22
- import { homedir } from "os";
23
- import { dirname, resolve } from "path";
24
- function resolveGlobalConnectionsPath(env = process.env) {
25
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
26
- if (explicit)
27
- return resolve(explicit);
28
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
29
- if (stateDir)
30
- return resolve(stateDir, "connections.json");
31
- return resolve(homedir(), ".rig", "connections.json");
32
- }
33
- function resolveRepoConnectionPath(projectRoot) {
34
- return resolve(projectRoot, ".rig", "state", "connection.json");
35
- }
36
- function readJsonFile(path) {
37
- if (!existsSync(path))
38
- return null;
39
- try {
40
- return JSON.parse(readFileSync(path, "utf8"));
41
- } catch (error) {
42
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
43
- }
44
- }
45
- function normalizeConnection(value) {
46
- if (!value || typeof value !== "object" || Array.isArray(value))
47
- return null;
48
- const record = value;
49
- if (record.kind === "local")
50
- return { kind: "local", mode: "auto" };
51
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
52
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
53
- return { kind: "remote", baseUrl };
54
- }
55
- return null;
56
- }
57
- function readGlobalConnections(options = {}) {
58
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
59
- const payload = readJsonFile(path);
60
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
61
- return { connections: {} };
62
- }
63
- const rawConnections = payload.connections;
64
- const connections = {};
65
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
66
- for (const [alias, raw] of Object.entries(rawConnections)) {
67
- const connection = normalizeConnection(raw);
68
- if (connection)
69
- connections[alias] = connection;
70
- }
71
- }
72
- return { connections };
73
- }
74
- function readRepoConnection(projectRoot) {
75
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
76
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
77
- return null;
78
- const record = payload;
79
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
80
- if (!selected)
81
- return null;
82
- return {
83
- selected,
84
- project: typeof record.project === "string" ? record.project : undefined,
85
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
86
- };
87
- }
88
- function resolveSelectedConnection(projectRoot, options = {}) {
89
- const repo = readRepoConnection(projectRoot);
90
- if (!repo)
91
- return null;
92
- if (repo.selected === "local")
93
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
94
- const global = readGlobalConnections(options);
95
- const connection = global.connections[repo.selected];
96
- if (!connection) {
97
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
98
- }
99
- return { alias: repo.selected, connection };
100
- }
101
-
102
- // packages/cli/src/commands/_server-client.ts
103
- var scopedGitHubBearerTokens = new Map;
104
- function cleanToken(value) {
105
- const trimmed = value?.trim();
106
- return trimmed ? trimmed : null;
107
- }
108
- function readPrivateRemoteSessionToken(projectRoot) {
109
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
110
- if (!existsSync2(path))
111
- return null;
112
- try {
113
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
114
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
115
- } catch {
116
- return null;
117
- }
118
- }
119
- function readGitHubBearerTokenForRemote(projectRoot) {
120
- const scopedKey = resolve2(projectRoot);
121
- if (scopedGitHubBearerTokens.has(scopedKey))
122
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
123
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
124
- if (privateSession)
125
- return privateSession;
126
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
127
- }
128
- async function ensureServerForCli(projectRoot) {
129
- try {
130
- const selected = resolveSelectedConnection(projectRoot);
131
- if (selected?.connection.kind === "remote") {
132
- return {
133
- baseUrl: selected.connection.baseUrl,
134
- authToken: readGitHubBearerTokenForRemote(projectRoot),
135
- connectionKind: "remote"
136
- };
137
- }
138
- const connection = await ensureLocalRigServerConnection(projectRoot);
139
- return {
140
- baseUrl: connection.baseUrl,
141
- authToken: connection.authToken,
142
- connectionKind: "local"
143
- };
144
- } catch (error) {
145
- if (error instanceof Error) {
146
- throw new CliError2(error.message, 1);
147
- }
148
- throw error;
149
- }
150
- }
151
- function mergeHeaders(headers, authToken) {
152
- const merged = new Headers(headers);
153
- if (authToken) {
154
- merged.set("authorization", `Bearer ${authToken}`);
155
- }
156
- return merged;
157
- }
158
- function diagnosticMessage(payload) {
159
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
160
- return null;
161
- const record = payload;
162
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
163
- const messages = diagnostics.flatMap((entry) => {
164
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
165
- return [];
166
- const diagnostic = entry;
167
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
168
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
169
- return message ? [`${kind}: ${message}`] : [];
170
- });
171
- return messages.length > 0 ? messages.join("; ") : null;
172
- }
173
- async function requestServerJson(context, pathname, init = {}) {
174
- const server = await ensureServerForCli(context.projectRoot);
175
- const response = await fetch(`${server.baseUrl}${pathname}`, {
176
- ...init,
177
- headers: mergeHeaders(init.headers, server.authToken)
178
- });
179
- const text = await response.text();
180
- const payload = text.trim().length > 0 ? (() => {
181
- try {
182
- return JSON.parse(text);
183
- } catch {
184
- return null;
185
- }
186
- })() : null;
187
- if (!response.ok) {
188
- const diagnostics = diagnosticMessage(payload);
189
- const detail = diagnostics ?? (text || response.statusText);
190
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
191
- }
192
- return payload;
193
- }
194
- async function getRunDetailsViaServer(context, runId) {
195
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
196
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
197
- }
198
- async function getRunLogsViaServer(context, runId, options = {}) {
199
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
200
- if (options.limit !== undefined)
201
- url.searchParams.set("limit", String(options.limit));
202
- if (options.cursor)
203
- url.searchParams.set("cursor", options.cursor);
204
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
205
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
206
- }
207
- async function getRunTimelineViaServer(context, runId, options = {}) {
208
- const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
209
- if (options.limit !== undefined)
210
- url.searchParams.set("limit", String(options.limit));
211
- if (options.cursor)
212
- url.searchParams.set("cursor", options.cursor);
213
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
214
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
215
- }
216
- async function stopRunViaServer(context, runId) {
217
- const payload = await requestServerJson(context, "/api/runs/stop", {
218
- method: "POST",
219
- headers: { "content-type": "application/json" },
220
- body: JSON.stringify({ runId })
221
- });
222
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
223
- }
224
- async function steerRunViaServer(context, runId, message) {
225
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
226
- method: "POST",
227
- headers: { "content-type": "application/json" },
228
- body: JSON.stringify({ message })
229
- });
230
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
231
- }
232
-
233
- // packages/cli/src/commands/_operator-surface.ts
234
- import { createInterface } from "readline";
235
- var CANONICAL_STAGES = [
236
- "Connect",
237
- "GitHub/task sync",
238
- "Prepare workspace",
239
- "Launch Pi",
240
- "Plan",
241
- "Implement",
242
- "Validate",
243
- "Commit",
244
- "Open PR",
245
- "Review/CI",
246
- "Merge",
247
- "Complete"
248
- ];
249
- function logDetail(log) {
250
- return typeof log.detail === "string" ? log.detail.trim() : "";
251
- }
252
- function parseProviderProtocolLog(title, detail) {
253
- if (title.trim().toLowerCase() !== "agent output")
254
- return null;
255
- if (!detail.startsWith("{") || !detail.endsWith("}"))
256
- return null;
257
- try {
258
- const record = JSON.parse(detail);
259
- if (!record || typeof record !== "object" || Array.isArray(record))
260
- return null;
261
- const type = record.type;
262
- return typeof type === "string" && [
263
- "assistant",
264
- "message_start",
265
- "message_update",
266
- "message_end",
267
- "stream_event",
268
- "tool_result",
269
- "tool_execution_start",
270
- "tool_execution_update",
271
- "tool_execution_end",
272
- "turn_start",
273
- "turn_end"
274
- ].includes(type) ? record : null;
275
- } catch {
276
- return null;
277
- }
278
- }
279
- function renderProviderProtocolLog(record) {
280
- const type = typeof record.type === "string" ? record.type : "";
281
- if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
282
- const toolName = String(record.toolName ?? record.name ?? "tool");
283
- 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";
284
- return `[Pi tool] ${toolName} ${status}`;
285
- }
286
- return null;
287
- }
288
- function entryId(entry, fallback) {
289
- return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
290
- }
291
- function renderOperatorSnapshot(snapshot) {
292
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
293
- const runId = String(run.runId ?? run.id ?? "run");
294
- const status = String(run.status ?? "unknown");
295
- const logs = snapshot.logs ?? [];
296
- const latestByStage = new Map;
297
- for (const log of logs) {
298
- const title = String(log.title ?? "").toLowerCase();
299
- const stageName = String(log.stage ?? "").toLowerCase();
300
- const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
301
- if (stage)
302
- latestByStage.set(stage, log);
303
- }
304
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
305
- const match = latestByStage.get(stage);
306
- return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
307
- });
308
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
309
- `);
310
- }
311
- function createPiRunStreamRenderer(output = process.stdout) {
312
- let lastSnapshot = "";
313
- const assistantTextById = new Map;
314
- const seenTimeline = new Set;
315
- const seenLogs = new Set;
316
- const writeLine = (line) => output.write(`${line}
317
- `);
318
- return {
319
- renderSnapshot(snapshot) {
320
- const rendered = renderOperatorSnapshot(snapshot);
321
- if (rendered && rendered !== lastSnapshot) {
322
- writeLine(rendered);
323
- lastSnapshot = rendered;
324
- }
325
- },
326
- renderTimeline(entries) {
327
- for (const [index, entry] of entries.entries()) {
328
- const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
329
- if (entry.type === "assistant_message" && typeof entry.text === "string") {
330
- const text = entry.text;
331
- const previousText = assistantTextById.get(id) ?? "";
332
- if (!previousText && text.trim()) {
333
- writeLine("[Pi assistant]");
334
- }
335
- if (text.startsWith(previousText)) {
336
- const delta = text.slice(previousText.length);
337
- if (delta)
338
- output.write(delta);
339
- } else if (text.trim() && text !== previousText) {
340
- if (previousText)
341
- writeLine(`
342
- [Pi assistant]`);
343
- output.write(text);
344
- }
345
- assistantTextById.set(id, text);
346
- continue;
347
- }
348
- if (seenTimeline.has(id))
349
- continue;
350
- seenTimeline.add(id);
351
- if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
352
- writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
353
- continue;
354
- }
355
- if (entry.type === "timeline_warning") {
356
- writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
357
- }
358
- }
359
- },
360
- renderLogs(entries) {
361
- for (const [index, entry] of entries.entries()) {
362
- const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
363
- if (seenLogs.has(id))
364
- continue;
365
- seenLogs.add(id);
366
- const title = String(entry.title ?? "");
367
- if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
368
- continue;
369
- const detail = logDetail(entry);
370
- if (!detail)
371
- continue;
372
- const protocolRecord = parseProviderProtocolLog(title, detail);
373
- if (protocolRecord) {
374
- const protocolLine = renderProviderProtocolLog(protocolRecord);
375
- if (protocolLine)
376
- writeLine(protocolLine);
377
- continue;
378
- }
379
- writeLine(`[${title || "Rig log"}] ${detail}`);
380
- }
381
- }
382
- };
383
- }
384
- function createOperatorSurface(options = {}) {
385
- const input = options.input ?? process.stdin;
386
- const output = options.output ?? process.stdout;
387
- const errorOutput = options.errorOutput ?? process.stderr;
388
- const renderer = createPiRunStreamRenderer(output);
389
- const writeLine = (line) => output.write(`${line}
390
- `);
391
- return {
392
- mode: "pi-compatible-text",
393
- ...renderer,
394
- info: writeLine,
395
- error: (message) => errorOutput.write(`${message}
396
- `),
397
- attachCommandInput(handler) {
398
- if (options.interactive === false || !input.isTTY)
399
- return null;
400
- const rl = createInterface({ input, output: process.stdout, terminal: false });
401
- rl.on("line", (line) => {
402
- Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
403
- });
404
- return { close: () => rl.close() };
405
- }
406
- };
407
- }
408
-
409
- // packages/cli/src/commands/_operator-view.ts
410
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
411
- var CANONICAL_STAGES2 = [
412
- "Connect",
413
- "GitHub/task sync",
414
- "Prepare workspace",
415
- "Launch Pi",
416
- "Plan",
417
- "Implement",
418
- "Validate",
419
- "Commit",
420
- "Open PR",
421
- "Review/CI",
422
- "Merge",
423
- "Complete"
424
- ];
425
- var GREEN = "\x1B[32m";
426
- var BLUE = "\x1B[34m";
427
- var MAGENTA = "\x1B[35m";
428
- var YELLOW = "\x1B[33m";
429
- var RED = "\x1B[31m";
430
- var DIM = "\x1B[2m";
431
- var BOLD = "\x1B[1m";
432
- var RESET = "\x1B[0m";
433
- async function loadPiTuiRuntime() {
434
- try {
435
- return await import("@earendil-works/pi-tui");
436
- } catch {
437
- const base = new URL("../../../pi/packages/tui/src/", import.meta.url);
438
- const [tui, input, terminal, keys, utils] = await Promise.all([
439
- import(new URL("tui.ts", base).href),
440
- import(new URL("components/input.ts", base).href),
441
- import(new URL("terminal.ts", base).href),
442
- import(new URL("keys.ts", base).href),
443
- import(new URL("utils.ts", base).href)
444
- ]);
445
- return {
446
- Container: tui.Container,
447
- TUI: tui.TUI,
448
- Input: input.Input,
449
- ProcessTerminal: terminal.ProcessTerminal,
450
- matchesKey: keys.matchesKey,
451
- truncateToWidth: utils.truncateToWidth
452
- };
453
- }
454
- }
455
- function runStatusFromPayload(payload) {
456
- const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
457
- return String(run.status ?? "unknown").toLowerCase();
458
- }
459
- async function applyOperatorCommand(context, input, deps = {}) {
460
- const line = input.line.trim();
461
- if (!line)
462
- return { action: "ignored" };
463
- if (line === "/detach" || line === "/quit" || line === "/q") {
464
- return { action: "detach", message: "Detached from run." };
465
- }
466
- if (line === "/stop") {
467
- await (deps.stop ?? stopRunViaServer)(context, input.runId);
468
- return { action: "stopped", message: "Stop requested." };
469
- }
470
- const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
471
- if (!userMessage)
472
- return { action: "ignored" };
473
- await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
474
- return { action: "continue", message: "Steering message queued." };
475
- }
476
- async function readOperatorSnapshot(context, runId, options = {}) {
477
- const run = await getRunDetailsViaServer(context, runId);
478
- const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
479
- const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
480
- entries: [{
481
- id: `timeline-unavailable:${runId}`,
482
- type: "timeline_warning",
483
- detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
484
- createdAt: new Date().toISOString()
485
- }],
486
- nextCursor: options.timelineCursor ?? null
487
- }));
488
- const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
489
- const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
490
- const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
491
- return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
492
- }
493
- function unwrapRun(runPayload) {
494
- return runPayload.run && typeof runPayload.run === "object" && !Array.isArray(runPayload.run) ? runPayload.run : runPayload;
495
- }
496
- function logDetail2(log) {
497
- return typeof log.detail === "string" ? log.detail.trim() : "";
498
- }
499
- function logTitle(log) {
500
- return typeof log.title === "string" ? log.title.trim() : "";
501
- }
502
- function renderAssistantTextFromTimeline(entries) {
503
- const assistant = entries.filter((entry) => entry.type === "assistant_message" && typeof entry.text === "string").at(-1);
504
- const text = typeof assistant?.text === "string" ? assistant.text.trimEnd() : "";
505
- if (!text)
506
- return [];
507
- return [`${BLUE}${BOLD}Remote Pi assistant${RESET}`, ...text.split(/\r?\n/).slice(-18)];
508
- }
509
- function renderToolLines(entries) {
510
- return entries.filter((entry) => entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call").slice(-8).map((entry) => `${DIM}[tool]${RESET} ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
511
- }
512
- function renderStageLines(logs) {
513
- const latestByStage = new Map;
514
- for (const log of logs) {
515
- const title = logTitle(log).toLowerCase();
516
- const stageName = String(log.stage ?? "").toLowerCase();
517
- const stage = CANONICAL_STAGES2.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
518
- if (stage)
519
- latestByStage.set(stage, log);
520
- }
521
- return CANONICAL_STAGES2.map((stage) => {
522
- const log = latestByStage.get(stage);
523
- const status = String(log?.status ?? "pending");
524
- const detail = log ? logDetail2(log) : "";
525
- const color = status === "completed" ? GREEN : status === "failed" || status === "rejected" ? RED : status === "pending" ? DIM : YELLOW;
526
- const mark = status === "completed" ? "\u2713" : status === "pending" ? "\xB7" : status === "failed" ? "\u2717" : "\u25B6";
527
- return `${color}${mark} ${stage}${RESET}${detail ? ` ${DIM}\u2014 ${detail.slice(0, 140)}${RESET}` : ""}`;
528
- });
529
- }
530
- function renderEventLines(logs) {
531
- return logs.filter((log) => !CANONICAL_STAGES2.some((stage) => stage.toLowerCase() === logTitle(log).toLowerCase())).slice(-12).flatMap((log) => {
532
- const title = logTitle(log) || "Rig event";
533
- const detail = logDetail2(log);
534
- if (!detail)
535
- return [];
536
- const tone = String(log.tone ?? "");
537
- const color = tone === "error" ? RED : tone === "tool" ? MAGENTA : DIM;
538
- return [`${color}[${title}]${RESET} ${detail.slice(0, 220)}`];
539
- });
540
- }
541
-
542
- class RigRunComponent {
543
- truncateToWidth;
544
- snapshot = { run: {}, logs: [], timeline: [] };
545
- localEvents = [];
546
- constructor(truncateToWidth) {
547
- this.truncateToWidth = truncateToWidth;
548
- }
549
- update(snapshot) {
550
- this.snapshot = snapshot;
551
- }
552
- addLocalEvent(message) {
553
- this.localEvents.push(`${new Date().toLocaleTimeString()} ${message}`);
554
- this.localEvents = this.localEvents.slice(-8);
555
- }
556
- invalidate() {}
557
- render(width) {
558
- const run = unwrapRun(this.snapshot.run);
559
- const runId = String(run.runId ?? run.id ?? "run");
560
- const status = String(run.status ?? "unknown");
561
- const worker = typeof run.worktreePath === "string" && run.worktreePath.trim() ? run.worktreePath.trim() : typeof run.projectRoot === "string" && run.projectRoot.trim() ? run.projectRoot.trim() : "worker workspace pending";
562
- const lines = [
563
- `${BOLD}Rig Pi frontend${RESET} ${DIM}(local Pi TUI \u2192 Rig server \u2192 worker Pi backend)${RESET}`,
564
- `${BOLD}${runId}${RESET} \xB7 ${status} \xB7 ${DIM}${worker}${RESET}`,
565
- "",
566
- `${BOLD}Rig flow${RESET}`,
567
- ...renderStageLines(this.snapshot.logs ?? []),
568
- "",
569
- ...renderAssistantTextFromTimeline(this.snapshot.timeline ?? []),
570
- ...renderToolLines(this.snapshot.timeline ?? []),
571
- "",
572
- `${BOLD}Rig / Pi events${RESET}`,
573
- ...renderEventLines(this.snapshot.logs ?? []),
574
- ...this.localEvents.map((event) => `${GREEN}[frontend]${RESET} ${event}`),
575
- ""
576
- ];
577
- return lines.slice(-42).map((line) => this.truncateToWidth(line, Math.max(10, width)));
578
- }
579
- }
580
-
581
- class RigInputComponent {
582
- matchesKey;
583
- truncateToWidth;
584
- input;
585
- status = "Type text, /skill:..., or remote Pi slash commands. Local: /stop /detach.";
586
- constructor(InputCtor, matchesKey, truncateToWidth, onSubmit, onEscape) {
587
- this.matchesKey = matchesKey;
588
- this.truncateToWidth = truncateToWidth;
589
- this.input = new InputCtor;
590
- this.input.onSubmit = (value) => {
591
- const text = value.trim();
592
- this.input.setValue("");
593
- if (text)
594
- Promise.resolve(onSubmit(text));
595
- };
596
- this.input.onEscape = onEscape;
597
- }
598
- handleInput(data) {
599
- if (this.matchesKey(data, "ctrl+d")) {
600
- this.input.onEscape?.();
601
- return;
602
- }
603
- this.input.handleInput?.(data);
604
- }
605
- setStatus(status) {
606
- this.status = status;
607
- }
608
- invalidate() {
609
- this.input.invalidate();
610
- }
611
- render(width) {
612
- return [
613
- `${DIM}${this.truncateToWidth(this.status, Math.max(10, width))}${RESET}`,
614
- `${GREEN}${BOLD}You \u2192 worker Pi:${RESET}`,
615
- ...this.input.render(width)
616
- ];
617
- }
618
- }
619
- async function attachRunPiTuiFrontend(context, input) {
620
- const piTui = await loadPiTuiRuntime();
621
- const terminal = new piTui.ProcessTerminal;
622
- const tui = new piTui.TUI(terminal);
623
- const root = new piTui.Container;
624
- const runView = new RigRunComponent(piTui.truncateToWidth);
625
- let detached = false;
626
- let steered = input.steered === true;
627
- let latest = await readOperatorSnapshot(context, input.runId);
628
- let timelineCursor = latest.timelineCursor;
629
- runView.update(latest);
630
- if (steered)
631
- runView.addLocalEvent("initial message queued to worker Pi.");
632
- const stop = () => {
633
- detached = true;
634
- tui.stop();
635
- };
636
- const inputView = new RigInputComponent(piTui.Input, piTui.matchesKey, piTui.truncateToWidth, async (line) => {
637
- if (line === "/detach" || line === "/quit" || line === "/q") {
638
- runView.addLocalEvent("detached from run.");
639
- stop();
640
- return;
641
- }
642
- if (line === "/stop") {
643
- await stopRunViaServer(context, input.runId);
644
- runView.addLocalEvent("stop requested.");
645
- stop();
646
- return;
647
- }
648
- await steerRunViaServer(context, input.runId, line);
649
- steered = true;
650
- runView.addLocalEvent(`queued to worker Pi: ${line.slice(0, 160)}`);
651
- tui.requestRender();
652
- }, stop);
653
- root.addChild(runView);
654
- root.addChild(inputView);
655
- tui.addChild(root);
656
- tui.setFocus(inputView.input);
657
- tui.start();
658
- tui.requestRender(true);
659
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 1000));
660
- try {
661
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(latest.run))) {
662
- await Bun.sleep(pollMs);
663
- latest = await readOperatorSnapshot(context, input.runId, { timelineCursor });
664
- timelineCursor = latest.timelineCursor;
665
- runView.update(latest);
666
- inputView.setStatus(`Remote worker ${runStatusFromPayload(latest.run)}. Input is forwarded to worker Pi; /stop /detach are local controls.`);
667
- tui.requestRender();
668
- }
669
- } finally {
670
- if (!detached)
671
- tui.stop();
672
- }
673
- return { ...latest, timelineCursor, steered, detached, rendered: renderOperatorSnapshot(latest) };
674
- }
675
- async function attachRunOperatorView(context, input) {
676
- let steered = false;
677
- if (input.message?.trim()) {
678
- await steerRunViaServer(context, input.runId, input.message.trim());
679
- steered = true;
680
- }
681
- if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
682
- return attachRunPiTuiFrontend(context, {
683
- runId: input.runId,
684
- pollMs: input.pollMs,
685
- steered
686
- });
687
- }
688
- const surface = createOperatorSurface({ interactive: input.interactive !== false });
689
- let snapshot = await readOperatorSnapshot(context, input.runId);
690
- if (context.outputMode === "text") {
691
- surface.renderSnapshot(snapshot);
692
- surface.renderTimeline(snapshot.timeline);
693
- surface.renderLogs(snapshot.logs);
694
- if (steered)
695
- surface.info("Steering message queued.");
696
- }
697
- let detached = false;
698
- let commandInput = null;
699
- if (input.follow && !input.once && context.outputMode === "text") {
700
- if (input.interactive !== false && process.stdin.isTTY) {
701
- surface.info("Controls: /user <message>, /stop, /detach");
702
- commandInput = surface.attachCommandInput(async (line) => {
703
- const result = await applyOperatorCommand(context, { runId: input.runId, line });
704
- if (result.message)
705
- surface.info(result.message);
706
- if (result.action === "detach" || result.action === "stopped") {
707
- detached = true;
708
- commandInput?.close();
709
- }
710
- });
711
- }
712
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
713
- let timelineCursor = snapshot.timelineCursor;
714
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
715
- await Bun.sleep(pollMs);
716
- snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
717
- timelineCursor = snapshot.timelineCursor;
718
- surface.renderSnapshot(snapshot);
719
- surface.renderTimeline(snapshot.timeline);
720
- surface.renderLogs(snapshot.logs);
721
- }
722
- commandInput?.close();
723
- }
724
- return { ...snapshot, steered, detached };
725
- }
726
- export {
727
- renderOperatorSnapshot,
728
- createPiRunStreamRenderer,
729
- attachRunOperatorView,
730
- applyOperatorCommand
731
- };