@h-rig/cli 0.0.6-alpha.40 → 0.0.6-alpha.42
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 +512 -551
- package/dist/src/commands/_operator-view.js +510 -530
- package/dist/src/commands/_pi-frontend.js +514 -534
- package/dist/src/commands/_pi-remote-session.js +671 -0
- package/dist/src/commands/_pi-worker-bridge-extension.js +352 -502
- package/dist/src/commands/_run-driver-helpers.js +2 -21
- package/dist/src/commands/run.js +510 -530
- package/dist/src/commands/task-run-driver.js +2 -21
- package/dist/src/commands/task.js +510 -530
- package/dist/src/commands.js +512 -551
- package/dist/src/index.js +512 -551
- package/package.json +6 -6
package/dist/src/commands/run.js
CHANGED
|
@@ -560,435 +560,400 @@ function createOperatorSurface(options = {}) {
|
|
|
560
560
|
import { mkdtempSync, rmSync } from "fs";
|
|
561
561
|
import { tmpdir } from "os";
|
|
562
562
|
import { join } from "path";
|
|
563
|
-
import {
|
|
563
|
+
import {
|
|
564
|
+
createAgentSessionFromServices,
|
|
565
|
+
createAgentSessionServices,
|
|
566
|
+
main as runPiMain
|
|
567
|
+
} from "@earendil-works/pi-coding-agent";
|
|
564
568
|
|
|
565
|
-
// packages/cli/src/commands/_pi-
|
|
569
|
+
// packages/cli/src/commands/_pi-remote-session.ts
|
|
570
|
+
import { AgentSession as PiAgentSession } from "@earendil-works/pi-coding-agent";
|
|
566
571
|
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
567
|
-
|
|
572
|
+
function defaultTransport() {
|
|
573
|
+
return {
|
|
574
|
+
getSession: getRunPiSessionViaServer,
|
|
575
|
+
getMessages: getRunPiMessagesViaServer,
|
|
576
|
+
getStatus: getRunPiStatusViaServer,
|
|
577
|
+
getCommands: getRunPiCommandsViaServer,
|
|
578
|
+
sendPrompt: sendRunPiPromptViaServer,
|
|
579
|
+
sendShell: sendRunPiShellViaServer,
|
|
580
|
+
runCommand: runRunPiCommandViaServer,
|
|
581
|
+
abort: abortRunPiViaServer,
|
|
582
|
+
buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
|
|
583
|
+
};
|
|
584
|
+
}
|
|
568
585
|
function recordOf(value) {
|
|
569
586
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
570
587
|
}
|
|
571
|
-
function
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
return content;
|
|
587
|
-
if (!Array.isArray(content))
|
|
588
|
-
return asText(content);
|
|
589
|
-
return content.flatMap((part) => {
|
|
590
|
-
const item = recordOf(part);
|
|
591
|
-
if (!item)
|
|
592
|
-
return [];
|
|
593
|
-
if (typeof item.text === "string")
|
|
594
|
-
return [item.text];
|
|
595
|
-
if (typeof item.content === "string")
|
|
596
|
-
return [item.content];
|
|
597
|
-
if (item.type === "toolCall")
|
|
598
|
-
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
599
|
-
if (item.type === "toolResult")
|
|
600
|
-
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
601
|
-
return [];
|
|
602
|
-
}).join(`
|
|
603
|
-
`);
|
|
604
|
-
}
|
|
605
|
-
function appendTranscript(state, label, text) {
|
|
606
|
-
const trimmed = text.trimEnd();
|
|
607
|
-
if (!trimmed)
|
|
608
|
-
return;
|
|
609
|
-
const lines = trimmed.split(/\r?\n/);
|
|
610
|
-
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
611
|
-
for (const line of lines.slice(1))
|
|
612
|
-
state.transcript.push(` ${line}`);
|
|
613
|
-
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
614
|
-
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
function nativePiUi(ctx) {
|
|
618
|
-
const ui = ctx.ui;
|
|
619
|
-
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
620
|
-
}
|
|
621
|
-
function syncNativeDisplayCwd(ctx, state) {
|
|
622
|
-
const ui = nativePiUi(ctx);
|
|
623
|
-
if (ui?.setDisplayCwd && state.cwd)
|
|
624
|
-
ui.setDisplayCwd(state.cwd);
|
|
625
|
-
}
|
|
626
|
-
function parseExtensionUiRequest(value) {
|
|
627
|
-
const request = recordOf(value) ?? {};
|
|
628
|
-
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
629
|
-
const method = String(request.method ?? request.type ?? "input");
|
|
630
|
-
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
631
|
-
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
632
|
-
const options = rawOptions.map((option) => {
|
|
633
|
-
const record = recordOf(option);
|
|
634
|
-
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
635
|
-
}).filter(Boolean);
|
|
636
|
-
return { requestId, method, prompt, options };
|
|
637
|
-
}
|
|
638
|
-
function renderBridgeWidget(state) {
|
|
639
|
-
const statusParts = [
|
|
640
|
-
state.wsConnected ? "live" : "connecting",
|
|
641
|
-
state.status,
|
|
642
|
-
state.model,
|
|
643
|
-
state.cwd
|
|
644
|
-
].filter(Boolean);
|
|
645
|
-
const lines = [`Rig worker session \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
646
|
-
if (state.activity)
|
|
647
|
-
lines.push(state.activity);
|
|
648
|
-
if (state.commands.length > 0) {
|
|
649
|
-
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
650
|
-
}
|
|
651
|
-
lines.push("");
|
|
652
|
-
if (state.transcript.length > 0) {
|
|
653
|
-
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
654
|
-
} else {
|
|
655
|
-
lines.push("Waiting for the worker session transcript\u2026 (/detach exits and leaves the worker running)");
|
|
656
|
-
}
|
|
657
|
-
if (state.pendingUi) {
|
|
658
|
-
lines.push("");
|
|
659
|
-
lines.push(`Worker needs input \xB7 ${state.pendingUi.method}`);
|
|
660
|
-
lines.push(state.pendingUi.prompt);
|
|
661
|
-
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
662
|
-
lines.push("Reply in the editor below. /cancel dismisses this request.");
|
|
663
|
-
}
|
|
664
|
-
return lines;
|
|
665
|
-
}
|
|
666
|
-
function reportBridgeError(ctx, state, message) {
|
|
667
|
-
appendTranscript(state, "Error", message);
|
|
668
|
-
state.status = message;
|
|
669
|
-
try {
|
|
670
|
-
ctx.ui.notify(message, "error");
|
|
671
|
-
} catch {}
|
|
672
|
-
updatePiUi(ctx, state);
|
|
673
|
-
}
|
|
674
|
-
function updatePiUi(ctx, state) {
|
|
675
|
-
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
676
|
-
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker session live" : state.status);
|
|
677
|
-
syncNativeDisplayCwd(ctx, state);
|
|
678
|
-
if (state.nativeStream && nativePiUi(ctx)) {
|
|
679
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
680
|
-
return;
|
|
681
|
-
}
|
|
682
|
-
ctx.ui.setWorkingVisible(false);
|
|
683
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
|
|
684
|
-
}
|
|
685
|
-
function applyStatus(state, payload) {
|
|
686
|
-
const status = recordOf(payload.status) ?? payload;
|
|
687
|
-
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
688
|
-
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
689
|
-
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
690
|
-
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
691
|
-
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
692
|
-
}
|
|
693
|
-
function applyMessage(state, message) {
|
|
694
|
-
const record = recordOf(message);
|
|
695
|
-
if (!record)
|
|
696
|
-
return;
|
|
697
|
-
const role = String(record.role ?? "system");
|
|
698
|
-
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
699
|
-
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
700
|
-
}
|
|
701
|
-
function applyPiEvent(ctx, state, eventValue) {
|
|
702
|
-
const event = recordOf(eventValue);
|
|
703
|
-
if (!event)
|
|
704
|
-
return;
|
|
705
|
-
const type = String(event.type ?? "event");
|
|
706
|
-
if (type === "agent_start") {
|
|
707
|
-
state.streaming = true;
|
|
708
|
-
state.status = "streaming";
|
|
709
|
-
} else if (type === "agent_end") {
|
|
710
|
-
state.streaming = false;
|
|
711
|
-
state.status = "idle";
|
|
712
|
-
} else if (type === "queue_update") {
|
|
713
|
-
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
714
|
-
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
715
|
-
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
716
|
-
}
|
|
717
|
-
const native = nativePiUi(ctx);
|
|
718
|
-
if (state.nativeStream && native?.emitSessionEvent) {
|
|
719
|
-
native.emitSessionEvent(eventValue);
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
if (type === "agent_end") {
|
|
723
|
-
appendTranscript(state, "System", "Agent turn complete.");
|
|
724
|
-
return;
|
|
725
|
-
}
|
|
726
|
-
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
727
|
-
applyMessage(state, event.message);
|
|
728
|
-
return;
|
|
729
|
-
}
|
|
730
|
-
if (type === "message_update") {
|
|
731
|
-
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
732
|
-
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
733
|
-
if (delta)
|
|
734
|
-
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
735
|
-
return;
|
|
736
|
-
}
|
|
737
|
-
if (type === "tool_execution_start") {
|
|
738
|
-
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
739
|
-
return;
|
|
740
|
-
}
|
|
741
|
-
if (type === "tool_execution_update") {
|
|
742
|
-
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
743
|
-
return;
|
|
744
|
-
}
|
|
745
|
-
if (type === "tool_execution_end") {
|
|
746
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
function firstPendingShell(state) {
|
|
750
|
-
return state.pendingShells[0];
|
|
751
|
-
}
|
|
752
|
-
function finishPendingShell(state, shell, result) {
|
|
753
|
-
const index = state.pendingShells.indexOf(shell);
|
|
754
|
-
if (index !== -1)
|
|
755
|
-
state.pendingShells.splice(index, 1);
|
|
756
|
-
shell.resolve(result);
|
|
757
|
-
}
|
|
758
|
-
function failPendingShell(state, shell, error) {
|
|
759
|
-
const index = state.pendingShells.indexOf(shell);
|
|
760
|
-
if (index !== -1)
|
|
761
|
-
state.pendingShells.splice(index, 1);
|
|
762
|
-
shell.reject(error);
|
|
763
|
-
}
|
|
764
|
-
function applyUiEvent(state, value) {
|
|
765
|
-
const event = recordOf(value);
|
|
766
|
-
if (!event)
|
|
767
|
-
return;
|
|
768
|
-
const type = String(event.type ?? "ui");
|
|
769
|
-
if (type === "shell.chunk") {
|
|
770
|
-
const pending = firstPendingShell(state);
|
|
771
|
-
const chunk = asText(event.chunk);
|
|
772
|
-
if (pending) {
|
|
773
|
-
pending.sawChunk = true;
|
|
774
|
-
pending.onData(Buffer.from(chunk));
|
|
775
|
-
} else {
|
|
776
|
-
appendTranscript(state, "Tool", chunk);
|
|
777
|
-
}
|
|
778
|
-
return;
|
|
779
|
-
}
|
|
780
|
-
if (type === "shell.end") {
|
|
781
|
-
const pending = firstPendingShell(state);
|
|
782
|
-
const output = asText(event.output ?? "");
|
|
783
|
-
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
784
|
-
if (pending) {
|
|
785
|
-
if (output && !pending.sawChunk)
|
|
786
|
-
pending.onData(Buffer.from(output));
|
|
787
|
-
finishPendingShell(state, pending, { exitCode });
|
|
788
|
-
} else {
|
|
789
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
790
|
-
}
|
|
791
|
-
return;
|
|
792
|
-
}
|
|
793
|
-
if (type === "shell.start") {
|
|
794
|
-
if (!firstPendingShell(state))
|
|
795
|
-
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
796
|
-
return;
|
|
797
|
-
}
|
|
798
|
-
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
799
|
-
}
|
|
800
|
-
function applyEnvelope(ctx, state, envelopeValue) {
|
|
801
|
-
const envelope = recordOf(envelopeValue);
|
|
802
|
-
if (!envelope)
|
|
803
|
-
return;
|
|
804
|
-
const type = String(envelope.type ?? "");
|
|
805
|
-
if (type === "ready") {
|
|
806
|
-
const metadata = recordOf(envelope.metadata);
|
|
807
|
-
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
808
|
-
state.status = "worker Pi daemon ready";
|
|
809
|
-
if (!state.nativeStream)
|
|
810
|
-
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
811
|
-
} else if (type === "status.update") {
|
|
812
|
-
applyStatus(state, envelope);
|
|
813
|
-
} else if (type === "activity.update") {
|
|
814
|
-
const activity = recordOf(envelope.activity);
|
|
815
|
-
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
816
|
-
} else if (type === "extension_ui_request") {
|
|
817
|
-
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
818
|
-
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
819
|
-
} else if (type === "pi.ui_event") {
|
|
820
|
-
applyUiEvent(state, envelope.event);
|
|
821
|
-
} else if (type === "pi.event") {
|
|
822
|
-
applyPiEvent(ctx, state, envelope.event);
|
|
823
|
-
} else if (type === "error") {
|
|
824
|
-
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
825
|
-
}
|
|
826
|
-
syncNativeDisplayCwd(ctx, state);
|
|
588
|
+
function emptyRemoteStatus() {
|
|
589
|
+
return {
|
|
590
|
+
isStreaming: false,
|
|
591
|
+
isCompacting: false,
|
|
592
|
+
isBashRunning: false,
|
|
593
|
+
pendingMessageCount: 0,
|
|
594
|
+
steeringMessages: [],
|
|
595
|
+
followUpMessages: [],
|
|
596
|
+
model: null,
|
|
597
|
+
thinkingLevel: null,
|
|
598
|
+
sessionName: null,
|
|
599
|
+
cwd: null,
|
|
600
|
+
stats: null,
|
|
601
|
+
contextUsage: null
|
|
602
|
+
};
|
|
827
603
|
}
|
|
828
604
|
function resolveAttachReadyTimeoutMs() {
|
|
829
605
|
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
830
606
|
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
831
607
|
}
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
return false;
|
|
868
|
-
}
|
|
869
|
-
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
870
|
-
continue;
|
|
871
|
-
}
|
|
872
|
-
const sessionRecord = recordOf(session) ?? {};
|
|
873
|
-
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
874
|
-
updatePiUi(ctx, state);
|
|
875
|
-
return true;
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
function parseWsPayload(message) {
|
|
879
|
-
if (typeof message.data === "string")
|
|
880
|
-
return JSON.parse(message.data);
|
|
881
|
-
return JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
882
|
-
}
|
|
883
|
-
var BRIDGE_LOCAL_COMMANDS = new Set(["detach", "quit", "q", "stop"]);
|
|
884
|
-
function registerDaemonCommandsNatively(pi, options, ctx, state, commands, registered) {
|
|
885
|
-
for (const command of commands) {
|
|
886
|
-
const record = recordOf(command);
|
|
887
|
-
const name = typeof record?.name === "string" ? record.name : "";
|
|
888
|
-
if (!name || registered.has(name) || BRIDGE_LOCAL_COMMANDS.has(name))
|
|
889
|
-
continue;
|
|
890
|
-
registered.add(name);
|
|
891
|
-
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
892
|
-
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
893
|
-
try {
|
|
894
|
-
pi.registerCommand(name, {
|
|
895
|
-
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
896
|
-
handler: async (args) => {
|
|
897
|
-
const text = `/${name}${args ? ` ${args}` : ""}`;
|
|
898
|
-
appendTranscript(state, "You", text);
|
|
899
|
-
try {
|
|
900
|
-
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
901
|
-
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
902
|
-
appendTranscript(state, "System", message);
|
|
903
|
-
if (state.nativeStream)
|
|
904
|
-
ctx.ui.notify(message, "info");
|
|
905
|
-
} catch (error) {
|
|
906
|
-
reportBridgeError(ctx, state, error instanceof Error ? error.message : String(error));
|
|
907
|
-
}
|
|
908
|
-
updatePiUi(ctx, state);
|
|
909
|
-
}
|
|
910
|
-
});
|
|
911
|
-
} catch {}
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
async function connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands) {
|
|
915
|
-
const ready = await waitForWorkerReady(options, ctx, state);
|
|
916
|
-
if (!ready)
|
|
917
|
-
return;
|
|
918
|
-
let catchupDone = false;
|
|
919
|
-
const buffered = [];
|
|
920
|
-
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
921
|
-
const socket = new WebSocket(wsUrl);
|
|
922
|
-
const closePromise = new Promise((resolve3) => {
|
|
608
|
+
|
|
609
|
+
class RigRemoteSessionController {
|
|
610
|
+
context;
|
|
611
|
+
runId;
|
|
612
|
+
status = emptyRemoteStatus();
|
|
613
|
+
transport;
|
|
614
|
+
hooks = {};
|
|
615
|
+
session = null;
|
|
616
|
+
socket = null;
|
|
617
|
+
closed = false;
|
|
618
|
+
pendingShells = [];
|
|
619
|
+
pendingCompactions = [];
|
|
620
|
+
constructor(input) {
|
|
621
|
+
this.context = input.context;
|
|
622
|
+
this.runId = input.runId;
|
|
623
|
+
this.transport = input.transport ?? defaultTransport();
|
|
624
|
+
}
|
|
625
|
+
ingestEnvelope(envelopeValue) {
|
|
626
|
+
this.applyEnvelope(envelopeValue);
|
|
627
|
+
}
|
|
628
|
+
bindSession(session) {
|
|
629
|
+
this.session = session;
|
|
630
|
+
}
|
|
631
|
+
setUiHooks(hooks) {
|
|
632
|
+
this.hooks = hooks;
|
|
633
|
+
}
|
|
634
|
+
async connect() {
|
|
635
|
+
const ready = await this.waitForReady();
|
|
636
|
+
if (!ready || this.closed)
|
|
637
|
+
return;
|
|
638
|
+
let catchupDone = false;
|
|
639
|
+
const buffered = [];
|
|
640
|
+
const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
|
|
641
|
+
const socket = new WebSocket(wsUrl);
|
|
642
|
+
this.socket = socket;
|
|
923
643
|
socket.onopen = () => {
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
updatePiUi(ctx, state);
|
|
644
|
+
this.hooks.onConnectionChange?.(true);
|
|
645
|
+
this.hooks.onStatusText?.("worker session live");
|
|
927
646
|
};
|
|
928
647
|
socket.onmessage = (message) => {
|
|
929
648
|
try {
|
|
930
|
-
const payload =
|
|
649
|
+
const payload = typeof message.data === "string" ? JSON.parse(message.data) : JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
931
650
|
if (!catchupDone)
|
|
932
651
|
buffered.push(payload);
|
|
933
|
-
else
|
|
934
|
-
applyEnvelope(
|
|
935
|
-
updatePiUi(ctx, state);
|
|
936
|
-
}
|
|
652
|
+
else
|
|
653
|
+
this.applyEnvelope(payload);
|
|
937
654
|
} catch (error) {
|
|
938
|
-
|
|
939
|
-
updatePiUi(ctx, state);
|
|
655
|
+
this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
940
656
|
}
|
|
941
657
|
};
|
|
942
658
|
socket.onerror = () => socket.close();
|
|
943
659
|
socket.onclose = () => {
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
resolve3();
|
|
660
|
+
this.hooks.onConnectionChange?.(false);
|
|
661
|
+
if (!this.closed)
|
|
662
|
+
this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
|
|
948
663
|
};
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
664
|
+
try {
|
|
665
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
666
|
+
this.transport.getMessages(this.context, this.runId),
|
|
667
|
+
this.transport.getStatus(this.context, this.runId),
|
|
668
|
+
this.transport.getCommands(this.context, this.runId)
|
|
669
|
+
]);
|
|
670
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
671
|
+
this.applyStatusPayload(statusPayload);
|
|
672
|
+
this.session?.replaceRemoteMessages(messages);
|
|
673
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
674
|
+
this.hooks.onCatchUp?.(messages, commands);
|
|
675
|
+
catchupDone = true;
|
|
676
|
+
for (const payload of buffered.splice(0))
|
|
677
|
+
this.applyEnvelope(payload);
|
|
678
|
+
} catch (error) {
|
|
679
|
+
catchupDone = true;
|
|
680
|
+
this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
close() {
|
|
684
|
+
this.closed = true;
|
|
685
|
+
this.socket?.close();
|
|
686
|
+
for (const shell of this.pendingShells.splice(0))
|
|
687
|
+
shell.reject(new Error("Remote session closed."));
|
|
688
|
+
for (const compaction of this.pendingCompactions.splice(0))
|
|
689
|
+
compaction.reject(new Error("Remote session closed."));
|
|
690
|
+
}
|
|
691
|
+
async sendPrompt(text, streamingBehavior) {
|
|
692
|
+
await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
|
|
693
|
+
}
|
|
694
|
+
async sendCommand(text) {
|
|
695
|
+
const result = await this.transport.runCommand(this.context, this.runId, text);
|
|
696
|
+
return typeof result.message === "string" ? result.message : "worker command accepted";
|
|
697
|
+
}
|
|
698
|
+
async sendShell(text) {
|
|
699
|
+
await this.transport.sendShell(this.context, this.runId, text);
|
|
700
|
+
}
|
|
701
|
+
async abort() {
|
|
702
|
+
await this.transport.abort(this.context, this.runId);
|
|
703
|
+
}
|
|
704
|
+
registerPendingShell(shell) {
|
|
705
|
+
this.pendingShells.push(shell);
|
|
706
|
+
}
|
|
707
|
+
failPendingShell(shell, error) {
|
|
708
|
+
const index = this.pendingShells.indexOf(shell);
|
|
709
|
+
if (index !== -1)
|
|
710
|
+
this.pendingShells.splice(index, 1);
|
|
711
|
+
shell.reject(error);
|
|
712
|
+
}
|
|
713
|
+
registerPendingCompaction(pending) {
|
|
714
|
+
this.pendingCompactions.push(pending);
|
|
715
|
+
}
|
|
716
|
+
async waitForReady() {
|
|
717
|
+
const startedAt = Date.now();
|
|
718
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
719
|
+
let consecutiveFailures = 0;
|
|
720
|
+
while (!this.closed) {
|
|
721
|
+
let requestFailed = false;
|
|
722
|
+
const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
|
|
723
|
+
requestFailed = true;
|
|
724
|
+
return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
|
|
725
|
+
});
|
|
726
|
+
if (session.ready !== false)
|
|
727
|
+
return true;
|
|
728
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
729
|
+
const status = String(session.status ?? "starting");
|
|
730
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
731
|
+
this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
|
|
732
|
+
return false;
|
|
733
|
+
}
|
|
734
|
+
this.hooks.onStatusText?.(consecutiveFailures >= 5 ? "Rig server unreachable \xB7 retrying \xB7 /detach to exit" : `waiting for worker Pi daemon \xB7 ${status} \xB7 /detach to exit`);
|
|
735
|
+
if (Date.now() >= deadline) {
|
|
736
|
+
this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
|
|
737
|
+
return false;
|
|
738
|
+
}
|
|
739
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
740
|
+
}
|
|
741
|
+
return false;
|
|
742
|
+
}
|
|
743
|
+
applyEnvelope(envelopeValue) {
|
|
744
|
+
const envelope = recordOf(envelopeValue);
|
|
745
|
+
if (!envelope)
|
|
746
|
+
return;
|
|
747
|
+
const type = String(envelope.type ?? "");
|
|
748
|
+
if (type === "status.update") {
|
|
749
|
+
this.applyStatusPayload(envelope);
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (type === "activity.update") {
|
|
753
|
+
const activity = recordOf(envelope.activity);
|
|
754
|
+
this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
if (type === "extension_ui_request") {
|
|
758
|
+
const request = recordOf(envelope.request);
|
|
759
|
+
if (request)
|
|
760
|
+
this.hooks.onExtensionUiRequest?.(request);
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
if (type === "pi.ui_event") {
|
|
764
|
+
this.applyShellUiEvent(envelope.event);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
if (type === "pi.event") {
|
|
768
|
+
this.session?.handleRemoteSessionEvent(envelope.event);
|
|
769
|
+
this.settlePendingCompaction(envelope.event);
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
if (type === "error") {
|
|
773
|
+
this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
applyStatusPayload(payload) {
|
|
777
|
+
const status = recordOf(payload.status) ?? payload;
|
|
778
|
+
const next = this.status;
|
|
779
|
+
next.isStreaming = status.isStreaming === true;
|
|
780
|
+
next.isCompacting = status.isCompacting === true;
|
|
781
|
+
next.isBashRunning = status.isBashRunning === true;
|
|
782
|
+
next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
783
|
+
next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
|
|
784
|
+
next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
|
|
785
|
+
next.model = recordOf(status.model) ?? next.model;
|
|
786
|
+
next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
|
|
787
|
+
next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
|
|
788
|
+
next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
|
|
789
|
+
next.stats = recordOf(status.stats) ?? next.stats;
|
|
790
|
+
next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
|
|
791
|
+
}
|
|
792
|
+
applyShellUiEvent(value) {
|
|
793
|
+
const event = recordOf(value);
|
|
794
|
+
if (!event)
|
|
795
|
+
return;
|
|
796
|
+
const type = String(event.type ?? "");
|
|
797
|
+
const pending = this.pendingShells[0];
|
|
798
|
+
if (type === "shell.chunk" && pending) {
|
|
799
|
+
pending.sawChunk = true;
|
|
800
|
+
pending.onData(Buffer.from(String(event.chunk ?? "")));
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (type === "shell.end" && pending) {
|
|
804
|
+
const output = String(event.output ?? "");
|
|
805
|
+
if (output && !pending.sawChunk)
|
|
806
|
+
pending.onData(Buffer.from(output));
|
|
807
|
+
const index = this.pendingShells.indexOf(pending);
|
|
808
|
+
if (index !== -1)
|
|
809
|
+
this.pendingShells.splice(index, 1);
|
|
810
|
+
pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
settlePendingCompaction(eventValue) {
|
|
814
|
+
const event = recordOf(eventValue);
|
|
815
|
+
if (!event)
|
|
816
|
+
return;
|
|
817
|
+
const type = String(event.type ?? "");
|
|
818
|
+
if (type !== "compaction_end" || this.pendingCompactions.length === 0)
|
|
819
|
+
return;
|
|
820
|
+
const pending = this.pendingCompactions.shift();
|
|
821
|
+
const result = recordOf(event.result);
|
|
822
|
+
if (result)
|
|
823
|
+
pending.resolve(result);
|
|
824
|
+
else if (event.aborted === true)
|
|
825
|
+
pending.reject(new Error("Compaction aborted on the worker."));
|
|
960
826
|
else
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
827
|
+
pending.resolve({});
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
class RigRemoteAgentSession extends PiAgentSession {
|
|
832
|
+
remote;
|
|
833
|
+
constructor(config, remote) {
|
|
834
|
+
super(config);
|
|
835
|
+
this.remote = remote;
|
|
836
|
+
remote.bindSession(this);
|
|
837
|
+
}
|
|
838
|
+
handleRemoteSessionEvent(eventValue) {
|
|
839
|
+
const event = recordOf(eventValue);
|
|
840
|
+
if (!event)
|
|
841
|
+
return;
|
|
842
|
+
const type = String(event.type ?? "");
|
|
843
|
+
if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
|
|
844
|
+
this.agent.state.messages = [...this.agent.state.messages, event.message];
|
|
845
|
+
}
|
|
846
|
+
this._emit(eventValue);
|
|
847
|
+
}
|
|
848
|
+
replaceRemoteMessages(messages) {
|
|
849
|
+
this.agent.state.messages = messages;
|
|
850
|
+
}
|
|
851
|
+
async prompt(text, options) {
|
|
852
|
+
const trimmed = text.trim();
|
|
853
|
+
if (!trimmed)
|
|
854
|
+
return;
|
|
855
|
+
if (trimmed.startsWith("/")) {
|
|
856
|
+
if (await this._tryExecuteExtensionCommand(trimmed))
|
|
857
|
+
return;
|
|
858
|
+
await this.remote.sendCommand(trimmed);
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
if (trimmed.startsWith("!")) {
|
|
862
|
+
await this.remote.sendShell(trimmed);
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
866
|
+
options?.preflightResult?.(true);
|
|
867
|
+
await this.remote.sendPrompt(trimmed, behavior);
|
|
868
|
+
}
|
|
869
|
+
async steer(text) {
|
|
870
|
+
const trimmed = text.trim();
|
|
871
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
872
|
+
return;
|
|
873
|
+
await this.remote.sendPrompt(trimmed, "steer");
|
|
874
|
+
}
|
|
875
|
+
async followUp(text) {
|
|
876
|
+
const trimmed = text.trim();
|
|
877
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
878
|
+
return;
|
|
879
|
+
await this.remote.sendPrompt(trimmed, "followUp");
|
|
880
|
+
}
|
|
881
|
+
async abort() {
|
|
882
|
+
await this.remote.abort();
|
|
883
|
+
}
|
|
884
|
+
async compact(customInstructions) {
|
|
885
|
+
const pending = new Promise((resolve3, reject) => {
|
|
886
|
+
this.remote.registerPendingCompaction({ resolve: resolve3, reject });
|
|
968
887
|
});
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
888
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
889
|
+
return pending;
|
|
890
|
+
}
|
|
891
|
+
clearQueue() {
|
|
892
|
+
const cleared = {
|
|
893
|
+
steering: [...this.remote.status.steeringMessages],
|
|
894
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
895
|
+
};
|
|
896
|
+
this.remote.status.steeringMessages = [];
|
|
897
|
+
this.remote.status.followUpMessages = [];
|
|
898
|
+
this.remote.status.pendingMessageCount = 0;
|
|
899
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
900
|
+
return cleared;
|
|
901
|
+
}
|
|
902
|
+
get isStreaming() {
|
|
903
|
+
return this.remote.status.isStreaming;
|
|
904
|
+
}
|
|
905
|
+
get isCompacting() {
|
|
906
|
+
return this.remote.status.isCompacting;
|
|
907
|
+
}
|
|
908
|
+
get isBashRunning() {
|
|
909
|
+
return this.remote.status.isBashRunning;
|
|
910
|
+
}
|
|
911
|
+
get pendingMessageCount() {
|
|
912
|
+
return this.remote.status.pendingMessageCount;
|
|
913
|
+
}
|
|
914
|
+
getSteeringMessages() {
|
|
915
|
+
return this.remote.status.steeringMessages;
|
|
916
|
+
}
|
|
917
|
+
getFollowUpMessages() {
|
|
918
|
+
return this.remote.status.followUpMessages;
|
|
919
|
+
}
|
|
920
|
+
get model() {
|
|
921
|
+
return this.remote.status.model ?? super.model;
|
|
922
|
+
}
|
|
923
|
+
async setModel(model) {
|
|
924
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
925
|
+
this.remote.status.model = model;
|
|
926
|
+
}
|
|
927
|
+
get thinkingLevel() {
|
|
928
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
929
|
+
}
|
|
930
|
+
setThinkingLevel(level) {
|
|
931
|
+
this.remote.status.thinkingLevel = level;
|
|
932
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
933
|
+
}
|
|
934
|
+
get sessionName() {
|
|
935
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
936
|
+
}
|
|
937
|
+
setSessionName(name) {
|
|
938
|
+
this.remote.status.sessionName = name;
|
|
939
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
940
|
+
}
|
|
941
|
+
getSessionStats() {
|
|
942
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
943
|
+
}
|
|
944
|
+
getContextUsage() {
|
|
945
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
946
|
+
}
|
|
947
|
+
dispose() {
|
|
948
|
+
this.remote.close();
|
|
949
|
+
super.dispose();
|
|
978
950
|
}
|
|
979
|
-
await closePromise;
|
|
980
951
|
}
|
|
981
|
-
function createRemoteBashOperations(
|
|
952
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
982
953
|
return {
|
|
983
954
|
exec(command, _cwd, execOptions) {
|
|
984
955
|
return new Promise((resolve3, reject) => {
|
|
985
|
-
const pending = {
|
|
986
|
-
command,
|
|
987
|
-
onData: execOptions.onData,
|
|
988
|
-
resolve: resolve3,
|
|
989
|
-
reject,
|
|
990
|
-
sawChunk: false
|
|
991
|
-
};
|
|
956
|
+
const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
|
|
992
957
|
const cleanup = () => {
|
|
993
958
|
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
994
959
|
if (timer)
|
|
@@ -996,12 +961,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
996
961
|
};
|
|
997
962
|
const onAbort = () => {
|
|
998
963
|
cleanup();
|
|
999
|
-
failPendingShell(
|
|
964
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
1000
965
|
};
|
|
1001
966
|
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
1002
967
|
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
1003
968
|
cleanup();
|
|
1004
|
-
failPendingShell(
|
|
969
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
1005
970
|
}, timeoutMs) : null;
|
|
1006
971
|
const wrappedResolve = pending.resolve;
|
|
1007
972
|
const wrappedReject = pending.reject;
|
|
@@ -1014,125 +979,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
1014
979
|
wrappedReject(error);
|
|
1015
980
|
};
|
|
1016
981
|
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1017
|
-
|
|
1018
|
-
|
|
982
|
+
controller.registerPendingShell(pending);
|
|
983
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
1019
984
|
cleanup();
|
|
1020
|
-
failPendingShell(
|
|
985
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
1021
986
|
});
|
|
1022
987
|
});
|
|
1023
988
|
}
|
|
1024
989
|
};
|
|
1025
990
|
}
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
if (line === "/cancel") {
|
|
1031
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
1032
|
-
} else if (pending.method === "confirm") {
|
|
1033
|
-
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
1034
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
1035
|
-
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
1036
|
-
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
1037
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
1038
|
-
} else {
|
|
1039
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
1040
|
-
}
|
|
1041
|
-
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
1042
|
-
state.pendingUi = null;
|
|
1043
|
-
return true;
|
|
991
|
+
|
|
992
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
993
|
+
function recordOf2(value) {
|
|
994
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1044
995
|
}
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
return;
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
ctx.shutdown();
|
|
1057
|
-
return;
|
|
996
|
+
function asText(value) {
|
|
997
|
+
if (typeof value === "string")
|
|
998
|
+
return value;
|
|
999
|
+
if (value === null || value === undefined)
|
|
1000
|
+
return "";
|
|
1001
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1002
|
+
return String(value);
|
|
1003
|
+
try {
|
|
1004
|
+
return JSON.stringify(value);
|
|
1005
|
+
} catch {
|
|
1006
|
+
return String(value);
|
|
1058
1007
|
}
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1008
|
+
}
|
|
1009
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
1010
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
1011
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
1012
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
1013
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
1014
|
+
const choices = rawOptions.map((option) => {
|
|
1015
|
+
const record = recordOf2(option);
|
|
1016
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
1017
|
+
}).filter(Boolean);
|
|
1018
|
+
try {
|
|
1019
|
+
if (method === "confirm") {
|
|
1020
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
1021
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
if (choices.length > 0) {
|
|
1025
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
1026
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
1030
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1065
1033
|
}
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
const
|
|
1072
|
-
const
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1034
|
+
}
|
|
1035
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
1036
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
1037
|
+
for (const command of commands) {
|
|
1038
|
+
const record = recordOf2(command);
|
|
1039
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
1040
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
1041
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
1042
|
+
continue;
|
|
1043
|
+
registered.add(name);
|
|
1044
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
1045
|
+
try {
|
|
1046
|
+
pi.registerCommand(name, {
|
|
1047
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
1048
|
+
handler: async (args) => {
|
|
1049
|
+
try {
|
|
1050
|
+
const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
1051
|
+
ctx.ui.notify(message, "info");
|
|
1052
|
+
} catch (error) {
|
|
1053
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
});
|
|
1057
|
+
} catch {}
|
|
1077
1058
|
}
|
|
1078
|
-
updatePiUi(ctx, state);
|
|
1079
1059
|
}
|
|
1080
1060
|
function createRigWorkerPiBridgeExtension(options) {
|
|
1081
1061
|
return (pi) => {
|
|
1082
|
-
const state = {
|
|
1083
|
-
transcript: [],
|
|
1084
|
-
status: "starting worker Pi daemon bridge",
|
|
1085
|
-
activity: "",
|
|
1086
|
-
cwd: "",
|
|
1087
|
-
model: "",
|
|
1088
|
-
commands: [],
|
|
1089
|
-
streaming: false,
|
|
1090
|
-
pendingUi: null,
|
|
1091
|
-
pendingShells: [],
|
|
1092
|
-
wsConnected: false,
|
|
1093
|
-
nativeStream: false
|
|
1094
|
-
};
|
|
1095
|
-
if (options.initialMessageSent)
|
|
1096
|
-
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
1097
1062
|
const registeredDaemonCommands = new Set;
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1063
|
+
pi.registerCommand("detach", {
|
|
1064
|
+
description: "Detach from this run; the worker keeps going",
|
|
1065
|
+
handler: async (_args, ctx) => {
|
|
1066
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
1067
|
+
ctx.shutdown();
|
|
1068
|
+
}
|
|
1069
|
+
});
|
|
1070
|
+
pi.registerCommand("stop", {
|
|
1071
|
+
description: "Stop the worker Pi run and detach",
|
|
1072
|
+
handler: async (_args, ctx) => {
|
|
1073
|
+
await options.controller.abort();
|
|
1074
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
1075
|
+
ctx.shutdown();
|
|
1076
|
+
}
|
|
1102
1077
|
});
|
|
1078
|
+
pi.on("user_bash", (event) => ({
|
|
1079
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
1080
|
+
}));
|
|
1103
1081
|
pi.on("session_start", async (_event, ctx) => {
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1082
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
1083
|
+
ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
|
|
1084
|
+
ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
|
|
1085
|
+
if (options.initialMessageSent)
|
|
1086
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
1087
|
+
const nativeUi = ctx.ui;
|
|
1088
|
+
options.controller.setUiHooks({
|
|
1089
|
+
onStatusText: (text) => ctx.ui.setStatus("rig-worker-pi", text),
|
|
1090
|
+
onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
|
|
1091
|
+
onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
|
|
1092
|
+
onError: (message) => ctx.ui.notify(message, "error"),
|
|
1093
|
+
onExtensionUiRequest: (request) => {
|
|
1094
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
1095
|
+
},
|
|
1096
|
+
onCatchUp: (messages, commands) => {
|
|
1097
|
+
if (nativeUi.appendSessionMessages)
|
|
1098
|
+
nativeUi.appendSessionMessages(messages);
|
|
1099
|
+
const cwd = options.controller.status.cwd;
|
|
1100
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
1101
|
+
nativeUi.setDisplayCwd(cwd);
|
|
1102
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
1112
1103
|
}
|
|
1113
|
-
if (!data.includes("\r") && !data.includes(`
|
|
1114
|
-
`))
|
|
1115
|
-
return;
|
|
1116
|
-
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
1117
|
-
const editorText = ctx.ui.getEditorText().trim();
|
|
1118
|
-
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
1119
|
-
if (!text)
|
|
1120
|
-
return;
|
|
1121
|
-
if (text.startsWith("!"))
|
|
1122
|
-
return;
|
|
1123
|
-
ctx.ui.setEditorText("");
|
|
1124
|
-
routeInput(options, ctx, state, text).catch((error) => {
|
|
1125
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1126
|
-
updatePiUi(ctx, state);
|
|
1127
|
-
});
|
|
1128
|
-
return { consume: true };
|
|
1129
1104
|
});
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
updatePiUi(ctx, state);
|
|
1105
|
+
options.controller.connect().catch((error) => {
|
|
1106
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1133
1107
|
});
|
|
1134
1108
|
});
|
|
1135
|
-
pi.on("session_shutdown", () => {
|
|
1109
|
+
pi.on("session_shutdown", () => {
|
|
1110
|
+
options.controller.close();
|
|
1111
|
+
});
|
|
1136
1112
|
};
|
|
1137
1113
|
}
|
|
1138
1114
|
|
|
@@ -1153,43 +1129,47 @@ function setTemporaryEnv(updates) {
|
|
|
1153
1129
|
};
|
|
1154
1130
|
}
|
|
1155
1131
|
async function attachRunBundledPiFrontend(context, input) {
|
|
1156
|
-
const
|
|
1157
|
-
const cwd = join(tempRoot, "workspace");
|
|
1158
|
-
const agentDir = join(tempRoot, "agent");
|
|
1159
|
-
const sessionDir = join(tempRoot, "sessions");
|
|
1160
|
-
const previousCwd = process.cwd();
|
|
1132
|
+
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
1161
1133
|
const restoreEnv = setTemporaryEnv({
|
|
1162
|
-
|
|
1163
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
1164
|
-
PI_OFFLINE: "1",
|
|
1134
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
1165
1135
|
PI_SKIP_VERSION_CHECK: "1"
|
|
1166
1136
|
});
|
|
1137
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
1138
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
1139
|
+
const services = await createAgentSessionServices({
|
|
1140
|
+
cwd,
|
|
1141
|
+
agentDir,
|
|
1142
|
+
resourceLoaderOptions: {
|
|
1143
|
+
extensionFactories: [
|
|
1144
|
+
createRigWorkerPiBridgeExtension({
|
|
1145
|
+
context,
|
|
1146
|
+
controller,
|
|
1147
|
+
runId: input.runId,
|
|
1148
|
+
initialMessageSent: input.steered === true
|
|
1149
|
+
})
|
|
1150
|
+
],
|
|
1151
|
+
noContextFiles: true
|
|
1152
|
+
}
|
|
1153
|
+
});
|
|
1154
|
+
const created = await createAgentSessionFromServices({
|
|
1155
|
+
services,
|
|
1156
|
+
sessionManager,
|
|
1157
|
+
sessionStartEvent,
|
|
1158
|
+
noTools: "all",
|
|
1159
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
1160
|
+
});
|
|
1161
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
1162
|
+
};
|
|
1167
1163
|
let detached = false;
|
|
1168
1164
|
try {
|
|
1169
|
-
await
|
|
1170
|
-
|
|
1171
|
-
await runPiMain([
|
|
1172
|
-
"--offline",
|
|
1173
|
-
"--no-session",
|
|
1174
|
-
"--no-tools",
|
|
1175
|
-
"--no-builtin-tools",
|
|
1176
|
-
"--no-skills",
|
|
1177
|
-
"--no-context-files",
|
|
1178
|
-
"--no-approve"
|
|
1179
|
-
], {
|
|
1180
|
-
extensionFactories: [
|
|
1181
|
-
createRigWorkerPiBridgeExtension({
|
|
1182
|
-
context,
|
|
1183
|
-
runId: input.runId,
|
|
1184
|
-
initialMessageSent: input.steered === true
|
|
1185
|
-
})
|
|
1186
|
-
]
|
|
1165
|
+
await runPiMain([], {
|
|
1166
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
1187
1167
|
});
|
|
1188
1168
|
detached = true;
|
|
1189
1169
|
} finally {
|
|
1190
|
-
process.chdir(previousCwd);
|
|
1191
1170
|
restoreEnv();
|
|
1192
|
-
|
|
1171
|
+
controller.close();
|
|
1172
|
+
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
1193
1173
|
}
|
|
1194
1174
|
let run = { runId: input.runId, status: "unknown" };
|
|
1195
1175
|
try {
|
|
@@ -1202,7 +1182,7 @@ async function attachRunBundledPiFrontend(context, input) {
|
|
|
1202
1182
|
timelineCursor: null,
|
|
1203
1183
|
steered: input.steered === true,
|
|
1204
1184
|
detached,
|
|
1205
|
-
rendered: "
|
|
1185
|
+
rendered: "native bundled Pi frontend with remote worker session runtime"
|
|
1206
1186
|
};
|
|
1207
1187
|
}
|
|
1208
1188
|
|