@h-rig/cli 0.0.6-alpha.40 → 0.0.6-alpha.41

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.
@@ -560,435 +560,394 @@ function createOperatorSurface(options = {}) {
560
560
  import { mkdtempSync, rmSync } from "fs";
561
561
  import { tmpdir } from "os";
562
562
  import { join } from "path";
563
- import { main as runPiMain } from "@earendil-works/pi-coding-agent";
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-worker-bridge-extension.ts
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
- var MAX_TRANSCRIPT_LINES = 120;
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 asText(value) {
572
- if (typeof value === "string")
573
- return value;
574
- if (value === null || value === undefined)
575
- return "";
576
- if (typeof value === "number" || typeof value === "boolean")
577
- return String(value);
578
- try {
579
- return JSON.stringify(value);
580
- } catch {
581
- return String(value);
582
- }
583
- }
584
- function textFromContent(content) {
585
- if (typeof content === "string")
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
- function formatElapsed(sinceMs) {
833
- const totalSeconds = Math.floor((Date.now() - sinceMs) / 1000);
834
- const minutes = Math.floor(totalSeconds / 60);
835
- const seconds = totalSeconds % 60;
836
- return minutes > 0 ? `${minutes}m${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
837
- }
838
- async function waitForWorkerReady(options, ctx, state) {
839
- const startedAt = Date.now();
840
- const deadline = startedAt + resolveAttachReadyTimeoutMs();
841
- let consecutiveFailures = 0;
842
- while (true) {
843
- let requestFailed = false;
844
- const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => {
845
- requestFailed = true;
846
- return {
847
- ready: false,
848
- status: error instanceof Error ? error.message : String(error),
849
- retryAfterMs: 1000
850
- };
851
- });
852
- if (session.ready === false) {
853
- consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
854
- const status = String(session.status ?? "starting");
855
- if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
856
- reportBridgeError(ctx, state, `Run ended before worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${options.runId}\`; restart with \`rig task run --task <id>\`.`);
857
- return false;
858
- }
859
- if (consecutiveFailures >= 5) {
860
- state.status = `Rig server unreachable \xB7 retrying (${formatElapsed(startedAt)}) \xB7 /detach to exit`;
861
- } else {
862
- state.status = `waiting for worker Pi daemon \xB7 ${status} \xB7 ${formatElapsed(startedAt)} \xB7 /detach to exit`;
863
- }
864
- updatePiUi(ctx, state);
865
- if (Date.now() >= deadline) {
866
- reportBridgeError(ctx, state, `Worker Pi daemon did not become ready within ${formatElapsed(startedAt)} (last status: ${status}). ` + `Check \`rig run show ${options.runId}\` and \`rig doctor\`; the run may have been restarted by a server deploy. ` + "Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.");
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
- state.wsConnected = true;
925
- state.status = "live worker Pi WebSocket connected";
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 = parseWsPayload(message);
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(ctx, state, payload);
935
- updatePiUi(ctx, state);
936
- }
652
+ else
653
+ this.applyEnvelope(payload);
937
654
  } catch (error) {
938
- appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
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
- state.wsConnected = false;
945
- state.status = "worker Pi WebSocket disconnected";
946
- updatePiUi(ctx, state);
947
- resolve3();
660
+ this.hooks.onConnectionChange?.(false);
661
+ if (!this.closed)
662
+ this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
948
663
  };
