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