@h-rig/cli 0.0.6-alpha.40 → 0.0.6-alpha.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/rig.js +512 -551
- package/dist/src/commands/_operator-view.js +510 -530
- package/dist/src/commands/_pi-frontend.js +514 -534
- package/dist/src/commands/_pi-remote-session.js +671 -0
- package/dist/src/commands/_pi-worker-bridge-extension.js +352 -502
- package/dist/src/commands/_run-driver-helpers.js +2 -21
- package/dist/src/commands/run.js +510 -530
- package/dist/src/commands/task-run-driver.js +2 -21
- package/dist/src/commands/task.js +510 -530
- package/dist/src/commands.js +512 -551
- package/dist/src/index.js +512 -551
- package/package.json +6 -6
|
@@ -482,435 +482,400 @@ function createOperatorSurface(options = {}) {
|
|
|
482
482
|
import { mkdtempSync, rmSync } from "fs";
|
|
483
483
|
import { tmpdir } from "os";
|
|
484
484
|
import { join } from "path";
|
|
485
|
-
import {
|
|
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-
|
|
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
|
-
|
|
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
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
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
|
|
507
|
-
|
|
508
|
-
|
|
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
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
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
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
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
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
return;
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
795
|
-
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
796
|
-
updatePiUi(ctx, state);
|
|
797
|
-
return true;
|
|
663
|
+
return false;
|
|
798
664
|
}
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
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
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
}
|
|
871
|
-
}
|
|
872
|
-
|
|
873
|
-
const
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
const
|
|
880
|
-
|
|
881
|
-
|
|
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
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
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
|
+
const trimmed = text.trim();
|
|
793
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
794
|
+
return;
|
|
795
|
+
await this.remote.sendPrompt(trimmed, "steer");
|
|
796
|
+
}
|
|
797
|
+
async followUp(text) {
|
|
798
|
+
const trimmed = text.trim();
|
|
799
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
800
|
+
return;
|
|
801
|
+
await this.remote.sendPrompt(trimmed, "followUp");
|
|
802
|
+
}
|
|
803
|
+
async abort() {
|
|
804
|
+
await this.remote.abort();
|
|
805
|
+
}
|
|
806
|
+
async compact(customInstructions) {
|
|
807
|
+
const pending = new Promise((resolve3, reject) => {
|
|
808
|
+
this.remote.registerPendingCompaction({ resolve: resolve3, reject });
|
|
890
809
|
});
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
810
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
811
|
+
return pending;
|
|
812
|
+
}
|
|
813
|
+
clearQueue() {
|
|
814
|
+
const cleared = {
|
|
815
|
+
steering: [...this.remote.status.steeringMessages],
|
|
816
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
817
|
+
};
|
|
818
|
+
this.remote.status.steeringMessages = [];
|
|
819
|
+
this.remote.status.followUpMessages = [];
|
|
820
|
+
this.remote.status.pendingMessageCount = 0;
|
|
821
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
822
|
+
return cleared;
|
|
823
|
+
}
|
|
824
|
+
get isStreaming() {
|
|
825
|
+
return this.remote.status.isStreaming;
|
|
826
|
+
}
|
|
827
|
+
get isCompacting() {
|
|
828
|
+
return this.remote.status.isCompacting;
|
|
829
|
+
}
|
|
830
|
+
get isBashRunning() {
|
|
831
|
+
return this.remote.status.isBashRunning;
|
|
832
|
+
}
|
|
833
|
+
get pendingMessageCount() {
|
|
834
|
+
return this.remote.status.pendingMessageCount;
|
|
835
|
+
}
|
|
836
|
+
getSteeringMessages() {
|
|
837
|
+
return this.remote.status.steeringMessages;
|
|
838
|
+
}
|
|
839
|
+
getFollowUpMessages() {
|
|
840
|
+
return this.remote.status.followUpMessages;
|
|
841
|
+
}
|
|
842
|
+
get model() {
|
|
843
|
+
return this.remote.status.model ?? super.model;
|
|
844
|
+
}
|
|
845
|
+
async setModel(model) {
|
|
846
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
847
|
+
this.remote.status.model = model;
|
|
848
|
+
}
|
|
849
|
+
get thinkingLevel() {
|
|
850
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
851
|
+
}
|
|
852
|
+
setThinkingLevel(level) {
|
|
853
|
+
this.remote.status.thinkingLevel = level;
|
|
854
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
855
|
+
}
|
|
856
|
+
get sessionName() {
|
|
857
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
858
|
+
}
|
|
859
|
+
setSessionName(name) {
|
|
860
|
+
this.remote.status.sessionName = name;
|
|
861
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
862
|
+
}
|
|
863
|
+
getSessionStats() {
|
|
864
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
865
|
+
}
|
|
866
|
+
getContextUsage() {
|
|
867
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
868
|
+
}
|
|
869
|
+
dispose() {
|
|
870
|
+
this.remote.close();
|
|
871
|
+
super.dispose();
|
|
900
872
|
}
|
|
901
|
-
await closePromise;
|
|
902
873
|
}
|
|
903
|
-
function createRemoteBashOperations(
|
|
874
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
904
875
|
return {
|
|
905
876
|
exec(command, _cwd, execOptions) {
|
|
906
877
|
return new Promise((resolve3, reject) => {
|
|
907
|
-
const pending = {
|
|
908
|
-
command,
|
|
909
|
-
onData: execOptions.onData,
|
|
910
|
-
resolve: resolve3,
|
|
911
|
-
reject,
|
|
912
|
-
sawChunk: false
|
|
913
|
-
};
|
|
878
|
+
const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
|
|
914
879
|
const cleanup = () => {
|
|
915
880
|
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
916
881
|
if (timer)
|
|
@@ -918,12 +883,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
918
883
|
};
|
|
919
884
|
const onAbort = () => {
|
|
920
885
|
cleanup();
|
|
921
|
-
failPendingShell(
|
|
886
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
922
887
|
};
|
|
923
888
|
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
924
889
|
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
925
890
|
cleanup();
|
|
926
|
-
failPendingShell(
|
|
891
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
927
892
|
}, timeoutMs) : null;
|
|
928
893
|
const wrappedResolve = pending.resolve;
|
|
929
894
|
const wrappedReject = pending.reject;
|
|
@@ -936,125 +901,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
936
901
|
wrappedReject(error);
|
|
937
902
|
};
|
|
938
903
|
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
939
|
-
|
|
940
|
-
|
|
904
|
+
controller.registerPendingShell(pending);
|
|
905
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
941
906
|
cleanup();
|
|
942
|
-
failPendingShell(
|
|
907
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
943
908
|
});
|
|
944
909
|
});
|
|
945
910
|
}
|
|
946
911
|
};
|
|
947
912
|
}
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
913
|
+
|
|
914
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
915
|
+
function recordOf2(value) {
|
|
916
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
917
|
+
}
|
|
918
|
+
function asText(value) {
|
|
919
|
+
if (typeof value === "string")
|
|
920
|
+
return value;
|
|
921
|
+
if (value === null || value === undefined)
|
|
922
|
+
return "";
|
|
923
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
924
|
+
return String(value);
|
|
925
|
+
try {
|
|
926
|
+
return JSON.stringify(value);
|
|
927
|
+
} catch {
|
|
928
|
+
return String(value);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
932
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
933
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
934
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
935
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
936
|
+
const choices = rawOptions.map((option) => {
|
|
937
|
+
const record = recordOf2(option);
|
|
938
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
939
|
+
}).filter(Boolean);
|
|
940
|
+
try {
|
|
941
|
+
if (method === "confirm") {
|
|
942
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
943
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
if (choices.length > 0) {
|
|
947
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
948
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
952
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
953
|
+
} catch (error) {
|
|
954
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
955
|
+
}
|
|
966
956
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
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);
|
|
957
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
958
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
959
|
+
for (const command of commands) {
|
|
960
|
+
const record = recordOf2(command);
|
|
961
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
962
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
963
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
964
|
+
continue;
|
|
965
|
+
registered.add(name);
|
|
966
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
967
|
+
try {
|
|
968
|
+
pi.registerCommand(name, {
|
|
969
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
970
|
+
handler: async (args) => {
|
|
971
|
+
try {
|
|
972
|
+
const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
973
|
+
ctx.ui.notify(message, "info");
|
|
974
|
+
} catch (error) {
|
|
975
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
});
|
|
979
|
+
} catch {}
|
|
980
|
+
}
|
|
1001
981
|
}
|
|
1002
982
|
function createRigWorkerPiBridgeExtension(options) {
|
|
1003
983
|
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
984
|
const registeredDaemonCommands = new Set;
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
985
|
+
pi.registerCommand("detach", {
|
|
986
|
+
description: "Detach from this run; the worker keeps going",
|
|
987
|
+
handler: async (_args, ctx) => {
|
|
988
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
989
|
+
ctx.shutdown();
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
pi.registerCommand("stop", {
|
|
993
|
+
description: "Stop the worker Pi run and detach",
|
|
994
|
+
handler: async (_args, ctx) => {
|
|
995
|
+
await options.controller.abort();
|
|
996
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
997
|
+
ctx.shutdown();
|
|
998
|
+
}
|
|
1024
999
|
});
|
|
1000
|
+
pi.on("user_bash", (event) => ({
|
|
1001
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
1002
|
+
}));
|
|
1025
1003
|
pi.on("session_start", async (_event, ctx) => {
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1004
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
1005
|
+
ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
|
|
1006
|
+
ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
|
|
1007
|
+
if (options.initialMessageSent)
|
|
1008
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
1009
|
+
const nativeUi = ctx.ui;
|
|
1010
|
+
options.controller.setUiHooks({
|
|
1011
|
+
onStatusText: (text) => ctx.ui.setStatus("rig-worker-pi", text),
|
|
1012
|
+
onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
|
|
1013
|
+
onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
|
|
1014
|
+
onError: (message) => ctx.ui.notify(message, "error"),
|
|
1015
|
+
onExtensionUiRequest: (request) => {
|
|
1016
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
1017
|
+
},
|
|
1018
|
+
onCatchUp: (messages, commands) => {
|
|
1019
|
+
if (nativeUi.appendSessionMessages)
|
|
1020
|
+
nativeUi.appendSessionMessages(messages);
|
|
1021
|
+
const cwd = options.controller.status.cwd;
|
|
1022
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
1023
|
+
nativeUi.setDisplayCwd(cwd);
|
|
1024
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
1034
1025
|
}
|
|
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
1026
|
});
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
updatePiUi(ctx, state);
|
|
1027
|
+
options.controller.connect().catch((error) => {
|
|
1028
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1055
1029
|
});
|
|
1056
1030
|
});
|
|
1057
|
-
pi.on("session_shutdown", () => {
|
|
1031
|
+
pi.on("session_shutdown", () => {
|
|
1032
|
+
options.controller.close();
|
|
1033
|
+
});
|
|
1058
1034
|
};
|
|
1059
1035
|
}
|
|
1060
1036
|
|
|
@@ -1075,43 +1051,47 @@ function setTemporaryEnv(updates) {
|
|
|
1075
1051
|
};
|
|
1076
1052
|
}
|
|
1077
1053
|
async function attachRunBundledPiFrontend(context, input) {
|
|
1078
|
-
const
|
|
1079
|
-
const cwd = join(tempRoot, "workspace");
|
|
1080
|
-
const agentDir = join(tempRoot, "agent");
|
|
1081
|
-
const sessionDir = join(tempRoot, "sessions");
|
|
1082
|
-
const previousCwd = process.cwd();
|
|
1054
|
+
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
1083
1055
|
const restoreEnv = setTemporaryEnv({
|
|
1084
|
-
|
|
1085
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
1086
|
-
PI_OFFLINE: "1",
|
|
1056
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
1087
1057
|
PI_SKIP_VERSION_CHECK: "1"
|
|
1088
1058
|
});
|
|
1059
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
1060
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
1061
|
+
const services = await createAgentSessionServices({
|
|
1062
|
+
cwd,
|
|
1063
|
+
agentDir,
|
|
1064
|
+
resourceLoaderOptions: {
|
|
1065
|
+
extensionFactories: [
|
|
1066
|
+
createRigWorkerPiBridgeExtension({
|
|
1067
|
+
context,
|
|
1068
|
+
controller,
|
|
1069
|
+
runId: input.runId,
|
|
1070
|
+
initialMessageSent: input.steered === true
|
|
1071
|
+
})
|
|
1072
|
+
],
|
|
1073
|
+
noContextFiles: true
|
|
1074
|
+
}
|
|
1075
|
+
});
|
|
1076
|
+
const created = await createAgentSessionFromServices({
|
|
1077
|
+
services,
|
|
1078
|
+
sessionManager,
|
|
1079
|
+
sessionStartEvent,
|
|
1080
|
+
noTools: "all",
|
|
1081
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
1082
|
+
});
|
|
1083
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
1084
|
+
};
|
|
1089
1085
|
let detached = false;
|
|
1090
1086
|
try {
|
|
1091
|
-
await
|
|
1092
|
-
|
|
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
|
-
]
|
|
1087
|
+
await runPiMain([], {
|
|
1088
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
1109
1089
|
});
|
|
1110
1090
|
detached = true;
|
|
1111
1091
|
} finally {
|
|
1112
|
-
process.chdir(previousCwd);
|
|
1113
1092
|
restoreEnv();
|
|
1114
|
-
|
|
1093
|
+
controller.close();
|
|
1094
|
+
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
1115
1095
|
}
|
|
1116
1096
|
let run = { runId: input.runId, status: "unknown" };
|
|
1117
1097
|
try {
|
|
@@ -1124,7 +1104,7 @@ async function attachRunBundledPiFrontend(context, input) {
|
|
|
1124
1104
|
timelineCursor: null,
|
|
1125
1105
|
steered: input.steered === true,
|
|
1126
1106
|
detached,
|
|
1127
|
-
rendered: "
|
|
1107
|
+
rendered: "native bundled Pi frontend with remote worker session runtime"
|
|
1128
1108
|
};
|
|
1129
1109
|
}
|
|
1130
1110
|
|