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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,4 @@
1
1
  // @bun
2
- var __require = import.meta.require;
3
-
4
2
  // packages/cli/src/commands/_server-client.ts
5
3
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
6
4
  import { resolve as resolve2 } from "path";
@@ -229,6 +227,66 @@ async function steerRunViaServer(context, runId, message) {
229
227
  });
230
228
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
231
229
  }
230
+ async function getRunPiSessionViaServer(context, runId) {
231
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
232
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
233
+ }
234
+ async function getRunPiMessagesViaServer(context, runId) {
235
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
236
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
237
+ }
238
+ async function getRunPiStatusViaServer(context, runId) {
239
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
240
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
241
+ }
242
+ async function getRunPiCommandsViaServer(context, runId) {
243
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
244
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
245
+ }
246
+ async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
247
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
248
+ method: "POST",
249
+ headers: { "content-type": "application/json" },
250
+ body: JSON.stringify({ text, streamingBehavior })
251
+ });
252
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
253
+ }
254
+ async function sendRunPiShellViaServer(context, runId, text) {
255
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
256
+ method: "POST",
257
+ headers: { "content-type": "application/json" },
258
+ body: JSON.stringify({ text })
259
+ });
260
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
261
+ }
262
+ async function runRunPiCommandViaServer(context, runId, text) {
263
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
264
+ method: "POST",
265
+ headers: { "content-type": "application/json" },
266
+ body: JSON.stringify({ text })
267
+ });
268
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
269
+ }
270
+ async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
271
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
272
+ method: "POST",
273
+ headers: { "content-type": "application/json" },
274
+ body: JSON.stringify({ requestId, ...valueOrCancel })
275
+ });
276
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
277
+ }
278
+ async function abortRunPiViaServer(context, runId) {
279
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
280
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
281
+ }
282
+ async function buildRunPiEventsWebSocketUrl(context, runId) {
283
+ const server = await ensureServerForCli(context.projectRoot);
284
+ const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
285
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
286
+ if (server.authToken)
287
+ url.searchParams.set("token", server.authToken);
288
+ return url.toString();
289
+ }
232
290
 
233
291
  // packages/cli/src/commands/_operator-surface.ts
234
292
  import { createInterface } from "readline";
@@ -406,52 +464,593 @@ function createOperatorSurface(options = {}) {
406
464
  };
407
465
  }
408
466
 
409
- // packages/cli/src/commands/_operator-view.ts
467
+ // packages/cli/src/commands/_pi-frontend.ts
468
+ import { mkdtempSync, rmSync } from "fs";
469
+ import { tmpdir } from "os";
470
+ import { join } from "path";
471
+ import { main as runPiMain } from "@earendil-works/pi-coding-agent";
472
+
473
+ // packages/cli/src/commands/_pi-worker-bridge-extension.ts
410
474
  var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
