@h-rig/cli 0.0.6-alpha.22 → 0.0.6-alpha.24
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.
- package/dist/bin/rig.js +951 -494
- package/dist/src/commands/_operator-view.js +644 -228
- package/dist/src/commands/_pi-frontend.js +843 -0
- package/dist/src/commands/_pi-worker-bridge-extension.js +761 -0
- package/dist/src/commands/_preflight.js +1 -81
- package/dist/src/commands/_server-client.js +80 -1
- package/dist/src/commands/run.js +644 -228
- package/dist/src/commands/task-run-driver.js +51 -5
- package/dist/src/commands/task.js +648 -312
- package/dist/src/commands.js +951 -494
- package/dist/src/index.js +951 -494
- package/package.json +6 -6
package/dist/src/commands/run.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var __require = import.meta.require;
|
|
3
|
-
|
|
4
2
|
// packages/cli/src/commands/run.ts
|
|
5
3
|
import { createInterface as createInterface2 } from "readline/promises";
|
|
6
4
|
|
|
@@ -307,6 +305,66 @@ async function steerRunViaServer(context, runId, message) {
|
|
|
307
305
|
});
|
|
308
306
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
309
307
|
}
|
|
308
|
+
async function getRunPiSessionViaServer(context, runId) {
|
|
309
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
310
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
311
|
+
}
|
|
312
|
+
async function getRunPiMessagesViaServer(context, runId) {
|
|
313
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
314
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
315
|
+
}
|
|
316
|
+
async function getRunPiStatusViaServer(context, runId) {
|
|
317
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
318
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
319
|
+
}
|
|
320
|
+
async function getRunPiCommandsViaServer(context, runId) {
|
|
321
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
322
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
323
|
+
}
|
|
324
|
+
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
325
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
326
|
+
method: "POST",
|
|
327
|
+
headers: { "content-type": "application/json" },
|
|
328
|
+
body: JSON.stringify({ text, streamingBehavior })
|
|
329
|
+
});
|
|
330
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
331
|
+
}
|
|
332
|
+
async function sendRunPiShellViaServer(context, runId, text) {
|
|
333
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
334
|
+
method: "POST",
|
|
335
|
+
headers: { "content-type": "application/json" },
|
|
336
|
+
body: JSON.stringify({ text })
|
|
337
|
+
});
|
|
338
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
339
|
+
}
|
|
340
|
+
async function runRunPiCommandViaServer(context, runId, text) {
|
|
341
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
342
|
+
method: "POST",
|
|
343
|
+
headers: { "content-type": "application/json" },
|
|
344
|
+
body: JSON.stringify({ text })
|
|
345
|
+
});
|
|
346
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
347
|
+
}
|
|
348
|
+
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
349
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
350
|
+
method: "POST",
|
|
351
|
+
headers: { "content-type": "application/json" },
|
|
352
|
+
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
353
|
+
});
|
|
354
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
355
|
+
}
|
|
356
|
+
async function abortRunPiViaServer(context, runId) {
|
|
357
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
358
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
359
|
+
}
|
|
360
|
+
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
361
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
362
|
+
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
363
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
364
|
+
if (server.authToken)
|
|
365
|
+
url.searchParams.set("token", server.authToken);
|
|
366
|
+
return url.toString();
|
|
367
|
+
}
|
|
310
368
|
|
|
311
369
|
// packages/cli/src/commands/_operator-surface.ts
|
|
312
370
|
import { createInterface } from "readline";
|
|
@@ -484,52 +542,593 @@ function createOperatorSurface(options = {}) {
|
|
|
484
542
|
};
|
|
485
543
|
}
|
|
486
544
|
|
|
487
|
-
// packages/cli/src/commands/
|
|
545
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
546
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
547
|
+
import { tmpdir } from "os";
|
|
548
|
+
import { join } from "path";
|
|
549
|
+
import { main as runPiMain } from "@earendil-works/pi-coding-agent";
|
|
550
|
+
|
|
551
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
488
552
|
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
489
|
-
var
|
|
490
|
-
|
|
491
|
-
"
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
"
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
"
|
|
499
|
-
|
|
500
|
-
"Merge",
|
|
501
|
-
"Complete"
|
|
502
|
-
];
|
|
503
|
-
var GREEN = "\x1B[32m";
|
|
504
|
-
var BLUE = "\x1B[34m";
|
|
505
|
-
var MAGENTA = "\x1B[35m";
|
|
506
|
-
var YELLOW = "\x1B[33m";
|
|
507
|
-
var RED = "\x1B[31m";
|
|
508
|
-
var DIM = "\x1B[2m";
|
|
509
|
-
var BOLD = "\x1B[1m";
|
|
510
|
-
var RESET = "\x1B[0m";
|
|
511
|
-
async function loadPiTuiRuntime() {
|
|
553
|
+
var MAX_TRANSCRIPT_LINES = 120;
|
|
554
|
+
function recordOf(value) {
|
|
555
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
556
|
+
}
|
|
557
|
+
function asText(value) {
|
|
558
|
+
if (typeof value === "string")
|
|
559
|
+
return value;
|
|
560
|
+
if (value === null || value === undefined)
|
|
561
|
+
return "";
|
|
562
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
563
|
+
return String(value);
|
|
512
564
|
try {
|
|
513
|
-
return
|
|
565
|
+
return JSON.stringify(value);
|
|
514
566
|
} catch {
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
567
|
+
return String(value);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function textFromContent(content) {
|
|
571
|
+
if (typeof content === "string")
|
|
572
|
+
return content;
|
|
573
|
+
if (!Array.isArray(content))
|
|
574
|
+
return asText(content);
|
|
575
|
+
return content.flatMap((part) => {
|
|
576
|
+
const item = recordOf(part);
|
|
577
|
+
if (!item)
|
|
578
|
+
return [];
|
|
579
|
+
if (typeof item.text === "string")
|
|
580
|
+
return [item.text];
|
|
581
|
+
if (typeof item.content === "string")
|
|
582
|
+
return [item.content];
|
|
583
|
+
if (item.type === "toolCall")
|
|
584
|
+
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
585
|
+
if (item.type === "toolResult")
|
|
586
|
+
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
587
|
+
return [];
|
|
588
|
+
}).join(`
|
|
589
|
+
`);
|
|
590
|
+
}
|
|
591
|
+
function appendTranscript(state, label, text) {
|
|
592
|
+
const trimmed = text.trimEnd();
|
|
593
|
+
if (!trimmed)
|
|
594
|
+
return;
|
|
595
|
+
const lines = trimmed.split(/\r?\n/);
|
|
596
|
+
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
597
|
+
for (const line of lines.slice(1))
|
|
598
|
+
state.transcript.push(` ${line}`);
|
|
599
|
+
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
600
|
+
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
function nativePiUi(ctx) {
|
|
604
|
+
const ui = ctx.ui;
|
|
605
|
+
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
606
|
+
}
|
|
607
|
+
function syncNativeDisplayCwd(ctx, state) {
|
|
608
|
+
const ui = nativePiUi(ctx);
|
|
609
|
+
if (ui?.setDisplayCwd && state.cwd)
|
|
610
|
+
ui.setDisplayCwd(state.cwd);
|
|
611
|
+
}
|
|
612
|
+
function parseExtensionUiRequest(value) {
|
|
613
|
+
const request = recordOf(value) ?? {};
|
|
614
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
615
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
616
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
617
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
618
|
+
const options = rawOptions.map((option) => {
|
|
619
|
+
const record = recordOf(option);
|
|
620
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
621
|
+
}).filter(Boolean);
|
|
622
|
+
return { requestId, method, prompt, options };
|
|
623
|
+
}
|
|
624
|
+
function renderBridgeWidget(state) {
|
|
625
|
+
const statusParts = [
|
|
626
|
+
state.wsConnected ? "live WS" : "WS pending",
|
|
627
|
+
state.status,
|
|
628
|
+
state.model,
|
|
629
|
+
state.cwd
|
|
630
|
+
].filter(Boolean);
|
|
631
|
+
const lines = [`Worker Pi daemon bridge \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
632
|
+
if (state.activity)
|
|
633
|
+
lines.push(state.activity);
|
|
634
|
+
if (state.commands.length > 0) {
|
|
635
|
+
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
636
|
+
}
|
|
637
|
+
lines.push("");
|
|
638
|
+
if (state.transcript.length > 0) {
|
|
639
|
+
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
640
|
+
} else {
|
|
641
|
+
lines.push("Waiting for worker Pi daemon transcript\u2026");
|
|
642
|
+
}
|
|
643
|
+
if (state.pendingUi) {
|
|
644
|
+
lines.push("");
|
|
645
|
+
lines.push(`Extension UI request \xB7 ${state.pendingUi.method}`);
|
|
646
|
+
lines.push(state.pendingUi.prompt);
|
|
647
|
+
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
648
|
+
lines.push("Reply in the Pi editor. /cancel cancels this request.");
|
|
649
|
+
}
|
|
650
|
+
return lines;
|
|
651
|
+
}
|
|
652
|
+
function updatePiUi(ctx, state) {
|
|
653
|
+
ctx.ui.setTitle("Pi \xB7 Rig worker daemon");
|
|
654
|
+
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker Pi WS live" : state.status);
|
|
655
|
+
syncNativeDisplayCwd(ctx, state);
|
|
656
|
+
if (state.nativeStream && nativePiUi(ctx)) {
|
|
657
|
+
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
ctx.ui.setWorkingVisible(false);
|
|
661
|
+
ctx.ui.setWidget("rig-worker-pi-transcript", [`Worker Pi daemon bridge \xB7 degraded widget transcript`, ...renderBridgeWidget(state)], { placement: "aboveEditor" });
|
|
662
|
+
}
|
|
663
|
+
function applyStatus(state, payload) {
|
|
664
|
+
const status = recordOf(payload.status) ?? payload;
|
|
665
|
+
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
666
|
+
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
667
|
+
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
668
|
+
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
669
|
+
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
670
|
+
}
|
|
671
|
+
function applyMessage(state, message) {
|
|
672
|
+
const record = recordOf(message);
|
|
673
|
+
if (!record)
|
|
674
|
+
return;
|
|
675
|
+
const role = String(record.role ?? "system");
|
|
676
|
+
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
677
|
+
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
678
|
+
}
|
|
679
|
+
function applyPiEvent(ctx, state, eventValue) {
|
|
680
|
+
const event = recordOf(eventValue);
|
|
681
|
+
if (!event)
|
|
682
|
+
return;
|
|
683
|
+
const type = String(event.type ?? "event");
|
|
684
|
+
if (type === "agent_start") {
|
|
685
|
+
state.streaming = true;
|
|
686
|
+
state.status = "streaming";
|
|
687
|
+
} else if (type === "agent_end") {
|
|
688
|
+
state.streaming = false;
|
|
689
|
+
state.status = "idle";
|
|
690
|
+
} else if (type === "queue_update") {
|
|
691
|
+
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
692
|
+
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
693
|
+
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
694
|
+
}
|
|
695
|
+
const native = nativePiUi(ctx);
|
|
696
|
+
if (state.nativeStream && native?.emitSessionEvent) {
|
|
697
|
+
native.emitSessionEvent(eventValue);
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
if (type === "agent_end") {
|
|
701
|
+
appendTranscript(state, "System", "Agent turn complete.");
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
705
|
+
applyMessage(state, event.message);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (type === "message_update") {
|
|
709
|
+
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
710
|
+
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
711
|
+
if (delta)
|
|
712
|
+
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (type === "tool_execution_start") {
|
|
716
|
+
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
if (type === "tool_execution_update") {
|
|
720
|
+
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
if (type === "tool_execution_end") {
|
|
724
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
function firstPendingShell(state) {
|
|
728
|
+
return state.pendingShells[0];
|
|
729
|
+
}
|
|
730
|
+
function finishPendingShell(state, shell, result) {
|
|
731
|
+
const index = state.pendingShells.indexOf(shell);
|
|
732
|
+
if (index !== -1)
|
|
733
|
+
state.pendingShells.splice(index, 1);
|
|
734
|
+
shell.resolve(result);
|
|
735
|
+
}
|
|
736
|
+
function failPendingShell(state, shell, error) {
|
|
737
|
+
const index = state.pendingShells.indexOf(shell);
|
|
738
|
+
if (index !== -1)
|
|
739
|
+
state.pendingShells.splice(index, 1);
|
|
740
|
+
shell.reject(error);
|
|
741
|
+
}
|
|
742
|
+
function applyUiEvent(state, value) {
|
|
743
|
+
const event = recordOf(value);
|
|
744
|
+
if (!event)
|
|
745
|
+
return;
|
|
746
|
+
const type = String(event.type ?? "ui");
|
|
747
|
+
if (type === "shell.chunk") {
|
|
748
|
+
const pending = firstPendingShell(state);
|
|
749
|
+
const chunk = asText(event.chunk);
|
|
750
|
+
if (pending) {
|
|
751
|
+
pending.sawChunk = true;
|
|
752
|
+
pending.onData(Buffer.from(chunk));
|
|
753
|
+
} else {
|
|
754
|
+
appendTranscript(state, "Tool", chunk);
|
|
755
|
+
}
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
if (type === "shell.end") {
|
|
759
|
+
const pending = firstPendingShell(state);
|
|
760
|
+
const output = asText(event.output ?? "");
|
|
761
|
+
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
762
|
+
if (pending) {
|
|
763
|
+
if (output && !pending.sawChunk)
|
|
764
|
+
pending.onData(Buffer.from(output));
|
|
765
|
+
finishPendingShell(state, pending, { exitCode });
|
|
766
|
+
} else {
|
|
767
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
768
|
+
}
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
if (type === "shell.start") {
|
|
772
|
+
if (!firstPendingShell(state))
|
|
773
|
+
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
777
|
+
}
|
|
778
|
+
function applyEnvelope(ctx, state, envelopeValue) {
|
|
779
|
+
const envelope = recordOf(envelopeValue);
|
|
780
|
+
if (!envelope)
|
|
781
|
+
return;
|
|
782
|
+
const type = String(envelope.type ?? "");
|
|
783
|
+
if (type === "ready") {
|
|
784
|
+
const metadata = recordOf(envelope.metadata);
|
|
785
|
+
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
786
|
+
state.status = "worker Pi daemon ready";
|
|
787
|
+
if (!state.nativeStream)
|
|
788
|
+
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
789
|
+
} else if (type === "status.update") {
|
|
790
|
+
applyStatus(state, envelope);
|
|
791
|
+
} else if (type === "activity.update") {
|
|
792
|
+
const activity = recordOf(envelope.activity);
|
|
793
|
+
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
794
|
+
} else if (type === "extension_ui_request") {
|
|
795
|
+
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
796
|
+
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
797
|
+
} else if (type === "pi.ui_event") {
|
|
798
|
+
applyUiEvent(state, envelope.event);
|
|
799
|
+
} else if (type === "pi.event") {
|
|
800
|
+
applyPiEvent(ctx, state, envelope.event);
|
|
801
|
+
} else if (type === "error") {
|
|
802
|
+
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
803
|
+
}
|
|
804
|
+
syncNativeDisplayCwd(ctx, state);
|
|
805
|
+
}
|
|
806
|
+
async function waitForWorkerReady(options, ctx, state) {
|
|
807
|
+
while (true) {
|
|
808
|
+
const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => ({
|
|
809
|
+
ready: false,
|
|
810
|
+
status: error instanceof Error ? error.message : String(error),
|
|
811
|
+
retryAfterMs: 1000
|
|
812
|
+
}));
|
|
813
|
+
if (session.ready === false) {
|
|
814
|
+
const status = String(session.status ?? "starting");
|
|
815
|
+
state.status = `waiting for worker Pi daemon \xB7 ${status}`;
|
|
816
|
+
updatePiUi(ctx, state);
|
|
817
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
818
|
+
appendTranscript(state, "Error", `Run ended before worker Pi daemon became ready: ${status}`);
|
|
819
|
+
return false;
|
|
820
|
+
}
|
|
821
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
const sessionRecord = recordOf(session) ?? {};
|
|
825
|
+
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
826
|
+
updatePiUi(ctx, state);
|
|
827
|
+
return true;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
function parseWsPayload(message) {
|
|
831
|
+
if (typeof message.data === "string")
|
|
832
|
+
return JSON.parse(message.data);
|
|
833
|
+
return JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
834
|
+
}
|
|
835
|
+
async function connectWorkerStream(options, ctx, state) {
|
|
836
|
+
const ready = await waitForWorkerReady(options, ctx, state);
|
|
837
|
+
if (!ready)
|
|
838
|
+
return;
|
|
839
|
+
let catchupDone = false;
|
|
840
|
+
const buffered = [];
|
|
841
|
+
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
842
|
+
const socket = new WebSocket(wsUrl);
|
|
843
|
+
const closePromise = new Promise((resolve3) => {
|
|
844
|
+
socket.onopen = () => {
|
|
845
|
+
state.wsConnected = true;
|
|
846
|
+
state.status = "live worker Pi WebSocket connected";
|
|
847
|
+
updatePiUi(ctx, state);
|
|
848
|
+
};
|
|
849
|
+
socket.onmessage = (message) => {
|
|
850
|
+
try {
|
|
851
|
+
const payload = parseWsPayload(message);
|
|
852
|
+
if (!catchupDone)
|
|
853
|
+
buffered.push(payload);
|
|
854
|
+
else {
|
|
855
|
+
applyEnvelope(ctx, state, payload);
|
|
856
|
+
updatePiUi(ctx, state);
|
|
857
|
+
}
|
|
858
|
+
} catch (error) {
|
|
859
|
+
appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
860
|
+
updatePiUi(ctx, state);
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
socket.onerror = () => socket.close();
|
|
864
|
+
socket.onclose = () => {
|
|
865
|
+
state.wsConnected = false;
|
|
866
|
+
state.status = "worker Pi WebSocket disconnected";
|
|
867
|
+
updatePiUi(ctx, state);
|
|
868
|
+
resolve3();
|
|
869
|
+
};
|
|
870
|
+
});
|
|
871
|
+
try {
|
|
872
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
873
|
+
getRunPiMessagesViaServer(options.context, options.runId),
|
|
874
|
+
getRunPiStatusViaServer(options.context, options.runId),
|
|
875
|
+
getRunPiCommandsViaServer(options.context, options.runId)
|
|
522
876
|
]);
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
877
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
878
|
+
const native = nativePiUi(ctx);
|
|
879
|
+
if (state.nativeStream && native?.appendSessionMessages)
|
|
880
|
+
native.appendSessionMessages(messages);
|
|
881
|
+
else
|
|
882
|
+
for (const message of messages)
|
|
883
|
+
applyMessage(state, message);
|
|
884
|
+
applyStatus(state, statusPayload);
|
|
885
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
886
|
+
state.commands = commands.flatMap((command) => {
|
|
887
|
+
const record = recordOf(command);
|
|
888
|
+
return typeof record?.name === "string" ? [`/${record.name}`] : [];
|
|
889
|
+
});
|
|
890
|
+
catchupDone = true;
|
|
891
|
+
for (const payload of buffered.splice(0))
|
|
892
|
+
applyEnvelope(ctx, state, payload);
|
|
893
|
+
updatePiUi(ctx, state);
|
|
894
|
+
} catch (error) {
|
|
895
|
+
appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
896
|
+
catchupDone = true;
|
|
897
|
+
updatePiUi(ctx, state);
|
|
898
|
+
}
|
|
899
|
+
await closePromise;
|
|
900
|
+
}
|
|
901
|
+
function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
902
|
+
return {
|
|
903
|
+
exec(command, _cwd, execOptions) {
|
|
904
|
+
return new Promise((resolve3, reject) => {
|
|
905
|
+
const pending = {
|
|
906
|
+
command,
|
|
907
|
+
onData: execOptions.onData,
|
|
908
|
+
resolve: resolve3,
|
|
909
|
+
reject,
|
|
910
|
+
sawChunk: false
|
|
911
|
+
};
|
|
912
|
+
const cleanup = () => {
|
|
913
|
+
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
914
|
+
if (timer)
|
|
915
|
+
clearTimeout(timer);
|
|
916
|
+
};
|
|
917
|
+
const onAbort = () => {
|
|
918
|
+
cleanup();
|
|
919
|
+
failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
|
|
920
|
+
};
|
|
921
|
+
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
922
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
923
|
+
cleanup();
|
|
924
|
+
failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
925
|
+
}, timeoutMs) : null;
|
|
926
|
+
const wrappedResolve = pending.resolve;
|
|
927
|
+
const wrappedReject = pending.reject;
|
|
928
|
+
pending.resolve = (result) => {
|
|
929
|
+
cleanup();
|
|
930
|
+
wrappedResolve(result);
|
|
931
|
+
};
|
|
932
|
+
pending.reject = (error) => {
|
|
933
|
+
cleanup();
|
|
934
|
+
wrappedReject(error);
|
|
935
|
+
};
|
|
936
|
+
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
937
|
+
state.pendingShells.push(pending);
|
|
938
|
+
sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
939
|
+
cleanup();
|
|
940
|
+
failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
|
|
941
|
+
});
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
async function answerPendingUi(options, state, line) {
|
|
947
|
+
const pending = state.pendingUi;
|
|
948
|
+
if (!pending)
|
|
949
|
+
return false;
|
|
950
|
+
if (line === "/cancel") {
|
|
951
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
952
|
+
} else if (pending.method === "confirm") {
|
|
953
|
+
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
954
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
955
|
+
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
956
|
+
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
957
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
958
|
+
} else {
|
|
959
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
960
|
+
}
|
|
961
|
+
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
962
|
+
state.pendingUi = null;
|
|
963
|
+
return true;
|
|
964
|
+
}
|
|
965
|
+
async function routeInput(options, ctx, state, line) {
|
|
966
|
+
const text = line.trim();
|
|
967
|
+
if (!text)
|
|
968
|
+
return;
|
|
969
|
+
if (await answerPendingUi(options, state, text)) {
|
|
970
|
+
updatePiUi(ctx, state);
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
if (text === "/detach" || text === "/quit" || text === "/q") {
|
|
974
|
+
appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
|
|
975
|
+
updatePiUi(ctx, state);
|
|
976
|
+
ctx.shutdown();
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
if (text === "/stop") {
|
|
980
|
+
await abortRunPiViaServer(options.context, options.runId);
|
|
981
|
+
appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
|
|
982
|
+
updatePiUi(ctx, state);
|
|
983
|
+
ctx.shutdown();
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
if (text.startsWith("!")) {
|
|
987
|
+
appendTranscript(state, "You", text);
|
|
988
|
+
await sendRunPiShellViaServer(options.context, options.runId, text);
|
|
989
|
+
} else if (text.startsWith("/")) {
|
|
990
|
+
appendTranscript(state, "You", text);
|
|
991
|
+
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
992
|
+
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
993
|
+
appendTranscript(state, "System", message);
|
|
994
|
+
} else {
|
|
995
|
+
appendTranscript(state, "You", text);
|
|
996
|
+
await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
|
|
997
|
+
}
|
|
998
|
+
updatePiUi(ctx, state);
|
|
999
|
+
}
|
|
1000
|
+
function createRigWorkerPiBridgeExtension(options) {
|
|
1001
|
+
return (pi) => {
|
|
1002
|
+
const state = {
|
|
1003
|
+
transcript: [],
|
|
1004
|
+
status: "starting worker Pi daemon bridge",
|
|
1005
|
+
activity: "",
|
|
1006
|
+
cwd: "",
|
|
1007
|
+
model: "",
|
|
1008
|
+
commands: [],
|
|
1009
|
+
streaming: false,
|
|
1010
|
+
pendingUi: null,
|
|
1011
|
+
pendingShells: [],
|
|
1012
|
+
wsConnected: false,
|
|
1013
|
+
nativeStream: false
|
|
530
1014
|
};
|
|
1015
|
+
if (options.initialMessageSent)
|
|
1016
|
+
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
1017
|
+
let nativePiUiContextAvailable = false;
|
|
1018
|
+
pi.on("user_bash", (event) => {
|
|
1019
|
+
state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
|
|
1020
|
+
return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
|
|
1021
|
+
});
|
|
1022
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1023
|
+
nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
|
|
1024
|
+
state.nativeStream = nativePiUiContextAvailable;
|
|
1025
|
+
updatePiUi(ctx, state);
|
|
1026
|
+
ctx.ui.notify(nativePiUiContextAvailable ? "Rig worker Pi native stream bridge loaded" : "Rig worker Pi bridge extension loaded (degraded widget fallback)", "info");
|
|
1027
|
+
ctx.ui.onTerminalInput((data) => {
|
|
1028
|
+
if (data.includes("\x04")) {
|
|
1029
|
+
ctx.shutdown();
|
|
1030
|
+
return { consume: true };
|
|
1031
|
+
}
|
|
1032
|
+
if (!data.includes("\r") && !data.includes(`
|
|
1033
|
+
`))
|
|
1034
|
+
return;
|
|
1035
|
+
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
1036
|
+
const editorText = ctx.ui.getEditorText().trim();
|
|
1037
|
+
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
1038
|
+
if (!text)
|
|
1039
|
+
return;
|
|
1040
|
+
if (text.startsWith("!"))
|
|
1041
|
+
return;
|
|
1042
|
+
ctx.ui.setEditorText("");
|
|
1043
|
+
routeInput(options, ctx, state, text).catch((error) => {
|
|
1044
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1045
|
+
updatePiUi(ctx, state);
|
|
1046
|
+
});
|
|
1047
|
+
return { consume: true };
|
|
1048
|
+
});
|
|
1049
|
+
connectWorkerStream(options, ctx, state).catch((error) => {
|
|
1050
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1051
|
+
updatePiUi(ctx, state);
|
|
1052
|
+
});
|
|
1053
|
+
});
|
|
1054
|
+
pi.on("session_shutdown", () => {});
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
1059
|
+
function setTemporaryEnv(updates) {
|
|
1060
|
+
const previous = new Map;
|
|
1061
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
1062
|
+
previous.set(key, process.env[key]);
|
|
1063
|
+
process.env[key] = value;
|
|
1064
|
+
}
|
|
1065
|
+
return () => {
|
|
1066
|
+
for (const [key, value] of previous) {
|
|
1067
|
+
if (value === undefined)
|
|
1068
|
+
delete process.env[key];
|
|
1069
|
+
else
|
|
1070
|
+
process.env[key] = value;
|
|
1071
|
+
}
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
async function attachRunBundledPiFrontend(context, input) {
|
|
1075
|
+
const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
|
|
1076
|
+
const cwd = join(tempRoot, "workspace");
|
|
1077
|
+
const agentDir = join(tempRoot, "agent");
|
|
1078
|
+
const sessionDir = join(tempRoot, "sessions");
|
|
1079
|
+
const previousCwd = process.cwd();
|
|
1080
|
+
const restoreEnv = setTemporaryEnv({
|
|
1081
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
1082
|
+
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
1083
|
+
PI_OFFLINE: "1",
|
|
1084
|
+
PI_SKIP_VERSION_CHECK: "1"
|
|
1085
|
+
});
|
|
1086
|
+
let detached = false;
|
|
1087
|
+
try {
|
|
1088
|
+
await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
|
|
1089
|
+
process.chdir(cwd);
|
|
1090
|
+
await runPiMain([
|
|
1091
|
+
"--offline",
|
|
1092
|
+
"--no-session",
|
|
1093
|
+
"--no-tools",
|
|
1094
|
+
"--no-builtin-tools",
|
|
1095
|
+
"--no-skills",
|
|
1096
|
+
"--no-prompt-templates",
|
|
1097
|
+
"--no-themes",
|
|
1098
|
+
"--no-context-files",
|
|
1099
|
+
"--no-approve"
|
|
1100
|
+
], {
|
|
1101
|
+
extensionFactories: [
|
|
1102
|
+
createRigWorkerPiBridgeExtension({
|
|
1103
|
+
context,
|
|
1104
|
+
runId: input.runId,
|
|
1105
|
+
initialMessageSent: input.steered === true
|
|
1106
|
+
})
|
|
1107
|
+
]
|
|
1108
|
+
});
|
|
1109
|
+
detached = true;
|
|
1110
|
+
} finally {
|
|
1111
|
+
process.chdir(previousCwd);
|
|
1112
|
+
restoreEnv();
|
|
1113
|
+
rmSync(tempRoot, { recursive: true, force: true });
|
|
531
1114
|
}
|
|
1115
|
+
let run = { runId: input.runId, status: "unknown" };
|
|
1116
|
+
try {
|
|
1117
|
+
run = await getRunDetailsViaServer(context, input.runId);
|
|
1118
|
+
} catch {}
|
|
1119
|
+
return {
|
|
1120
|
+
run,
|
|
1121
|
+
logs: [],
|
|
1122
|
+
timeline: [],
|
|
1123
|
+
timelineCursor: null,
|
|
1124
|
+
steered: input.steered === true,
|
|
1125
|
+
detached,
|
|
1126
|
+
rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
|
|
1127
|
+
};
|
|
532
1128
|
}
|
|
1129
|
+
|
|
1130
|
+
// packages/cli/src/commands/_operator-view.ts
|
|
1131
|
+
var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
533
1132
|
function runStatusFromPayload(payload) {
|
|
534
1133
|
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
535
1134
|
return String(run.status ?? "unknown").toLowerCase();
|
|
@@ -568,198 +1167,15 @@ async function readOperatorSnapshot(context, runId, options = {}) {
|
|
|
568
1167
|
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
569
1168
|
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
570
1169
|
}
|
|
571
|
-
function unwrapRun(runPayload) {
|
|
572
|
-
return runPayload.run && typeof runPayload.run === "object" && !Array.isArray(runPayload.run) ? runPayload.run : runPayload;
|
|
573
|
-
}
|
|
574
|
-
function logDetail2(log) {
|
|
575
|
-
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
576
|
-
}
|
|
577
|
-
function logTitle(log) {
|
|
578
|
-
return typeof log.title === "string" ? log.title.trim() : "";
|
|
579
|
-
}
|
|
580
|
-
function renderAssistantTextFromTimeline(entries) {
|
|
581
|
-
const assistant = entries.filter((entry) => entry.type === "assistant_message" && typeof entry.text === "string").at(-1);
|
|
582
|
-
const text = typeof assistant?.text === "string" ? assistant.text.trimEnd() : "";
|
|
583
|
-
if (!text)
|
|
584
|
-
return [];
|
|
585
|
-
return [`${BLUE}${BOLD}Remote Pi assistant${RESET}`, ...text.split(/\r?\n/).slice(-18)];
|
|
586
|
-
}
|
|
587
|
-
function renderToolLines(entries) {
|
|
588
|
-
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());
|
|
589
|
-
}
|
|
590
|
-
function renderStageLines(logs) {
|
|
591
|
-
const latestByStage = new Map;
|
|
592
|
-
for (const log of logs) {
|
|
593
|
-
const title = logTitle(log).toLowerCase();
|
|
594
|
-
const stageName = String(log.stage ?? "").toLowerCase();
|
|
595
|
-
const stage = CANONICAL_STAGES2.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
596
|
-
if (stage)
|
|
597
|
-
latestByStage.set(stage, log);
|
|
598
|
-
}
|
|
599
|
-
return CANONICAL_STAGES2.map((stage) => {
|
|
600
|
-
const log = latestByStage.get(stage);
|
|
601
|
-
const status = String(log?.status ?? "pending");
|
|
602
|
-
const detail = log ? logDetail2(log) : "";
|
|
603
|
-
const color = status === "completed" ? GREEN : status === "failed" || status === "rejected" ? RED : status === "pending" ? DIM : YELLOW;
|
|
604
|
-
const mark = status === "completed" ? "\u2713" : status === "pending" ? "\xB7" : status === "failed" ? "\u2717" : "\u25B6";
|
|
605
|
-
return `${color}${mark} ${stage}${RESET}${detail ? ` ${DIM}\u2014 ${detail.slice(0, 140)}${RESET}` : ""}`;
|
|
606
|
-
});
|
|
607
|
-
}
|
|
608
|
-
function renderEventLines(logs) {
|
|
609
|
-
return logs.filter((log) => !CANONICAL_STAGES2.some((stage) => stage.toLowerCase() === logTitle(log).toLowerCase())).slice(-12).flatMap((log) => {
|
|
610
|
-
const title = logTitle(log) || "Rig event";
|
|
611
|
-
const detail = logDetail2(log);
|
|
612
|
-
if (!detail)
|
|
613
|
-
return [];
|
|
614
|
-
const tone = String(log.tone ?? "");
|
|
615
|
-
const color = tone === "error" ? RED : tone === "tool" ? MAGENTA : DIM;
|
|
616
|
-
return [`${color}[${title}]${RESET} ${detail.slice(0, 220)}`];
|
|
617
|
-
});
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
class RigRunComponent {
|
|
621
|
-
truncateToWidth;
|
|
622
|
-
snapshot = { run: {}, logs: [], timeline: [] };
|
|
623
|
-
localEvents = [];
|
|
624
|
-
constructor(truncateToWidth) {
|
|
625
|
-
this.truncateToWidth = truncateToWidth;
|
|
626
|
-
}
|
|
627
|
-
update(snapshot) {
|
|
628
|
-
this.snapshot = snapshot;
|
|
629
|
-
}
|
|
630
|
-
addLocalEvent(message) {
|
|
631
|
-
this.localEvents.push(`${new Date().toLocaleTimeString()} ${message}`);
|
|
632
|
-
this.localEvents = this.localEvents.slice(-8);
|
|
633
|
-
}
|
|
634
|
-
invalidate() {}
|
|
635
|
-
render(width) {
|
|
636
|
-
const run = unwrapRun(this.snapshot.run);
|
|
637
|
-
const runId = String(run.runId ?? run.id ?? "run");
|
|
638
|
-
const status = String(run.status ?? "unknown");
|
|
639
|
-
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";
|
|
640
|
-
const lines = [
|
|
641
|
-
`${BOLD}Rig Pi frontend${RESET} ${DIM}(local Pi TUI \u2192 Rig server \u2192 worker Pi backend)${RESET}`,
|
|
642
|
-
`${BOLD}${runId}${RESET} \xB7 ${status} \xB7 ${DIM}${worker}${RESET}`,
|
|
643
|
-
"",
|
|
644
|
-
`${BOLD}Rig flow${RESET}`,
|
|
645
|
-
...renderStageLines(this.snapshot.logs ?? []),
|
|
646
|
-
"",
|
|
647
|
-
...renderAssistantTextFromTimeline(this.snapshot.timeline ?? []),
|
|
648
|
-
...renderToolLines(this.snapshot.timeline ?? []),
|
|
649
|
-
"",
|
|
650
|
-
`${BOLD}Rig / Pi events${RESET}`,
|
|
651
|
-
...renderEventLines(this.snapshot.logs ?? []),
|
|
652
|
-
...this.localEvents.map((event) => `${GREEN}[frontend]${RESET} ${event}`),
|
|
653
|
-
""
|
|
654
|
-
];
|
|
655
|
-
return lines.slice(-42).map((line) => this.truncateToWidth(line, Math.max(10, width)));
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
class RigInputComponent {
|
|
660
|
-
matchesKey;
|
|
661
|
-
truncateToWidth;
|
|
662
|
-
input;
|
|
663
|
-
status = "Type text, /skill:..., or remote Pi slash commands. Local: /stop /detach.";
|
|
664
|
-
constructor(InputCtor, matchesKey, truncateToWidth, onSubmit, onEscape) {
|
|
665
|
-
this.matchesKey = matchesKey;
|
|
666
|
-
this.truncateToWidth = truncateToWidth;
|
|
667
|
-
this.input = new InputCtor;
|
|
668
|
-
this.input.onSubmit = (value) => {
|
|
669
|
-
const text = value.trim();
|
|
670
|
-
this.input.setValue("");
|
|
671
|
-
if (text)
|
|
672
|
-
Promise.resolve(onSubmit(text));
|
|
673
|
-
};
|
|
674
|
-
this.input.onEscape = onEscape;
|
|
675
|
-
}
|
|
676
|
-
handleInput(data) {
|
|
677
|
-
if (this.matchesKey(data, "ctrl+d")) {
|
|
678
|
-
this.input.onEscape?.();
|
|
679
|
-
return;
|
|
680
|
-
}
|
|
681
|
-
this.input.handleInput?.(data);
|
|
682
|
-
}
|
|
683
|
-
setStatus(status) {
|
|
684
|
-
this.status = status;
|
|
685
|
-
}
|
|
686
|
-
invalidate() {
|
|
687
|
-
this.input.invalidate();
|
|
688
|
-
}
|
|
689
|
-
render(width) {
|
|
690
|
-
return [
|
|
691
|
-
`${DIM}${this.truncateToWidth(this.status, Math.max(10, width))}${RESET}`,
|
|
692
|
-
`${GREEN}${BOLD}You \u2192 worker Pi:${RESET}`,
|
|
693
|
-
...this.input.render(width)
|
|
694
|
-
];
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
async function attachRunPiTuiFrontend(context, input) {
|
|
698
|
-
const piTui = await loadPiTuiRuntime();
|
|
699
|
-
const terminal = new piTui.ProcessTerminal;
|
|
700
|
-
const tui = new piTui.TUI(terminal);
|
|
701
|
-
const root = new piTui.Container;
|
|
702
|
-
const runView = new RigRunComponent(piTui.truncateToWidth);
|
|
703
|
-
let detached = false;
|
|
704
|
-
let steered = input.steered === true;
|
|
705
|
-
let latest = await readOperatorSnapshot(context, input.runId);
|
|
706
|
-
let timelineCursor = latest.timelineCursor;
|
|
707
|
-
runView.update(latest);
|
|
708
|
-
if (steered)
|
|
709
|
-
runView.addLocalEvent("initial message queued to worker Pi.");
|
|
710
|
-
const stop = () => {
|
|
711
|
-
detached = true;
|
|
712
|
-
tui.stop();
|
|
713
|
-
};
|
|
714
|
-
const inputView = new RigInputComponent(piTui.Input, piTui.matchesKey, piTui.truncateToWidth, async (line) => {
|
|
715
|
-
if (line === "/detach" || line === "/quit" || line === "/q") {
|
|
716
|
-
runView.addLocalEvent("detached from run.");
|
|
717
|
-
stop();
|
|
718
|
-
return;
|
|
719
|
-
}
|
|
720
|
-
if (line === "/stop") {
|
|
721
|
-
await stopRunViaServer(context, input.runId);
|
|
722
|
-
runView.addLocalEvent("stop requested.");
|
|
723
|
-
stop();
|
|
724
|
-
return;
|
|
725
|
-
}
|
|
726
|
-
await steerRunViaServer(context, input.runId, line);
|
|
727
|
-
steered = true;
|
|
728
|
-
runView.addLocalEvent(`queued to worker Pi: ${line.slice(0, 160)}`);
|
|
729
|
-
tui.requestRender();
|
|
730
|
-
}, stop);
|
|
731
|
-
root.addChild(runView);
|
|
732
|
-
root.addChild(inputView);
|
|
733
|
-
tui.addChild(root);
|
|
734
|
-
tui.setFocus(inputView.input);
|
|
735
|
-
tui.start();
|
|
736
|
-
tui.requestRender(true);
|
|
737
|
-
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 1000));
|
|
738
|
-
try {
|
|
739
|
-
while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(latest.run))) {
|
|
740
|
-
await Bun.sleep(pollMs);
|
|
741
|
-
latest = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
742
|
-
timelineCursor = latest.timelineCursor;
|
|
743
|
-
runView.update(latest);
|
|
744
|
-
inputView.setStatus(`Remote worker ${runStatusFromPayload(latest.run)}. Input is forwarded to worker Pi; /stop /detach are local controls.`);
|
|
745
|
-
tui.requestRender();
|
|
746
|
-
}
|
|
747
|
-
} finally {
|
|
748
|
-
if (!detached)
|
|
749
|
-
tui.stop();
|
|
750
|
-
}
|
|
751
|
-
return { ...latest, timelineCursor, steered, detached, rendered: renderOperatorSnapshot(latest) };
|
|
752
|
-
}
|
|
753
1170
|
async function attachRunOperatorView(context, input) {
|
|
754
1171
|
let steered = false;
|
|
755
1172
|
if (input.message?.trim()) {
|
|
756
|
-
await steerRunViaServer(context, input.runId, input.message.trim());
|
|
1173
|
+
await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
|
|
757
1174
|
steered = true;
|
|
758
1175
|
}
|
|
759
1176
|
if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
760
|
-
return
|
|
1177
|
+
return attachRunBundledPiFrontend(context, {
|
|
761
1178
|
runId: input.runId,
|
|
762
|
-
pollMs: input.pollMs,
|
|
763
1179
|
steered
|
|
764
1180
|
});
|
|
765
1181
|
}
|
|
@@ -770,7 +1186,7 @@ async function attachRunOperatorView(context, input) {
|
|
|
770
1186
|
surface.renderTimeline(snapshot.timeline);
|
|
771
1187
|
surface.renderLogs(snapshot.logs);
|
|
772
1188
|
if (steered)
|
|
773
|
-
surface.info("
|
|
1189
|
+
surface.info("Message submitted to worker Pi.");
|
|
774
1190
|
}
|
|
775
1191
|
let detached = false;
|
|
776
1192
|
let commandInput = null;
|
|
@@ -789,7 +1205,7 @@ async function attachRunOperatorView(context, input) {
|
|
|
789
1205
|
}
|
|
790
1206
|
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
791
1207
|
let timelineCursor = snapshot.timelineCursor;
|
|
792
|
-
while (!detached && !
|
|
1208
|
+
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
793
1209
|
await Bun.sleep(pollMs);
|
|
794
1210
|
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
795
1211
|
timelineCursor = snapshot.timelineCursor;
|