949
- });
950
- try {
951
- const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
952
- getRunPiMessagesViaServer(options.context, options.runId),
953
- getRunPiStatusViaServer(options.context, options.runId),
954
- getRunPiCommandsViaServer(options.context, options.runId)
955
- ]);
956
- const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
957
- const native = nativePiUi(ctx);
958
- if (state.nativeStream && native?.appendSessionMessages)
959
- native.appendSessionMessages(messages);
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
- for (const message of messages)
962
- applyMessage(state, message);
963
- applyStatus(state, statusPayload);
964
- const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
965
- state.commands = commands.flatMap((command) => {
966
- const record = recordOf(command);
967
- return typeof record?.name === "string" ? [`/${record.name}`] : [];
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
+ await this.remote.sendPrompt(text, "steer");
871
+ }
872
+ async followUp(text) {
873
+ await this.remote.sendPrompt(text, "followUp");
874
+ }
875
+ async abort() {
876
+ await this.remote.abort();
877
+ }
878
+ async compact(customInstructions) {
879
+ const pending = new Promise((resolve3, reject) => {
880
+ this.remote.registerPendingCompaction({ resolve: resolve3, reject });
968
881
  });
969
- registerDaemonCommandsNatively(pi, options, ctx, state, commands, registeredDaemonCommands);
970
- catchupDone = true;
971
- for (const payload of buffered.splice(0))
972
- applyEnvelope(ctx, state, payload);
973
- updatePiUi(ctx, state);
974
- } catch (error) {
975
- appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
976
- catchupDone = true;
977
- updatePiUi(ctx, state);
882
+ await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
883
+ return pending;
884
+ }
885
+ clearQueue() {
886
+ const cleared = {
887
+ steering: [...this.remote.status.steeringMessages],
888
+ followUp: [...this.remote.status.followUpMessages]
889
+ };
890
+ this.remote.status.steeringMessages = [];
891
+ this.remote.status.followUpMessages = [];
892
+ this.remote.status.pendingMessageCount = 0;
893
+ this.remote.sendCommand("/queue-clear").catch(() => {});
894
+ return cleared;
895
+ }
896
+ get isStreaming() {
897
+ return this.remote.status.isStreaming;
898
+ }
899
+ get isCompacting() {
900
+ return this.remote.status.isCompacting;
901
+ }
902
+ get isBashRunning() {
903
+ return this.remote.status.isBashRunning;
904
+ }
905
+ get pendingMessageCount() {
906
+ return this.remote.status.pendingMessageCount;
907
+ }
908
+ getSteeringMessages() {
909
+ return this.remote.status.steeringMessages;
910
+ }
911
+ getFollowUpMessages() {
912
+ return this.remote.status.followUpMessages;
913
+ }
914
+ get model() {
915
+ return this.remote.status.model ?? super.model;
916
+ }
917
+ async setModel(model) {
918
+ await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
919
+ this.remote.status.model = model;
920
+ }
921
+ get thinkingLevel() {
922
+ return this.remote.status.thinkingLevel ?? super.thinkingLevel;
923
+ }
924
+ setThinkingLevel(level) {
925
+ this.remote.status.thinkingLevel = level;
926
+ this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
927
+ }
928
+ get sessionName() {
929
+ return this.remote.status.sessionName ?? super.sessionName;
930
+ }
931
+ setSessionName(name) {
932
+ this.remote.status.sessionName = name;
933
+ this.remote.sendCommand(`/name ${name}`).catch(() => {});
934
+ }
935
+ getSessionStats() {
936
+ return this.remote.status.stats ?? super.getSessionStats();
937
+ }
938
+ getContextUsage() {
939
+ return this.remote.status.contextUsage ?? super.getContextUsage();
940
+ }
941
+ dispose() {
942
+ this.remote.close();
943
+ super.dispose();
978
944
  }
979
- await closePromise;
980
945
  }
981
- function createRemoteBashOperations(options, state, excludeFromContext) {
946
+ function createRemoteBashOperations(controller, excludeFromContext) {
982
947
  return {
983
948
  exec(command, _cwd, execOptions) {
984
949
  return new Promise((resolve3, reject) => {
985
- const pending = {
986
- command,
987
- onData: execOptions.onData,
988
- resolve: resolve3,
989
- reject,
990
- sawChunk: false
991
- };
950
+ const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
992
951
  const cleanup = () => {
993
952
  execOptions.signal?.removeEventListener("abort", onAbort);
994
953
  if (timer)
@@ -996,12 +955,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
996
955
  };
997
956
  const onAbort = () => {
998
957
  cleanup();
999
- failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
958
+ controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
1000
959
  };
1001
960
  const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
1002
961
  const timer = timeoutMs > 0 ? setTimeout(() => {
1003
962
  cleanup();
1004
- failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
963
+ controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
1005
964
  }, timeoutMs) : null;
1006
965
  const wrappedResolve = pending.resolve;
1007
966
  const wrappedReject = pending.reject;
@@ -1014,125 +973,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
1014
973
  wrappedReject(error);
1015
974
  };
1016
975
  execOptions.signal?.addEventListener("abort", onAbort, { once: true });
1017
- state.pendingShells.push(pending);
1018
- sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
976
+ controller.registerPendingShell(pending);
977
+ controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
1019
978
  cleanup();
1020
- failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
979
+ controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
1021
980
  });
1022
981
  });
1023
982
  }
1024
983
  };
1025
984
  }