411
- var CANONICAL_STAGES2 = [
412
- "Connect",
413
- "GitHub/task sync",
414
- "Prepare workspace",
415
- "Launch Pi",
416
- "Plan",
417
- "Implement",
418
- "Validate",
419
- "Commit",
420
- "Open PR",
421
- "Review/CI",
422
- "Merge",
423
- "Complete"
424
- ];
425
- var GREEN = "\x1B[32m";
426
- var BLUE = "\x1B[34m";
427
- var MAGENTA = "\x1B[35m";
428
- var YELLOW = "\x1B[33m";
429
- var RED = "\x1B[31m";
430
- var DIM = "\x1B[2m";
431
- var BOLD = "\x1B[1m";
432
- var RESET = "\x1B[0m";
433
- async function loadPiTuiRuntime() {
475
+ var MAX_TRANSCRIPT_LINES = 120;
476
+ function recordOf(value) {
477
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
478
+ }
479
+ function asText(value) {
480
+ if (typeof value === "string")
481
+ return value;
482
+ if (value === null || value === undefined)
483
+ return "";
484
+ if (typeof value === "number" || typeof value === "boolean")
485
+ return String(value);
434
486
  try {
435
- return await import("@earendil-works/pi-tui");
487
+ return JSON.stringify(value);
436
488
  } catch {
437
- const base = new URL("../../../pi/packages/tui/src/", import.meta.url);
438
- const [tui, input, terminal, keys, utils] = await Promise.all([
439
- import(new URL("tui.ts", base).href),
440
- import(new URL("components/input.ts", base).href),
441
- import(new URL("terminal.ts", base).href),
442
- import(new URL("keys.ts", base).href),
443
- import(new URL("utils.ts", base).href)
489
+ return String(value);
490
+ }
491
+ }
492
+ function textFromContent(content) {
493
+ if (typeof content === "string")
494
+ return content;
495
+ if (!Array.isArray(content))
496
+ return asText(content);
497
+ return content.flatMap((part) => {
498
+ const item = recordOf(part);
499
+ if (!item)
500
+ return [];
501
+ if (typeof item.text === "string")
502
+ return [item.text];
503
+ if (typeof item.content === "string")
504
+ return [item.content];
505
+ if (item.type === "toolCall")
506
+ return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
507
+ if (item.type === "toolResult")
508
+ return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
509
+ return [];
510
+ }).join(`
511
+ `);
512
+ }
513
+ function appendTranscript(state, label, text) {
514
+ const trimmed = text.trimEnd();
515
+ if (!trimmed)
516
+ return;
517
+ const lines = trimmed.split(/\r?\n/);
518
+ state.transcript.push(`${label}: ${lines[0] ?? ""}`);
519
+ for (const line of lines.slice(1))
520
+ state.transcript.push(` ${line}`);
521
+ if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
522
+ state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
523
+ }
524
+ }
525
+ function nativePiUi(ctx) {
526
+ const ui = ctx.ui;
527
+ return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
528
+ }
529
+ function syncNativeDisplayCwd(ctx, state) {
530
+ const ui = nativePiUi(ctx);
531
+ if (ui?.setDisplayCwd && state.cwd)
532
+ ui.setDisplayCwd(state.cwd);
533
+ }
534
+ function parseExtensionUiRequest(value) {
535
+ const request = recordOf(value) ?? {};
536
+ const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
537
+ const method = String(request.method ?? request.type ?? "input");
538
+ const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
539
+ const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
540
+ const options = rawOptions.map((option) => {
541
+ const record = recordOf(option);
542
+ return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
543
+ }).filter(Boolean);
544
+ return { requestId, method, prompt, options };
545
+ }
546
+ function renderBridgeWidget(state) {
547
+ const statusParts = [
548
+ state.wsConnected ? "live WS" : "WS pending",
549
+ state.status,
550
+ state.model,
551
+ state.cwd
552
+ ].filter(Boolean);
553
+ const lines = [`Worker Pi daemon bridge \xB7 ${statusParts.join(" \xB7 ")}`];
554
+ if (state.activity)
555
+ lines.push(state.activity);
556
+ if (state.commands.length > 0) {
557
+ lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
558
+ }
559
+ lines.push("");
560
+ if (state.transcript.length > 0) {
561
+ lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
562
+ } else {
563
+ lines.push("Waiting for worker Pi daemon transcript\u2026");
564
+ }
565
+ if (state.pendingUi) {
566
+ lines.push("");
567
+ lines.push(`Extension UI request \xB7 ${state.pendingUi.method}`);
568
+ lines.push(state.pendingUi.prompt);
569
+ state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
570
+ lines.push("Reply in the Pi editor. /cancel cancels this request.");
571
+ }
572
+ return lines;
573
+ }
574
+ function updatePiUi(ctx, state) {
575
+ ctx.ui.setTitle("Pi \xB7 Rig worker daemon");
576
+ ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker Pi WS live" : state.status);
577
+ syncNativeDisplayCwd(ctx, state);
578
+ if (state.nativeStream && nativePiUi(ctx)) {
579
+ ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
580
+ return;
581
+ }
582
+ ctx.ui.setWorkingVisible(false);
583
+ ctx.ui.setWidget("rig-worker-pi-transcript", [`Worker Pi daemon bridge \xB7 degraded widget transcript`, ...renderBridgeWidget(state)], { placement: "aboveEditor" });
584
+ }
585
+ function applyStatus(state, payload) {
586
+ const status = recordOf(payload.status) ?? payload;
587
+ state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
588
+ state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
589
+ state.model = typeof status.model === "string" ? status.model : state.model;
590
+ const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
591
+ state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
592
+ }
593
+ function applyMessage(state, message) {
594
+ const record = recordOf(message);
595
+ if (!record)
596
+ return;
597
+ const role = String(record.role ?? "system");
598
+ const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
599
+ appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
600
+ }
601
+ function applyPiEvent(ctx, state, eventValue) {
602
+ const event = recordOf(eventValue);
603
+ if (!event)
604
+ return;
605
+ const type = String(event.type ?? "event");
606
+ if (type === "agent_start") {
607
+ state.streaming = true;
608
+ state.status = "streaming";
609
+ } else if (type === "agent_end") {
610
+ state.streaming = false;
611
+ state.status = "idle";
612
+ } else if (type === "queue_update") {
613
+ const steering = Array.isArray(event.steering) ? event.steering.length : 0;
614
+ const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
615
+ state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
616
+ }
617
+ const native = nativePiUi(ctx);
618
+ if (state.nativeStream && native?.emitSessionEvent) {
619
+ native.emitSessionEvent(eventValue);
620
+ return;
621
+ }
622
+ if (type === "agent_end") {
623
+ appendTranscript(state, "System", "Agent turn complete.");
624
+ return;
625
+ }
626
+ if (type === "message_start" || type === "message_end" || type === "turn_end") {
627
+ applyMessage(state, event.message);
628
+ return;
629
+ }
630
+ if (type === "message_update") {
631
+ const assistantEvent = recordOf(event.assistantMessageEvent);
632
+ const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
633
+ if (delta)
634
+ appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
635
+ return;
636
+ }
637
+ if (type === "tool_execution_start") {
638
+ appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
639
+ return;
640
+ }
641
+ if (type === "tool_execution_update") {
642
+ appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
643
+ return;
644
+ }
645
+ if (type === "tool_execution_end") {
646
+ appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
647
+ }
648
+ }
649
+ function firstPendingShell(state) {
650
+ return state.pendingShells[0];
651
+ }
652
+ function finishPendingShell(state, shell, result) {
653
+ const index = state.pendingShells.indexOf(shell);
654
+ if (index !== -1)
655
+ state.pendingShells.splice(index, 1);
656
+ shell.resolve(result);
657
+ }
658
+ function failPendingShell(state, shell, error) {
659
+ const index = state.pendingShells.indexOf(shell);
660
+ if (index !== -1)
661
+ state.pendingShells.splice(index, 1);
662
+ shell.reject(error);
663
+ }
664
+ function applyUiEvent(state, value) {
665
+ const event = recordOf(value);
666
+ if (!event)
667
+ return;
668
+ const type = String(event.type ?? "ui");
669
+ if (type === "shell.chunk") {
670
+ const pending = firstPendingShell(state);
671
+ const chunk = asText(event.chunk);
672
+ if (pending) {
673
+ pending.sawChunk = true;
674
+ pending.onData(Buffer.from(chunk));
675
+ } else {
676
+ appendTranscript(state, "Tool", chunk);
677
+ }
678
+ return;
679
+ }
680
+ if (type === "shell.end") {
681
+ const pending = firstPendingShell(state);
682
+ const output = asText(event.output ?? "");
683
+ const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
684
+ if (pending) {
685
+ if (output && !pending.sawChunk)
686
+ pending.onData(Buffer.from(output));
687
+ finishPendingShell(state, pending, { exitCode });
688
+ } else {
689
+ appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
690
+ }
691
+ return;
692
+ }
693
+ if (type === "shell.start") {
694
+ if (!firstPendingShell(state))
695
+ appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
696
+ return;
697
+ }
698
+ appendTranscript(state, "System", `${type}: ${asText(event)}`);
699
+ }
700
+ function applyEnvelope(ctx, state, envelopeValue) {
701
+ const envelope = recordOf(envelopeValue);
702
+ if (!envelope)
703
+ return;
704
+ const type = String(envelope.type ?? "");
705
+ if (type === "ready") {
706
+ const metadata = recordOf(envelope.metadata);
707
+ state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
708
+ state.status = "worker Pi daemon ready";
709
+ if (!state.nativeStream)
710
+ appendTranscript(state, "System", "Connected to worker Pi daemon.");
711
+ } else if (type === "status.update") {
712
+ applyStatus(state, envelope);
713
+ } else if (type === "activity.update") {
714
+ const activity = recordOf(envelope.activity);
715
+ state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
716
+ } else if (type === "extension_ui_request") {
717
+ state.pendingUi = parseExtensionUiRequest(envelope.request);
718
+ appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
719
+ } else if (type === "pi.ui_event") {
720
+ applyUiEvent(state, envelope.event);
721
+ } else if (type === "pi.event") {
722
+ applyPiEvent(ctx, state, envelope.event);
723
+ } else if (type === "error") {
724
+ appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
725
+ }
726
+ syncNativeDisplayCwd(ctx, state);
727
+ }
728
+ async function waitForWorkerReady(options, ctx, state) {
729
+ while (true) {
730
+ const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => ({
731
+ ready: false,
732
+ status: error instanceof Error ? error.message : String(error),
733
+ retryAfterMs: 1000
734
+ }));
735
+ if (session.ready === false) {
736
+ const status = String(session.status ?? "starting");
737
+ state.status = `waiting for worker Pi daemon \xB7 ${status}`;
738
+ updatePiUi(ctx, state);
739
+ if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
740
+ appendTranscript(state, "Error", `Run ended before worker Pi daemon became ready: ${status}`);
741
+ return false;
742
+ }
743
+ await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
744
+ continue;
745
+ }
746
+ const sessionRecord = recordOf(session) ?? {};
747
+ applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
748
+ updatePiUi(ctx, state);
749
+ return true;
750
+ }
751
+ }
752
+ function parseWsPayload(message) {
753
+ if (typeof message.data === "string")
754
+ return JSON.parse(message.data);
755
+ return JSON.parse(Buffer.from(message.data).toString("utf8"));
756
+ }
757
+ async function connectWorkerStream(options, ctx, state) {
758
+ const ready = await waitForWorkerReady(options, ctx, state);
759
+ if (!ready)
760
+ return;
761
+ let catchupDone = false;
762
+ const buffered = [];
763
+ const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
764
+ const socket = new WebSocket(wsUrl);
765
+ const closePromise = new Promise((resolve3) => {
766
+ socket.onopen = () => {
767
+ state.wsConnected = true;
768
+ state.status = "live worker Pi WebSocket connected";
769
+ updatePiUi(ctx, state);
770
+ };
771
+ socket.onmessage = (message) => {
772
+ try {
773
+ const payload = parseWsPayload(message);
774
+ if (!catchupDone)
775
+ buffered.push(payload);
776
+ else {
777
+ applyEnvelope(ctx, state, payload);
778
+ updatePiUi(ctx, state);
779
+ }
780
+ } catch (error) {
781
+ appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
782
+ updatePiUi(ctx, state);
783
+ }
784
+ };
785
+ socket.onerror = () => socket.close();
786
+ socket.onclose = () => {
787
+ state.wsConnected = false;
788
+ state.status = "worker Pi WebSocket disconnected";
789
+ updatePiUi(ctx, state);
790
+ resolve3();
791
+ };
792
+ });
793
+ try {
794
+ const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
795
+ getRunPiMessagesViaServer(options.context, options.runId),
796
+ getRunPiStatusViaServer(options.context, options.runId),
797
+ getRunPiCommandsViaServer(options.context, options.runId)
444
798
  ]);
