@h-rig/cli 0.0.6-alpha.21 → 0.0.6-alpha.23
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 +940 -387
- package/dist/src/commands/_operator-view.js +539 -4
- package/dist/src/commands/_pi-frontend.js +727 -0
- package/dist/src/commands/_pi-worker-bridge-extension.js +645 -0
- package/dist/src/commands/_preflight.js +1 -81
- package/dist/src/commands/_server-client.js +80 -1
- package/dist/src/commands/run.js +541 -115
- package/dist/src/commands/task-run-driver.js +141 -10
- package/dist/src/commands/task.js +544 -197
- package/dist/src/commands.js +940 -387
- package/dist/src/index.js +940 -387
- package/package.json +6 -5
- package/dist/src/commands/_pi-session.js +0 -253
|
@@ -227,6 +227,66 @@ async function steerRunViaServer(context, runId, message) {
|
|
|
227
227
|
});
|
|
228
228
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
229
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
|
+
}
|
|
230
290
|
|
|
231
291
|
// packages/cli/src/commands/_operator-surface.ts
|
|
232
292
|
import { createInterface } from "readline";
|
|
@@ -404,8 +464,477 @@ function createOperatorSurface(options = {}) {
|
|
|
404
464
|
};
|
|
405
465
|
}
|
|
406
466
|
|
|
407
|
-
// packages/cli/src/commands/
|
|
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
|
|
408
474
|
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
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);
|
|
486
|
+
try {
|
|
487
|
+
return JSON.stringify(value);
|
|
488
|
+
} catch {
|
|
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 parseExtensionUiRequest(value) {
|
|
526
|
+
const request = recordOf(value) ?? {};
|
|
527
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
528
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
529
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
530
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
531
|
+
const options = rawOptions.map((option) => {
|
|
532
|
+
const record = recordOf(option);
|
|
533
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
534
|
+
}).filter(Boolean);
|
|
535
|
+
return { requestId, method, prompt, options };
|
|
536
|
+
}
|
|
537
|
+
function renderBridgeWidget(state) {
|
|
538
|
+
const statusParts = [
|
|
539
|
+
state.wsConnected ? "live WS" : "WS pending",
|
|
540
|
+
state.status,
|
|
541
|
+
state.model,
|
|
542
|
+
state.cwd
|
|
543
|
+
].filter(Boolean);
|
|
544
|
+
const lines = [`Worker Pi daemon bridge \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
545
|
+
if (state.activity)
|
|
546
|
+
lines.push(state.activity);
|
|
547
|
+
if (state.commands.length > 0) {
|
|
548
|
+
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
549
|
+
}
|
|
550
|
+
lines.push("");
|
|
551
|
+
if (state.transcript.length > 0) {
|
|
552
|
+
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
553
|
+
} else {
|
|
554
|
+
lines.push("Waiting for worker Pi daemon transcript\u2026");
|
|
555
|
+
}
|
|
556
|
+
if (state.pendingUi) {
|
|
557
|
+
lines.push("");
|
|
558
|
+
lines.push(`Extension UI request \xB7 ${state.pendingUi.method}`);
|
|
559
|
+
lines.push(state.pendingUi.prompt);
|
|
560
|
+
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
561
|
+
lines.push("Reply in the Pi editor. /cancel cancels this request.");
|
|
562
|
+
}
|
|
563
|
+
return lines;
|
|
564
|
+
}
|
|
565
|
+
function updatePiUi(ctx, state) {
|
|
566
|
+
ctx.ui.setTitle("Pi \xB7 Rig worker daemon");
|
|
567
|
+
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker Pi WS live" : state.status);
|
|
568
|
+
ctx.ui.setWorkingVisible(false);
|
|
569
|
+
ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
|
|
570
|
+
}
|
|
571
|
+
function applyStatus(state, payload) {
|
|
572
|
+
const status = recordOf(payload.status) ?? payload;
|
|
573
|
+
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
574
|
+
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
575
|
+
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
576
|
+
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
577
|
+
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
578
|
+
}
|
|
579
|
+
function applyMessage(state, message) {
|
|
580
|
+
const record = recordOf(message);
|
|
581
|
+
if (!record)
|
|
582
|
+
return;
|
|
583
|
+
const role = String(record.role ?? "system");
|
|
584
|
+
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
585
|
+
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
586
|
+
}
|
|
587
|
+
function applyPiEvent(state, eventValue) {
|
|
588
|
+
const event = recordOf(eventValue);
|
|
589
|
+
if (!event)
|
|
590
|
+
return;
|
|
591
|
+
const type = String(event.type ?? "event");
|
|
592
|
+
if (type === "agent_start") {
|
|
593
|
+
state.streaming = true;
|
|
594
|
+
state.status = "streaming";
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
if (type === "agent_end") {
|
|
598
|
+
state.streaming = false;
|
|
599
|
+
state.status = "idle";
|
|
600
|
+
appendTranscript(state, "System", "Agent turn complete.");
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
604
|
+
applyMessage(state, event.message);
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
if (type === "message_update") {
|
|
608
|
+
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
609
|
+
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
610
|
+
if (delta)
|
|
611
|
+
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
if (type === "tool_execution_start") {
|
|
615
|
+
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (type === "tool_execution_update") {
|
|
619
|
+
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
if (type === "tool_execution_end") {
|
|
623
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (type === "queue_update") {
|
|
627
|
+
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
628
|
+
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
629
|
+
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
function applyUiEvent(state, value) {
|
|
633
|
+
const event = recordOf(value);
|
|
634
|
+
if (!event)
|
|
635
|
+
return;
|
|
636
|
+
const type = String(event.type ?? "ui");
|
|
637
|
+
if (type === "shell.start")
|
|
638
|
+
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
639
|
+
else if (type === "shell.chunk")
|
|
640
|
+
appendTranscript(state, "Tool", asText(event.chunk));
|
|
641
|
+
else if (type === "shell.end")
|
|
642
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.output ?? `exit ${String(event.exitCode ?? "")}`));
|
|
643
|
+
else
|
|
644
|
+
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
645
|
+
}
|
|
646
|
+
function applyEnvelope(state, envelopeValue) {
|
|
647
|
+
const envelope = recordOf(envelopeValue);
|
|
648
|
+
if (!envelope)
|
|
649
|
+
return;
|
|
650
|
+
const type = String(envelope.type ?? "");
|
|
651
|
+
if (type === "ready") {
|
|
652
|
+
const metadata = recordOf(envelope.metadata);
|
|
653
|
+
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
654
|
+
state.status = "worker Pi daemon ready";
|
|
655
|
+
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
656
|
+
} else if (type === "status.update") {
|
|
657
|
+
applyStatus(state, envelope);
|
|
658
|
+
} else if (type === "activity.update") {
|
|
659
|
+
const activity = recordOf(envelope.activity);
|
|
660
|
+
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
661
|
+
} else if (type === "extension_ui_request") {
|
|
662
|
+
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
663
|
+
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
664
|
+
} else if (type === "pi.ui_event") {
|
|
665
|
+
applyUiEvent(state, envelope.event);
|
|
666
|
+
} else if (type === "pi.event") {
|
|
667
|
+
applyPiEvent(state, envelope.event);
|
|
668
|
+
} else if (type === "error") {
|
|
669
|
+
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
async function waitForWorkerReady(options, ctx, state) {
|
|
673
|
+
while (true) {
|
|
674
|
+
const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => ({
|
|
675
|
+
ready: false,
|
|
676
|
+
status: error instanceof Error ? error.message : String(error),
|
|
677
|
+
retryAfterMs: 1000
|
|
678
|
+
}));
|
|
679
|
+
if (session.ready === false) {
|
|
680
|
+
const status = String(session.status ?? "starting");
|
|
681
|
+
state.status = `waiting for worker Pi daemon \xB7 ${status}`;
|
|
682
|
+
updatePiUi(ctx, state);
|
|
683
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
684
|
+
appendTranscript(state, "Error", `Run ended before worker Pi daemon became ready: ${status}`);
|
|
685
|
+
return false;
|
|
686
|
+
}
|
|
687
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
const sessionRecord = recordOf(session) ?? {};
|
|
691
|
+
applyEnvelope(state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
692
|
+
updatePiUi(ctx, state);
|
|
693
|
+
return true;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
function parseWsPayload(message) {
|
|
697
|
+
if (typeof message.data === "string")
|
|
698
|
+
return JSON.parse(message.data);
|
|
699
|
+
return JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
700
|
+
}
|
|
701
|
+
async function connectWorkerStream(options, ctx, state) {
|
|
702
|
+
const ready = await waitForWorkerReady(options, ctx, state);
|
|
703
|
+
if (!ready)
|
|
704
|
+
return;
|
|
705
|
+
let catchupDone = false;
|
|
706
|
+
const buffered = [];
|
|
707
|
+
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
708
|
+
const socket = new WebSocket(wsUrl);
|
|
709
|
+
const closePromise = new Promise((resolve3) => {
|
|
710
|
+
socket.onopen = () => {
|
|
711
|
+
state.wsConnected = true;
|
|
712
|
+
state.status = "live worker Pi WebSocket connected";
|
|
713
|
+
updatePiUi(ctx, state);
|
|
714
|
+
};
|
|
715
|
+
socket.onmessage = (message) => {
|
|
716
|
+
try {
|
|
717
|
+
const payload = parseWsPayload(message);
|
|
718
|
+
if (!catchupDone)
|
|
719
|
+
buffered.push(payload);
|
|
720
|
+
else {
|
|
721
|
+
applyEnvelope(state, payload);
|
|
722
|
+
updatePiUi(ctx, state);
|
|
723
|
+
}
|
|
724
|
+
} catch (error) {
|
|
725
|
+
appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
726
|
+
updatePiUi(ctx, state);
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
socket.onerror = () => socket.close();
|
|
730
|
+
socket.onclose = () => {
|
|
731
|
+
state.wsConnected = false;
|
|
732
|
+
state.status = "worker Pi WebSocket disconnected";
|
|
733
|
+
updatePiUi(ctx, state);
|
|
734
|
+
resolve3();
|
|
735
|
+
};
|
|
736
|
+
});
|
|
737
|
+
try {
|
|
738
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
739
|
+
getRunPiMessagesViaServer(options.context, options.runId),
|
|
740
|
+
getRunPiStatusViaServer(options.context, options.runId),
|
|
741
|
+
getRunPiCommandsViaServer(options.context, options.runId)
|
|
742
|
+
]);
|
|
743
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
744
|
+
for (const message of messages)
|
|
745
|
+
applyMessage(state, message);
|
|
746
|
+
applyStatus(state, statusPayload);
|
|
747
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
748
|
+
state.commands = commands.flatMap((command) => {
|
|
749
|
+
const record = recordOf(command);
|
|
750
|
+
return typeof record?.name === "string" ? [`/${record.name}`] : [];
|
|
751
|
+
});
|
|
752
|
+
catchupDone = true;
|
|
753
|
+
for (const payload of buffered.splice(0))
|
|
754
|
+
applyEnvelope(state, payload);
|
|
755
|
+
updatePiUi(ctx, state);
|
|
756
|
+
} catch (error) {
|
|
757
|
+
appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
758
|
+
catchupDone = true;
|
|
759
|
+
updatePiUi(ctx, state);
|
|
760
|
+
}
|
|
761
|
+
await closePromise;
|
|
762
|
+
}
|
|
763
|
+
async function answerPendingUi(options, state, line) {
|
|
764
|
+
const pending = state.pendingUi;
|
|
765
|
+
if (!pending)
|
|
766
|
+
return false;
|
|
767
|
+
if (line === "/cancel") {
|
|
768
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
769
|
+
} else if (pending.method === "confirm") {
|
|
770
|
+
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
771
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
772
|
+
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
773
|
+
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
774
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
775
|
+
} else {
|
|
776
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
777
|
+
}
|
|
778
|
+
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
779
|
+
state.pendingUi = null;
|
|
780
|
+
return true;
|
|
781
|
+
}
|
|
782
|
+
async function routeInput(options, ctx, state, line) {
|
|
783
|
+
const text = line.trim();
|
|
784
|
+
if (!text)
|
|
785
|
+
return;
|
|
786
|
+
if (await answerPendingUi(options, state, text)) {
|
|
787
|
+
updatePiUi(ctx, state);
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
if (text === "/detach" || text === "/quit" || text === "/q") {
|
|
791
|
+
appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
|
|
792
|
+
updatePiUi(ctx, state);
|
|
793
|
+
ctx.shutdown();
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
if (text === "/stop") {
|
|
797
|
+
await abortRunPiViaServer(options.context, options.runId);
|
|
798
|
+
appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
|
|
799
|
+
updatePiUi(ctx, state);
|
|
800
|
+
ctx.shutdown();
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (text.startsWith("!")) {
|
|
804
|
+
appendTranscript(state, "You", text);
|
|
805
|
+
await sendRunPiShellViaServer(options.context, options.runId, text);
|
|
806
|
+
} else if (text.startsWith("/")) {
|
|
807
|
+
appendTranscript(state, "You", text);
|
|
808
|
+
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
809
|
+
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
810
|
+
appendTranscript(state, "System", message);
|
|
811
|
+
} else {
|
|
812
|
+
appendTranscript(state, "You", text);
|
|
813
|
+
await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
|
|
814
|
+
}
|
|
815
|
+
updatePiUi(ctx, state);
|
|
816
|
+
}
|
|
817
|
+
function createRigWorkerPiBridgeExtension(options) {
|
|
818
|
+
return (pi) => {
|
|
819
|
+
const state = {
|
|
820
|
+
transcript: [],
|
|
821
|
+
status: "starting worker Pi daemon bridge",
|
|
822
|
+
activity: "",
|
|
823
|
+
cwd: "",
|
|
824
|
+
model: "",
|
|
825
|
+
commands: [],
|
|
826
|
+
streaming: false,
|
|
827
|
+
pendingUi: null,
|
|
828
|
+
wsConnected: false
|
|
829
|
+
};
|
|
830
|
+
if (options.initialMessageSent)
|
|
831
|
+
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
832
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
833
|
+
updatePiUi(ctx, state);
|
|
834
|
+
ctx.ui.notify("Rig worker Pi bridge extension loaded", "info");
|
|
835
|
+
ctx.ui.onTerminalInput((data) => {
|
|
836
|
+
if (data.includes("\x04")) {
|
|
837
|
+
ctx.shutdown();
|
|
838
|
+
return { consume: true };
|
|
839
|
+
}
|
|
840
|
+
if (!data.includes("\r") && !data.includes(`
|
|
841
|
+
`))
|
|
842
|
+
return;
|
|
843
|
+
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
844
|
+
const editorText = ctx.ui.getEditorText().trim();
|
|
845
|
+
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
846
|
+
if (!text)
|
|
847
|
+
return;
|
|
848
|
+
ctx.ui.setEditorText("");
|
|
849
|
+
routeInput(options, ctx, state, text).catch((error) => {
|
|
850
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
851
|
+
updatePiUi(ctx, state);
|
|
852
|
+
});
|
|
853
|
+
return { consume: true };
|
|
854
|
+
});
|
|
855
|
+
connectWorkerStream(options, ctx, state).catch((error) => {
|
|
856
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
857
|
+
updatePiUi(ctx, state);
|
|
858
|
+
});
|
|
859
|
+
});
|
|
860
|
+
pi.on("session_shutdown", () => {});
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
865
|
+
function setTemporaryEnv(updates) {
|
|
866
|
+
const previous = new Map;
|
|
867
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
868
|
+
previous.set(key, process.env[key]);
|
|
869
|
+
process.env[key] = value;
|
|
870
|
+
}
|
|
871
|
+
return () => {
|
|
872
|
+
for (const [key, value] of previous) {
|
|
873
|
+
if (value === undefined)
|
|
874
|
+
delete process.env[key];
|
|
875
|
+
else
|
|
876
|
+
process.env[key] = value;
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
async function attachRunBundledPiFrontend(context, input) {
|
|
881
|
+
const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
|
|
882
|
+
const cwd = join(tempRoot, "workspace");
|
|
883
|
+
const agentDir = join(tempRoot, "agent");
|
|
884
|
+
const sessionDir = join(tempRoot, "sessions");
|
|
885
|
+
const previousCwd = process.cwd();
|
|
886
|
+
const restoreEnv = setTemporaryEnv({
|
|
887
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
888
|
+
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
889
|
+
PI_OFFLINE: "1",
|
|
890
|
+
PI_SKIP_VERSION_CHECK: "1"
|
|
891
|
+
});
|
|
892
|
+
let detached = false;
|
|
893
|
+
try {
|
|
894
|
+
await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
|
|
895
|
+
process.chdir(cwd);
|
|
896
|
+
await runPiMain([
|
|
897
|
+
"--offline",
|
|
898
|
+
"--no-session",
|
|
899
|
+
"--no-tools",
|
|
900
|
+
"--no-builtin-tools",
|
|
901
|
+
"--no-skills",
|
|
902
|
+
"--no-prompt-templates",
|
|
903
|
+
"--no-themes",
|
|
904
|
+
"--no-context-files",
|
|
905
|
+
"--no-approve"
|
|
906
|
+
], {
|
|
907
|
+
extensionFactories: [
|
|
908
|
+
createRigWorkerPiBridgeExtension({
|
|
909
|
+
context,
|
|
910
|
+
runId: input.runId,
|
|
911
|
+
initialMessageSent: input.steered === true
|
|
912
|
+
})
|
|
913
|
+
]
|
|
914
|
+
});
|
|
915
|
+
detached = true;
|
|
916
|
+
} finally {
|
|
917
|
+
process.chdir(previousCwd);
|
|
918
|
+
restoreEnv();
|
|
919
|
+
rmSync(tempRoot, { recursive: true, force: true });
|
|
920
|
+
}
|
|
921
|
+
let run = { runId: input.runId, status: "unknown" };
|
|
922
|
+
try {
|
|
923
|
+
run = await getRunDetailsViaServer(context, input.runId);
|
|
924
|
+
} catch {}
|
|
925
|
+
return {
|
|
926
|
+
run,
|
|
927
|
+
logs: [],
|
|
928
|
+
timeline: [],
|
|
929
|
+
timelineCursor: null,
|
|
930
|
+
steered: input.steered === true,
|
|
931
|
+
detached,
|
|
932
|
+
rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// packages/cli/src/commands/_operator-view.ts
|
|
937
|
+
var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
409
938
|
function runStatusFromPayload(payload) {
|
|
410
939
|
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
411
940
|
return String(run.status ?? "unknown").toLowerCase();
|
|
@@ -447,9 +976,15 @@ async function readOperatorSnapshot(context, runId, options = {}) {
|
|
|
447
976
|
async function attachRunOperatorView(context, input) {
|
|
448
977
|
let steered = false;
|
|
449
978
|
if (input.message?.trim()) {
|
|
450
|
-
await steerRunViaServer(context, input.runId, input.message.trim());
|
|
979
|
+
await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
|
|
451
980
|
steered = true;
|
|
452
981
|
}
|
|
982
|
+
if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
983
|
+
return attachRunBundledPiFrontend(context, {
|
|
984
|
+
runId: input.runId,
|
|
985
|
+
steered
|
|
986
|
+
});
|
|
987
|
+
}
|
|
453
988
|
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
454
989
|
let snapshot = await readOperatorSnapshot(context, input.runId);
|
|
455
990
|
if (context.outputMode === "text") {
|
|
@@ -457,7 +992,7 @@ async function attachRunOperatorView(context, input) {
|
|
|
457
992
|
surface.renderTimeline(snapshot.timeline);
|
|
458
993
|
surface.renderLogs(snapshot.logs);
|
|
459
994
|
if (steered)
|
|
460
|
-
surface.info("
|
|
995
|
+
surface.info("Message submitted to worker Pi.");
|
|
461
996
|
}
|
|
462
997
|
let detached = false;
|
|
463
998
|
let commandInput = null;
|
|
@@ -476,7 +1011,7 @@ async function attachRunOperatorView(context, input) {
|
|
|
476
1011
|
}
|
|
477
1012
|
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
478
1013
|
let timelineCursor = snapshot.timelineCursor;
|
|
479
|
-
while (!detached && !
|
|
1014
|
+
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
480
1015
|
await Bun.sleep(pollMs);
|
|
481
1016
|
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
482
1017
|
timelineCursor = snapshot.timelineCursor;
|