1026
- async function answerPendingUi(options, state, line) {
1027
- const pending = state.pendingUi;
1028
- if (!pending)
1029
- return false;
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;
985
+
986
+ // packages/cli/src/commands/_pi-worker-bridge-extension.ts
987
+ function recordOf2(value) {
988
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1044
989
  }
1045
- async function routeInput(options, ctx, state, line) {
1046
- const text = line.trim();
1047
- if (!text)
1048
- return;
1049
- if (await answerPendingUi(options, state, text)) {
1050
- updatePiUi(ctx, state);
1051
- return;
1052
- }
1053
- if (text === "/detach" || text === "/quit" || text === "/q") {
1054
- appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
1055
- updatePiUi(ctx, state);
1056
- ctx.shutdown();
1057
- return;
990
+ function asText(value) {
991
+ if (typeof value === "string")
992
+ return value;
993
+ if (value === null || value === undefined)
994
+ return "";
995
+ if (typeof value === "number" || typeof value === "boolean")
996
+ return String(value);
997
+ try {
998
+ return JSON.stringify(value);
999
+ } catch {
1000
+ return String(value);
1058
1001
  }
1059
- if (text === "/stop") {
1060
- await abortRunPiViaServer(options.context, options.runId);
1061
- appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
1062
- updatePiUi(ctx, state);
1063
- ctx.shutdown();
1064
- return;
1002
+ }
1003
+ async function answerExtensionUiRequest(options, ctx, request) {
1004
+ const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
1005
+ const method = String(request.method ?? request.type ?? "input");
1006
+ const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
1007
+ const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
1008
+ const choices = rawOptions.map((option) => {
1009
+ const record = recordOf2(option);
1010
+ return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
1011
+ }).filter(Boolean);
1012
+ try {
1013
+ if (method === "confirm") {
1014
+ const confirmed = await ctx.ui.confirm("Worker request", prompt);
1015
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
1016
+ return;
1017
+ }
1018
+ if (choices.length > 0) {
1019
+ const selected = await ctx.ui.select(prompt, choices);
1020
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
1021
+ return;
1022
+ }
1023
+ const value = await ctx.ui.input("Worker request", prompt);
1024
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
1025
+ } catch (error) {
1026
+ ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
1065
1027
  }
1066
- if (text.startsWith("!")) {
1067
- appendTranscript(state, "You", text);
1068
- await sendRunPiShellViaServer(options.context, options.runId, text);
1069
- } else if (text.startsWith("/")) {
1070
- appendTranscript(state, "You", text);
1071
- const result = await runRunPiCommandViaServer(options.context, options.runId, text);
1072
- const message = typeof result.message === "string" ? result.message : "worker command accepted";
1073
- appendTranscript(state, "System", message);
1074
- } else {
1075
- appendTranscript(state, "You", text);
1076
- await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
1028
+ }
1029
+ var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
1030
+ function registerDaemonCommands(pi, options, ctx, commands, registered) {
1031
+ for (const command of commands) {
1032
+ const record = recordOf2(command);
1033
+ const name = typeof record?.name === "string" ? record.name : "";
1034
+ const source = typeof record?.source === "string" ? record.source : "worker";
1035
+ if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
1036
+ continue;
1037
+ registered.add(name);
1038
+ const description = typeof record?.description === "string" ? record.description : undefined;
1039
+ try {
1040
+ pi.registerCommand(name, {
1041
+ description: `[worker ${source}] ${description ?? ""}`.trim(),
1042
+ handler: async (args) => {
1043
+ try {
1044
+ const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
1045
+ ctx.ui.notify(message, "info");
1046
+ } catch (error) {
1047
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1048
+ }
1049
+ }
1050
+ });
1051
+ } catch {}
1077
1052
  }
1078
- updatePiUi(ctx, state);
1079
1053
  }
1080
1054
  function createRigWorkerPiBridgeExtension(options) {
1081
1055
  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
1056
  const registeredDaemonCommands = new Set;
1098
- let nativePiUiContextAvailable = false;
1099
- pi.on("user_bash", (event) => {
1100
- state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
1101
- return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
1057
+ pi.registerCommand("detach", {
1058
+ description: "Detach from this run; the worker keeps going",
1059
+ handler: async (_args, ctx) => {
1060
+ ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
1061
+ ctx.shutdown();
1062
+ }
1102
1063
  });
1064
+ pi.registerCommand("stop", {
1065
+ description: "Stop the worker Pi run and detach",
1066
+ handler: async (_args, ctx) => {
1067
+ await options.controller.abort();
1068
+ ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
1069
+ ctx.shutdown();
1070
+ }
1071
+ });
1072
+ pi.on("user_bash", (event) => ({
1073
+ operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
1074
+ }));
1103
1075
  pi.on("session_start", async (_event, ctx) => {
1104
- nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
1105
- state.nativeStream = nativePiUiContextAvailable;
1106
- updatePiUi(ctx, state);
1107
- ctx.ui.notify(nativePiUiContextAvailable ? "Connected to the Rig worker session (native stream). /detach exits, /stop cancels the run." : "Connected to the Rig worker session (transcript view). /detach exits, /stop cancels the run.", "info");
1108
- ctx.ui.onTerminalInput((data) => {
1109
- if (data.includes("\x04")) {
1110
- ctx.shutdown();
1111
- return { consume: true };
1076
+ ctx.ui.setTitle("Rig \xB7 worker session");
1077
+ ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
1078
+ ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
1079
+ if (options.initialMessageSent)
1080
+ ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
1081
+ const nativeUi = ctx.ui;
1082
+ options.controller.setUiHooks({
1083
+ onStatusText: (text) => ctx.ui.setStatus("rig-worker-pi", text),
1084
+ onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
1085
+ onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
1086
+ onError: (message) => ctx.ui.notify(message, "error"),
1087
+ onExtensionUiRequest: (request) => {
1088
+ answerExtensionUiRequest(options, ctx, request);
1089
+ },
1090
+ onCatchUp: (messages, commands) => {
1091
+ if (nativeUi.appendSessionMessages)
1092
+ nativeUi.appendSessionMessages(messages);
1093
+ const cwd = options.controller.status.cwd;
1094
+ if (nativeUi.setDisplayCwd && cwd)
1095
+ nativeUi.setDisplayCwd(cwd);
1096
+ registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
1112
1097
  }
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
1098
  });
1130
- connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands).catch((error) => {
1131
- appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
1132
- updatePiUi(ctx, state);
1099
+ options.controller.connect().catch((error) => {
1100
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1133
1101
  });
1134
1102
  });
1135
- pi.on("session_shutdown", () => {});
1103
+ pi.on("session_shutdown", () => {
1104
+ options.controller.close();
1105
+ });
1136
1106
  };
1137
1107
  }
1138
1108
 
@@ -1153,43 +1123,47 @@ function setTemporaryEnv(updates) {
1153
1123
  };
1154
1124
  }
1155
1125
  async function attachRunBundledPiFrontend(context, input) {
1156
- const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
1157
- const cwd = join(tempRoot, "workspace");
1158
- const agentDir = join(tempRoot, "agent");
1159
- const sessionDir = join(tempRoot, "sessions");
1160
- const previousCwd = process.cwd();
1126
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1161
1127
  const restoreEnv = setTemporaryEnv({
1162
- PI_CODING_AGENT_DIR: agentDir,
1163
- PI_CODING_AGENT_SESSION_DIR: sessionDir,
1164
- PI_OFFLINE: "1",
1128
+ PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
1165
1129
  PI_SKIP_VERSION_CHECK: "1"
1166
1130
  });
1131
+ const controller = new RigRemoteSessionController({ context, runId: input.runId });
1132
+ const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
1133
+ const services = await createAgentSessionServices({
1134
+ cwd,
1135
+ agentDir,
1136
+ resourceLoaderOptions: {
1137
+ extensionFactories: [
1138
+ createRigWorkerPiBridgeExtension({
1139
+ context,
1140
+ controller,
1141
+ runId: input.runId,
1142
+ initialMessageSent: input.steered === true
1143
+ })
1144
+ ],
1145
+ noContextFiles: true
1146
+ }
1147
+ });
1148
+ const created = await createAgentSessionFromServices({
1149
+ services,
1150
+ sessionManager,
1151
+ sessionStartEvent,
1152
+ noTools: "all",
1153
+ sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
1154
+ });
1155
+ return { ...created, services, diagnostics: services.diagnostics };
1156
+ };
1167
1157
  let detached = false;
1168
1158
  try {
1169
- await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
1170
- process.chdir(cwd);
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
- ]
1159
+ await runPiMain([], {
1160
+ createRuntimeOverride: () => createRemoteRuntime
1187
1161
  });
1188
1162
  detached = true;
1189
1163
  } finally {
1190
- process.chdir(previousCwd);
1191
1164
  restoreEnv();
1192
- rmSync(tempRoot, { recursive: true, force: true });
1165
+ controller.close();
1166
+ rmSync(tempSessionDir, { recursive: true, force: true });
1193
1167
  }
1194
1168
  let run = { runId: input.runId, status: "unknown" };
1195
1169
  try {
@@ -1202,7 +1176,7 @@ async function attachRunBundledPiFrontend(context, input) {
1202
1176
  timelineCursor: null,
1203
1177
  steered: input.steered === true,
1204
1178
  detached,
1205
- rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
1179
+ rendered: "native bundled Pi frontend with remote worker session runtime"
1206
1180
  };
1207
1181
  }
1208
1182