445
- return {
446
- Container: tui.Container,
447
- TUI: tui.TUI,
448
- Input: input.Input,
449
- ProcessTerminal: terminal.ProcessTerminal,
450
- matchesKey: keys.matchesKey,
451
- truncateToWidth: utils.truncateToWidth
799
+ const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
800
+ const native = nativePiUi(ctx);
801
+ if (state.nativeStream && native?.appendSessionMessages)
802
+ native.appendSessionMessages(messages);
803
+ else
804
+ for (const message of messages)
805
+ applyMessage(state, message);
806
+ applyStatus(state, statusPayload);
807
+ const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
808
+ state.commands = commands.flatMap((command) => {
809
+ const record = recordOf(command);
810
+ return typeof record?.name === "string" ? [`/${record.name}`] : [];
811
+ });
812
+ catchupDone = true;
813
+ for (const payload of buffered.splice(0))
814
+ applyEnvelope(ctx, state, payload);
815
+ updatePiUi(ctx, state);
816
+ } catch (error) {
817
+ appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
818
+ catchupDone = true;
819
+ updatePiUi(ctx, state);
820
+ }
821
+ await closePromise;
822
+ }
823
+ function createRemoteBashOperations(options, state, excludeFromContext) {
824
+ return {
825
+ exec(command, _cwd, execOptions) {
826
+ return new Promise((resolve3, reject) => {
827
+ const pending = {
828
+ command,
829
+ onData: execOptions.onData,
830
+ resolve: resolve3,
831
+ reject,
832
+ sawChunk: false
833
+ };
834
+ const cleanup = () => {
835
+ execOptions.signal?.removeEventListener("abort", onAbort);
836
+ if (timer)
837
+ clearTimeout(timer);
838
+ };
839
+ const onAbort = () => {
840
+ cleanup();
841
+ failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
842
+ };
843
+ const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
844
+ const timer = timeoutMs > 0 ? setTimeout(() => {
845
+ cleanup();
846
+ failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
847
+ }, timeoutMs) : null;
848
+ const wrappedResolve = pending.resolve;
849
+ const wrappedReject = pending.reject;
850
+ pending.resolve = (result) => {
851
+ cleanup();
852
+ wrappedResolve(result);
853
+ };
854
+ pending.reject = (error) => {
855
+ cleanup();
856
+ wrappedReject(error);
857
+ };
858
+ execOptions.signal?.addEventListener("abort", onAbort, { once: true });
859
+ state.pendingShells.push(pending);
860
+ sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
861
+ cleanup();
862
+ failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
863
+ });
864
+ });
865
+ }
866
+ };
867
+ }
868
+ async function answerPendingUi(options, state, line) {
869
+ const pending = state.pendingUi;
870
+ if (!pending)
871
+ return false;
872
+ if (line === "/cancel") {
873
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
874
+ } else if (pending.method === "confirm") {
875
+ const confirmed = /^(y|yes|true|1)$/i.test(line);
876
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
877
+ } else if (pending.options.length > 0 && /^\d+$/.test(line)) {
878
+ const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
879
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
880
+ } else {
881
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
882
+ }
883
+ appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
884
+ state.pendingUi = null;
885
+ return true;
886
+ }
887
+ async function routeInput(options, ctx, state, line) {
888
+ const text = line.trim();
889
+ if (!text)
890
+ return;
891
+ if (await answerPendingUi(options, state, text)) {
892
+ updatePiUi(ctx, state);
893
+ return;
894
+ }
895
+ if (text === "/detach" || text === "/quit" || text === "/q") {
896
+ appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
897
+ updatePiUi(ctx, state);
898
+ ctx.shutdown();
899
+ return;
900
+ }
901
+ if (text === "/stop") {
902
+ await abortRunPiViaServer(options.context, options.runId);
903
+ appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
904
+ updatePiUi(ctx, state);
905
+ ctx.shutdown();
906
+ return;
907
+ }
908
+ if (text.startsWith("!")) {
909
+ appendTranscript(state, "You", text);
910
+ await sendRunPiShellViaServer(options.context, options.runId, text);
911
+ } else if (text.startsWith("/")) {
912
+ appendTranscript(state, "You", text);
913
+ const result = await runRunPiCommandViaServer(options.context, options.runId, text);
914
+ const message = typeof result.message === "string" ? result.message : "worker command accepted";
915
+ appendTranscript(state, "System", message);
916
+ } else {
917
+ appendTranscript(state, "You", text);
918
+ await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
919
+ }
920
+ updatePiUi(ctx, state);
921
+ }
922
+ function createRigWorkerPiBridgeExtension(options) {
923
+ return (pi) => {
924
+ const state = {
925
+ transcript: [],
926
+ status: "starting worker Pi daemon bridge",
927
+ activity: "",
928
+ cwd: "",
929
+ model: "",
930
+ commands: [],
931
+ streaming: false,
932
+ pendingUi: null,
933
+ pendingShells: [],
934
+ wsConnected: false,
935
+ nativeStream: false
452
936
  };
937
+ if (options.initialMessageSent)
938
+ appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
939
+ let nativePiUiContextAvailable = false;
940
+ pi.on("user_bash", (event) => {
941
+ state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
942
+ return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
943
+ });
944
+ pi.on("session_start", async (_event, ctx) => {
945
+ nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
946
+ state.nativeStream = nativePiUiContextAvailable;
947
+ updatePiUi(ctx, state);
948
+ ctx.ui.notify(nativePiUiContextAvailable ? "Rig worker Pi native stream bridge loaded" : "Rig worker Pi bridge extension loaded (degraded widget fallback)", "info");
949
+ ctx.ui.onTerminalInput((data) => {
950
+ if (data.includes("\x04")) {
951
+ ctx.shutdown();
952
+ return { consume: true };
953
+ }
954
+ if (!data.includes("\r") && !data.includes(`
955
+ `))
956
+ return;
957
+ const inlineText = data.replace(/[\r\n]+/g, "").trim();
958
+ const editorText = ctx.ui.getEditorText().trim();
959
+ const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
960
+ if (!text)
961
+ return;
962
+ if (text.startsWith("!"))
963
+ return;
964
+ ctx.ui.setEditorText("");
965
+ routeInput(options, ctx, state, text).catch((error) => {
966
+ appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
967
+ updatePiUi(ctx, state);
968
+ });
969
+ return { consume: true };
970
+ });
971
+ connectWorkerStream(options, ctx, state).catch((error) => {
972
+ appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
973
+ updatePiUi(ctx, state);
974
+ });
975
+ });
976
+ pi.on("session_shutdown", () => {});
977
+ };
978
+ }
979
+
980
+ // packages/cli/src/commands/_pi-frontend.ts
981
+ function setTemporaryEnv(updates) {
982
+ const previous = new Map;
983
+ for (const [key, value] of Object.entries(updates)) {
984
+ previous.set(key, process.env[key]);
985
+ process.env[key] = value;
986
+ }
987
+ return () => {
988
+ for (const [key, value] of previous) {
989
+ if (value === undefined)
990
+ delete process.env[key];
991
+ else
992
+ process.env[key] = value;
993
+ }
994
+ };
995
+ }
996
+ async function attachRunBundledPiFrontend(context, input) {
997
+ const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
998
+ const cwd = join(tempRoot, "workspace");
999
+ const agentDir = join(tempRoot, "agent");
1000
+ const sessionDir = join(tempRoot, "sessions");
1001
+ const previousCwd = process.cwd();
1002
+ const restoreEnv = setTemporaryEnv({
1003
+ PI_CODING_AGENT_DIR: agentDir,
1004
+ PI_CODING_AGENT_SESSION_DIR: sessionDir,
1005
+ PI_OFFLINE: "1",
1006
+ PI_SKIP_VERSION_CHECK: "1"
1007
+ });
1008
+ let detached = false;
1009
+ try {
1010
+ await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
1011
+ process.chdir(cwd);
1012
+ await runPiMain([
1013
+ "--offline",
1014
+ "--no-session",
1015
+ "--no-tools",
1016
+ "--no-builtin-tools",
1017
+ "--no-skills",
1018
+ "--no-prompt-templates",
1019
+ "--no-themes",
1020
+ "--no-context-files",
1021
+ "--no-approve"
1022
+ ], {
1023
+ extensionFactories: [
1024
+ createRigWorkerPiBridgeExtension({
1025
+ context,
1026
+ runId: input.runId,
1027
+ initialMessageSent: input.steered === true
1028
+ })
1029
+ ]
1030
+ });
1031
+ detached = true;
1032
+ } finally {
1033
+ process.chdir(previousCwd);
1034
+ restoreEnv();
1035
+ rmSync(tempRoot, { recursive: true, force: true });
453
1036
  }
1037
+ let run = { runId: input.runId, status: "unknown" };
1038
+ try {
1039
+ run = await getRunDetailsViaServer(context, input.runId);
1040
+ } catch {}
1041
+ return {
1042
+ run,
1043
+ logs: [],
1044
+ timeline: [],
1045
+ timelineCursor: null,
1046
+ steered: input.steered === true,
1047
+ detached,
1048
+ rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
1049
+ };
454
1050
  }
1051
+
1052
+ // packages/cli/src/commands/_operator-view.ts
1053
+ var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
455
1054
  function runStatusFromPayload(payload) {
456
1055
  const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
457
1056
  return String(run.status ?? "unknown").toLowerCase();
@@ -490,198 +1089,15 @@ async function readOperatorSnapshot(context, runId, options = {}) {
490
1089
  const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
491
1090
  return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
492
1091
  }
493
- function unwrapRun(runPayload) {
494
- return runPayload.run && typeof runPayload.run === "object" && !Array.isArray(runPayload.run) ? runPayload.run : runPayload;
495
- }
496
- function logDetail2(log) {
497
- return typeof log.detail === "string" ? log.detail.trim() : "";
498
- }
499
- function logTitle(log) {
500
- return typeof log.title === "string" ? log.title.trim() : "";
501
- }
502
- function renderAssistantTextFromTimeline(entries) {
503
- const assistant = entries.filter((entry) => entry.type === "assistant_message" && typeof entry.text === "string").at(-1);
504
- const text = typeof assistant?.text === "string" ? assistant.text.trimEnd() : "";
505
- if (!text)
506
- return [];
507
- return [`${BLUE}${BOLD}Remote Pi assistant${RESET}`, ...text.split(/\r?\n/).slice(-18)];
508
- }
509
- function renderToolLines(entries) {
510
- return entries.filter((entry) => entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call").slice(-8).map((entry) => `${DIM}[tool]${RESET} ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
511
- }
512
- function renderStageLines(logs) {
513
- const latestByStage = new Map;
514
- for (const log of logs) {
515
- const title = logTitle(log).toLowerCase();
516
- const stageName = String(log.stage ?? "").toLowerCase();
517
- const stage = CANONICAL_STAGES2.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
518
- if (stage)
519
- latestByStage.set(stage, log);
520
- }
521
- return CANONICAL_STAGES2.map((stage) => {
522
- const log = latestByStage.get(stage);
523
- const status = String(log?.status ?? "pending");
524
- const detail = log ? logDetail2(log) : "";
525
- const color = status === "completed" ? GREEN : status === "failed" || status === "rejected" ? RED : status === "pending" ? DIM : YELLOW;
526
- const mark = status === "completed" ? "\u2713" : status === "pending" ? "\xB7" : status === "failed" ? "\u2717" : "\u25B6";
527
- return `${color}${mark} ${stage}${RESET}${detail ? ` ${DIM}\u2014 ${detail.slice(0, 140)}${RESET}` : ""}`;
528
- });
529
- }
530
- function renderEventLines(logs) {
531
- return logs.filter((log) => !CANONICAL_STAGES2.some((stage) => stage.toLowerCase() === logTitle(log).toLowerCase())).slice(-12).flatMap((log) => {
532
- const title = logTitle(log) || "Rig event";
533
- const detail = logDetail2(log);
534
- if (!detail)
535
- return [];
536
- const tone = String(log.tone ?? "");
537
- const color = tone === "error" ? RED : tone === "tool" ? MAGENTA : DIM;
538
- return [`${color}[${title}]${RESET} ${detail.slice(0, 220)}`];
539
- });
540
- }
541
-
542
- class RigRunComponent {
543
- truncateToWidth;
544
- snapshot = { run: {}, logs: [], timeline: [] };
545
- localEvents = [];
546
- constructor(truncateToWidth) {
547
- this.truncateToWidth = truncateToWidth;
548
- }
549
- update(snapshot) {
550
- this.snapshot = snapshot;
551
- }
552
- addLocalEvent(message) {
553
- this.localEvents.push(`${new Date().toLocaleTimeString()} ${message}`);
554
- this.localEvents = this.localEvents.slice(-8);
555
- }
556
- invalidate() {}
557
- render(width) {
558
- const run = unwrapRun(this.snapshot.run);
559
- const runId = String(run.runId ?? run.id ?? "run");
560
- const status = String(run.status ?? "unknown");
561
- const worker = typeof run.worktreePath === "string" && run.worktreePath.trim() ? run.worktreePath.trim() : typeof run.projectRoot === "string" && run.projectRoot.trim() ? run.projectRoot.trim() : "worker workspace pending";
562
- const lines = [
563
- `${BOLD}Rig Pi frontend${RESET} ${DIM}(local Pi TUI \u2192 Rig server \u2192 worker Pi backend)${RESET}`,
564
- `${BOLD}${runId}${RESET} \xB7 ${status} \xB7 ${DIM}${worker}${RESET}`,
565
- "",
566
- `${BOLD}Rig flow${RESET}`,
567
- ...renderStageLines(this.snapshot.logs ?? []),
568
- "",
569
- ...renderAssistantTextFromTimeline(this.snapshot.timeline ?? []),
570
- ...renderToolLines(this.snapshot.timeline ?? []),
571
- "",
572
- `${BOLD}Rig / Pi events${RESET}`,
573
- ...renderEventLines(this.snapshot.logs ?? []),
574
- ...this.localEvents.map((event) => `${GREEN}[frontend]${RESET} ${event}`),
575
- ""
576
- ];
577
- return lines.slice(-42).map((line) => this.truncateToWidth(line, Math.max(10, width)));
578
- }
579
- }
580
-
581
- class RigInputComponent {
582
- matchesKey;
583
- truncateToWidth;
584
- input;
585
- status = "Type text, /skill:..., or remote Pi slash commands. Local: /stop /detach.";
586
- constructor(InputCtor, matchesKey, truncateToWidth, onSubmit, onEscape) {
587
- this.matchesKey = matchesKey;
588
- this.truncateToWidth = truncateToWidth;
589
- this.input = new InputCtor;
590
- this.input.onSubmit = (value) => {
591
- const text = value.trim();
592
- this.input.setValue("");
593
- if (text)
594
- Promise.resolve(onSubmit(text));
595
- };
596
- this.input.onEscape = onEscape;
597
- }
598
- handleInput(data) {
599
- if (this.matchesKey(data, "ctrl+d")) {
600
- this.input.onEscape?.();
601
- return;
602
- }
603
- this.input.handleInput?.(data);
604
- }
605
- setStatus(status) {
606
- this.status = status;
607
- }
608
- invalidate() {
609
- this.input.invalidate();
610
- }
611
- render(width) {
612
- return [
613
- `${DIM}${this.truncateToWidth(this.status, Math.max(10, width))}${RESET}`,
614
- `${GREEN}${BOLD}You \u2192 worker Pi:${RESET}`,
615
- ...this.input.render(width)
616
- ];
617
- }
618
- }
619
- async function attachRunPiTuiFrontend(context, input) {
620
- const piTui = await loadPiTuiRuntime();
621
- const terminal = new piTui.ProcessTerminal;
622
- const tui = new piTui.TUI(terminal);
623
- const root = new piTui.Container;
624
- const runView = new RigRunComponent(piTui.truncateToWidth);
625
- let detached = false;
626
- let steered = input.steered === true;
627
- let latest = await readOperatorSnapshot(context, input.runId);
628
- let timelineCursor = latest.timelineCursor;
629
- runView.update(latest);
630
- if (steered)
631
- runView.addLocalEvent("initial message queued to worker Pi.");
632
- const stop = () => {
633
- detached = true;
634
- tui.stop();
635
- };
636
- const inputView = new RigInputComponent(piTui.Input, piTui.matchesKey, piTui.truncateToWidth, async (line) => {
637
- if (line === "/detach" || line === "/quit" || line === "/q") {
638
- runView.addLocalEvent("detached from run.");
639
- stop();
640
- return;
641
- }
642
- if (line === "/stop") {
643
- await stopRunViaServer(context, input.runId);
644
- runView.addLocalEvent("stop requested.");
645
- stop();
646
- return;
647
- }
648
- await steerRunViaServer(context, input.runId, line);
649
- steered = true;
650
- runView.addLocalEvent(`queued to worker Pi: ${line.slice(0, 160)}`);
651
- tui.requestRender();
652
- }, stop);
653
- root.addChild(runView);
654
- root.addChild(inputView);
655
- tui.addChild(root);
656
- tui.setFocus(inputView.input);
657
- tui.start();
658
- tui.requestRender(true);
659
- const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 1000));
660
- try {
661
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(latest.run))) {
662
- await Bun.sleep(pollMs);
663
- latest = await readOperatorSnapshot(context, input.runId, { timelineCursor });
664
- timelineCursor = latest.timelineCursor;
665
- runView.update(latest);
666
- inputView.setStatus(`Remote worker ${runStatusFromPayload(latest.run)}. Input is forwarded to worker Pi; /stop /detach are local controls.`);
667
- tui.requestRender();
668
- }
669
- } finally {
670
- if (!detached)
671
- tui.stop();
672
- }
673
- return { ...latest, timelineCursor, steered, detached, rendered: renderOperatorSnapshot(latest) };
674
- }
675
1092
  async function attachRunOperatorView(context, input) {
676
1093
  let steered = false;
677
1094
  if (input.message?.trim()) {
678
- await steerRunViaServer(context, input.runId, input.message.trim());
1095
+ await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
679
1096
  steered = true;
680
1097
  }
681
1098
  if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
682
- return attachRunPiTuiFrontend(context, {
1099
+ return attachRunBundledPiFrontend(context, {
683
1100
  runId: input.runId,
684
- pollMs: input.pollMs,
685
1101
  steered
686
1102
  });
687
1103
  }
@@ -692,7 +1108,7 @@ async function attachRunOperatorView(context, input) {
692
1108
  surface.renderTimeline(snapshot.timeline);
693
1109
  surface.renderLogs(snapshot.logs);
694
1110
  if (steered)
695
- surface.info("Steering message queued.");
1111
+ surface.info("Message submitted to worker Pi.");
696
1112
  }
697
1113
  let detached = false;
698
1114
  let commandInput = null;
@@ -711,7 +1127,7 @@ async function attachRunOperatorView(context, input) {
711
1127
  }
712
1128
  const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
713
1129
  let timelineCursor = snapshot.timelineCursor;
714
- while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
1130
+ while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
715
1131
  await Bun.sleep(pollMs);
716
1132
  snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
717
1133
  timelineCursor = snapshot.timelineCursor;