@h-rig/cli 0.0.6-alpha.40 → 0.0.6-alpha.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/rig.js +506 -551
- package/dist/src/commands/_operator-view.js +504 -530
- package/dist/src/commands/_pi-frontend.js +508 -534
- package/dist/src/commands/_pi-remote-session.js +665 -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 +504 -530
- package/dist/src/commands/task-run-driver.js +2 -21
- package/dist/src/commands/task.js +504 -530
- package/dist/src/commands.js +506 -551
- package/dist/src/index.js +506 -551
- package/package.json +6 -6
package/dist/bin/rig.js
CHANGED
|
@@ -6160,6 +6160,7 @@ import {
|
|
|
6160
6160
|
writeJsonFile as writeJsonFile4
|
|
6161
6161
|
} from "@rig/runtime/control-plane/authority-files";
|
|
6162
6162
|
import { taskLookup } from "@rig/runtime/control-plane/native/task-ops";
|
|
6163
|
+
import { readPriorPrProgressPromptSection } from "@rig/runtime/control-plane/prompt-context";
|
|
6163
6164
|
import { buildProviderTaskRunInstructionLines } from "@rig/runtime/control-plane/provider/runtime-instructions";
|
|
6164
6165
|
import { loadRigTaskRunSkillBody } from "@rig/runtime/control-plane/provider/rig-task-run-skill";
|
|
6165
6166
|
function patchAuthorityRun(projectRoot, runId, patch) {
|
|
@@ -6306,7 +6307,7 @@ ${acceptance}` : null,
|
|
|
6306
6307
|
${sourceContractLines.join(`
|
|
6307
6308
|
`)}` : null,
|
|
6308
6309
|
scopeText || renderSourceScopeValidation(sourceTask, sourceValidation) || null,
|
|
6309
|
-
|
|
6310
|
+
readPriorPrProgressPromptSection(input.projectRoot, input.taskId),
|
|
6310
6311
|
initialPrompt ? `Additional operator guidance:
|
|
6311
6312
|
${initialPrompt}` : null,
|
|
6312
6313
|
providerLines.length > 0 ? `Provider-specific runtime tooling:
|
|
@@ -6316,26 +6317,6 @@ ${providerLines.join(" ")}` : null,
|
|
|
6316
6317
|
|
|
6317
6318
|
`);
|
|
6318
6319
|
}
|
|
6319
|
-
function readPriorPrProgressForPrompt(projectRoot, taskId) {
|
|
6320
|
-
for (const candidate of [
|
|
6321
|
-
resolve20(projectRoot, ".worktrees", taskId, "artifacts", taskId, "pr-state.json"),
|
|
6322
|
-
resolve20(projectRoot, "artifacts", taskId, "pr-state.json")
|
|
6323
|
-
]) {
|
|
6324
|
-
try {
|
|
6325
|
-
const raw = JSON.parse(readFileSync8(candidate, "utf8"));
|
|
6326
|
-
const entries = Array.isArray(raw) ? raw : [raw];
|
|
6327
|
-
const first = entries.find((entry) => entry && typeof entry === "object" && typeof entry.url === "string");
|
|
6328
|
-
if (!first)
|
|
6329
|
-
continue;
|
|
6330
|
-
return [
|
|
6331
|
-
`Prior progress exists for this task: PR ${first.url}${first.branch ? ` (branch ${first.branch})` : ""} was opened by an earlier run.`,
|
|
6332
|
-
"Check its current state first (diff, checks, review). If the work is already complete and checks are green,",
|
|
6333
|
-
"run `rig-agent completion-verification` to merge and close instead of re-implementing anything."
|
|
6334
|
-
].join(" ");
|
|
6335
|
-
} catch {}
|
|
6336
|
-
}
|
|
6337
|
-
return null;
|
|
6338
|
-
}
|
|
6339
6320
|
function firstPromptString(...values) {
|
|
6340
6321
|
for (const value of values) {
|
|
6341
6322
|
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
@@ -7402,435 +7383,394 @@ async function promptForTaskSelection(question) {
|
|
|
7402
7383
|
import { mkdtempSync, rmSync as rmSync5 } from "fs";
|
|
7403
7384
|
import { tmpdir } from "os";
|
|
7404
7385
|
import { join as join2 } from "path";
|
|
7405
|
-
import {
|
|
7386
|
+
import {
|
|
7387
|
+
createAgentSessionFromServices,
|
|
7388
|
+
createAgentSessionServices,
|
|
7389
|
+
main as runPiMain
|
|
7390
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7406
7391
|
|
|
7407
|
-
// packages/cli/src/commands/_pi-
|
|
7392
|
+
// packages/cli/src/commands/_pi-remote-session.ts
|
|
7393
|
+
import { AgentSession as PiAgentSession } from "@earendil-works/pi-coding-agent";
|
|
7408
7394
|
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
7409
|
-
|
|
7395
|
+
function defaultTransport() {
|
|
7396
|
+
return {
|
|
7397
|
+
getSession: getRunPiSessionViaServer,
|
|
7398
|
+
getMessages: getRunPiMessagesViaServer,
|
|
7399
|
+
getStatus: getRunPiStatusViaServer,
|
|
7400
|
+
getCommands: getRunPiCommandsViaServer,
|
|
7401
|
+
sendPrompt: sendRunPiPromptViaServer,
|
|
7402
|
+
sendShell: sendRunPiShellViaServer,
|
|
7403
|
+
runCommand: runRunPiCommandViaServer,
|
|
7404
|
+
abort: abortRunPiViaServer,
|
|
7405
|
+
buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
|
|
7406
|
+
};
|
|
7407
|
+
}
|
|
7410
7408
|
function recordOf(value) {
|
|
7411
7409
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
7412
7410
|
}
|
|
7413
|
-
function
|
|
7414
|
-
|
|
7415
|
-
|
|
7416
|
-
|
|
7417
|
-
|
|
7418
|
-
|
|
7419
|
-
|
|
7420
|
-
|
|
7421
|
-
|
|
7422
|
-
|
|
7423
|
-
|
|
7424
|
-
|
|
7425
|
-
|
|
7426
|
-
|
|
7427
|
-
|
|
7428
|
-
return content;
|
|
7429
|
-
if (!Array.isArray(content))
|
|
7430
|
-
return asText(content);
|
|
7431
|
-
return content.flatMap((part) => {
|
|
7432
|
-
const item = recordOf(part);
|
|
7433
|
-
if (!item)
|
|
7434
|
-
return [];
|
|
7435
|
-
if (typeof item.text === "string")
|
|
7436
|
-
return [item.text];
|
|
7437
|
-
if (typeof item.content === "string")
|
|
7438
|
-
return [item.content];
|
|
7439
|
-
if (item.type === "toolCall")
|
|
7440
|
-
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
7441
|
-
if (item.type === "toolResult")
|
|
7442
|
-
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
7443
|
-
return [];
|
|
7444
|
-
}).join(`
|
|
7445
|
-
`);
|
|
7446
|
-
}
|
|
7447
|
-
function appendTranscript(state, label, text2) {
|
|
7448
|
-
const trimmed = text2.trimEnd();
|
|
7449
|
-
if (!trimmed)
|
|
7450
|
-
return;
|
|
7451
|
-
const lines = trimmed.split(/\r?\n/);
|
|
7452
|
-
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
7453
|
-
for (const line of lines.slice(1))
|
|
7454
|
-
state.transcript.push(` ${line}`);
|
|
7455
|
-
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
7456
|
-
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
7457
|
-
}
|
|
7458
|
-
}
|
|
7459
|
-
function nativePiUi(ctx) {
|
|
7460
|
-
const ui = ctx.ui;
|
|
7461
|
-
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
7462
|
-
}
|
|
7463
|
-
function syncNativeDisplayCwd(ctx, state) {
|
|
7464
|
-
const ui = nativePiUi(ctx);
|
|
7465
|
-
if (ui?.setDisplayCwd && state.cwd)
|
|
7466
|
-
ui.setDisplayCwd(state.cwd);
|
|
7467
|
-
}
|
|
7468
|
-
function parseExtensionUiRequest(value) {
|
|
7469
|
-
const request = recordOf(value) ?? {};
|
|
7470
|
-
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
7471
|
-
const method = String(request.method ?? request.type ?? "input");
|
|
7472
|
-
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
7473
|
-
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
7474
|
-
const options = rawOptions.map((option) => {
|
|
7475
|
-
const record = recordOf(option);
|
|
7476
|
-
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
7477
|
-
}).filter(Boolean);
|
|
7478
|
-
return { requestId, method, prompt, options };
|
|
7479
|
-
}
|
|
7480
|
-
function renderBridgeWidget(state) {
|
|
7481
|
-
const statusParts = [
|
|
7482
|
-
state.wsConnected ? "live" : "connecting",
|
|
7483
|
-
state.status,
|
|
7484
|
-
state.model,
|
|
7485
|
-
state.cwd
|
|
7486
|
-
].filter(Boolean);
|
|
7487
|
-
const lines = [`Rig worker session \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
7488
|
-
if (state.activity)
|
|
7489
|
-
lines.push(state.activity);
|
|
7490
|
-
if (state.commands.length > 0) {
|
|
7491
|
-
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
7492
|
-
}
|
|
7493
|
-
lines.push("");
|
|
7494
|
-
if (state.transcript.length > 0) {
|
|
7495
|
-
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
7496
|
-
} else {
|
|
7497
|
-
lines.push("Waiting for the worker session transcript\u2026 (/detach exits and leaves the worker running)");
|
|
7498
|
-
}
|
|
7499
|
-
if (state.pendingUi) {
|
|
7500
|
-
lines.push("");
|
|
7501
|
-
lines.push(`Worker needs input \xB7 ${state.pendingUi.method}`);
|
|
7502
|
-
lines.push(state.pendingUi.prompt);
|
|
7503
|
-
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
7504
|
-
lines.push("Reply in the editor below. /cancel dismisses this request.");
|
|
7505
|
-
}
|
|
7506
|
-
return lines;
|
|
7507
|
-
}
|
|
7508
|
-
function reportBridgeError(ctx, state, message2) {
|
|
7509
|
-
appendTranscript(state, "Error", message2);
|
|
7510
|
-
state.status = message2;
|
|
7511
|
-
try {
|
|
7512
|
-
ctx.ui.notify(message2, "error");
|
|
7513
|
-
} catch {}
|
|
7514
|
-
updatePiUi(ctx, state);
|
|
7515
|
-
}
|
|
7516
|
-
function updatePiUi(ctx, state) {
|
|
7517
|
-
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
7518
|
-
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker session live" : state.status);
|
|
7519
|
-
syncNativeDisplayCwd(ctx, state);
|
|
7520
|
-
if (state.nativeStream && nativePiUi(ctx)) {
|
|
7521
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
7522
|
-
return;
|
|
7523
|
-
}
|
|
7524
|
-
ctx.ui.setWorkingVisible(false);
|
|
7525
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
|
|
7526
|
-
}
|
|
7527
|
-
function applyStatus(state, payload) {
|
|
7528
|
-
const status = recordOf(payload.status) ?? payload;
|
|
7529
|
-
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
7530
|
-
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
7531
|
-
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
7532
|
-
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
7533
|
-
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
7534
|
-
}
|
|
7535
|
-
function applyMessage(state, message2) {
|
|
7536
|
-
const record = recordOf(message2);
|
|
7537
|
-
if (!record)
|
|
7538
|
-
return;
|
|
7539
|
-
const role = String(record.role ?? "system");
|
|
7540
|
-
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
7541
|
-
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
7542
|
-
}
|
|
7543
|
-
function applyPiEvent(ctx, state, eventValue) {
|
|
7544
|
-
const event = recordOf(eventValue);
|
|
7545
|
-
if (!event)
|
|
7546
|
-
return;
|
|
7547
|
-
const type = String(event.type ?? "event");
|
|
7548
|
-
if (type === "agent_start") {
|
|
7549
|
-
state.streaming = true;
|
|
7550
|
-
state.status = "streaming";
|
|
7551
|
-
} else if (type === "agent_end") {
|
|
7552
|
-
state.streaming = false;
|
|
7553
|
-
state.status = "idle";
|
|
7554
|
-
} else if (type === "queue_update") {
|
|
7555
|
-
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
7556
|
-
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
7557
|
-
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
7558
|
-
}
|
|
7559
|
-
const native = nativePiUi(ctx);
|
|
7560
|
-
if (state.nativeStream && native?.emitSessionEvent) {
|
|
7561
|
-
native.emitSessionEvent(eventValue);
|
|
7562
|
-
return;
|
|
7563
|
-
}
|
|
7564
|
-
if (type === "agent_end") {
|
|
7565
|
-
appendTranscript(state, "System", "Agent turn complete.");
|
|
7566
|
-
return;
|
|
7567
|
-
}
|
|
7568
|
-
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
7569
|
-
applyMessage(state, event.message);
|
|
7570
|
-
return;
|
|
7571
|
-
}
|
|
7572
|
-
if (type === "message_update") {
|
|
7573
|
-
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
7574
|
-
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
7575
|
-
if (delta)
|
|
7576
|
-
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
7577
|
-
return;
|
|
7578
|
-
}
|
|
7579
|
-
if (type === "tool_execution_start") {
|
|
7580
|
-
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
7581
|
-
return;
|
|
7582
|
-
}
|
|
7583
|
-
if (type === "tool_execution_update") {
|
|
7584
|
-
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
7585
|
-
return;
|
|
7586
|
-
}
|
|
7587
|
-
if (type === "tool_execution_end") {
|
|
7588
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
7589
|
-
}
|
|
7590
|
-
}
|
|
7591
|
-
function firstPendingShell(state) {
|
|
7592
|
-
return state.pendingShells[0];
|
|
7593
|
-
}
|
|
7594
|
-
function finishPendingShell(state, shell, result) {
|
|
7595
|
-
const index = state.pendingShells.indexOf(shell);
|
|
7596
|
-
if (index !== -1)
|
|
7597
|
-
state.pendingShells.splice(index, 1);
|
|
7598
|
-
shell.resolve(result);
|
|
7599
|
-
}
|
|
7600
|
-
function failPendingShell(state, shell, error) {
|
|
7601
|
-
const index = state.pendingShells.indexOf(shell);
|
|
7602
|
-
if (index !== -1)
|
|
7603
|
-
state.pendingShells.splice(index, 1);
|
|
7604
|
-
shell.reject(error);
|
|
7605
|
-
}
|
|
7606
|
-
function applyUiEvent(state, value) {
|
|
7607
|
-
const event = recordOf(value);
|
|
7608
|
-
if (!event)
|
|
7609
|
-
return;
|
|
7610
|
-
const type = String(event.type ?? "ui");
|
|
7611
|
-
if (type === "shell.chunk") {
|
|
7612
|
-
const pending = firstPendingShell(state);
|
|
7613
|
-
const chunk = asText(event.chunk);
|
|
7614
|
-
if (pending) {
|
|
7615
|
-
pending.sawChunk = true;
|
|
7616
|
-
pending.onData(Buffer.from(chunk));
|
|
7617
|
-
} else {
|
|
7618
|
-
appendTranscript(state, "Tool", chunk);
|
|
7619
|
-
}
|
|
7620
|
-
return;
|
|
7621
|
-
}
|
|
7622
|
-
if (type === "shell.end") {
|
|
7623
|
-
const pending = firstPendingShell(state);
|
|
7624
|
-
const output = asText(event.output ?? "");
|
|
7625
|
-
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
7626
|
-
if (pending) {
|
|
7627
|
-
if (output && !pending.sawChunk)
|
|
7628
|
-
pending.onData(Buffer.from(output));
|
|
7629
|
-
finishPendingShell(state, pending, { exitCode });
|
|
7630
|
-
} else {
|
|
7631
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
7632
|
-
}
|
|
7633
|
-
return;
|
|
7634
|
-
}
|
|
7635
|
-
if (type === "shell.start") {
|
|
7636
|
-
if (!firstPendingShell(state))
|
|
7637
|
-
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
7638
|
-
return;
|
|
7639
|
-
}
|
|
7640
|
-
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
7641
|
-
}
|
|
7642
|
-
function applyEnvelope(ctx, state, envelopeValue) {
|
|
7643
|
-
const envelope = recordOf(envelopeValue);
|
|
7644
|
-
if (!envelope)
|
|
7645
|
-
return;
|
|
7646
|
-
const type = String(envelope.type ?? "");
|
|
7647
|
-
if (type === "ready") {
|
|
7648
|
-
const metadata = recordOf(envelope.metadata);
|
|
7649
|
-
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
7650
|
-
state.status = "worker Pi daemon ready";
|
|
7651
|
-
if (!state.nativeStream)
|
|
7652
|
-
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
7653
|
-
} else if (type === "status.update") {
|
|
7654
|
-
applyStatus(state, envelope);
|
|
7655
|
-
} else if (type === "activity.update") {
|
|
7656
|
-
const activity = recordOf(envelope.activity);
|
|
7657
|
-
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
7658
|
-
} else if (type === "extension_ui_request") {
|
|
7659
|
-
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
7660
|
-
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
7661
|
-
} else if (type === "pi.ui_event") {
|
|
7662
|
-
applyUiEvent(state, envelope.event);
|
|
7663
|
-
} else if (type === "pi.event") {
|
|
7664
|
-
applyPiEvent(ctx, state, envelope.event);
|
|
7665
|
-
} else if (type === "error") {
|
|
7666
|
-
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
7667
|
-
}
|
|
7668
|
-
syncNativeDisplayCwd(ctx, state);
|
|
7411
|
+
function emptyRemoteStatus() {
|
|
7412
|
+
return {
|
|
7413
|
+
isStreaming: false,
|
|
7414
|
+
isCompacting: false,
|
|
7415
|
+
isBashRunning: false,
|
|
7416
|
+
pendingMessageCount: 0,
|
|
7417
|
+
steeringMessages: [],
|
|
7418
|
+
followUpMessages: [],
|
|
7419
|
+
model: null,
|
|
7420
|
+
thinkingLevel: null,
|
|
7421
|
+
sessionName: null,
|
|
7422
|
+
cwd: null,
|
|
7423
|
+
stats: null,
|
|
7424
|
+
contextUsage: null
|
|
7425
|
+
};
|
|
7669
7426
|
}
|
|
7670
7427
|
function resolveAttachReadyTimeoutMs() {
|
|
7671
7428
|
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
7672
7429
|
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
7673
7430
|
}
|
|
7674
|
-
|
|
7675
|
-
|
|
7676
|
-
|
|
7677
|
-
|
|
7678
|
-
|
|
7679
|
-
|
|
7680
|
-
|
|
7681
|
-
|
|
7682
|
-
|
|
7683
|
-
|
|
7684
|
-
|
|
7685
|
-
|
|
7686
|
-
|
|
7687
|
-
|
|
7688
|
-
|
|
7689
|
-
|
|
7690
|
-
|
|
7691
|
-
|
|
7692
|
-
|
|
7693
|
-
|
|
7694
|
-
|
|
7695
|
-
|
|
7696
|
-
|
|
7697
|
-
|
|
7698
|
-
|
|
7699
|
-
|
|
7700
|
-
|
|
7701
|
-
|
|
7702
|
-
|
|
7703
|
-
|
|
7704
|
-
|
|
7705
|
-
|
|
7706
|
-
|
|
7707
|
-
|
|
7708
|
-
|
|
7709
|
-
return false;
|
|
7710
|
-
}
|
|
7711
|
-
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
7712
|
-
continue;
|
|
7713
|
-
}
|
|
7714
|
-
const sessionRecord = recordOf(session) ?? {};
|
|
7715
|
-
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
7716
|
-
updatePiUi(ctx, state);
|
|
7717
|
-
return true;
|
|
7718
|
-
}
|
|
7719
|
-
}
|
|
7720
|
-
function parseWsPayload(message2) {
|
|
7721
|
-
if (typeof message2.data === "string")
|
|
7722
|
-
return JSON.parse(message2.data);
|
|
7723
|
-
return JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
7724
|
-
}
|
|
7725
|
-
var BRIDGE_LOCAL_COMMANDS = new Set(["detach", "quit", "q", "stop"]);
|
|
7726
|
-
function registerDaemonCommandsNatively(pi, options, ctx, state, commands, registered) {
|
|
7727
|
-
for (const command of commands) {
|
|
7728
|
-
const record = recordOf(command);
|
|
7729
|
-
const name = typeof record?.name === "string" ? record.name : "";
|
|
7730
|
-
if (!name || registered.has(name) || BRIDGE_LOCAL_COMMANDS.has(name))
|
|
7731
|
-
continue;
|
|
7732
|
-
registered.add(name);
|
|
7733
|
-
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
7734
|
-
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
7735
|
-
try {
|
|
7736
|
-
pi.registerCommand(name, {
|
|
7737
|
-
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
7738
|
-
handler: async (args) => {
|
|
7739
|
-
const text2 = `/${name}${args ? ` ${args}` : ""}`;
|
|
7740
|
-
appendTranscript(state, "You", text2);
|
|
7741
|
-
try {
|
|
7742
|
-
const result = await runRunPiCommandViaServer(options.context, options.runId, text2);
|
|
7743
|
-
const message2 = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
7744
|
-
appendTranscript(state, "System", message2);
|
|
7745
|
-
if (state.nativeStream)
|
|
7746
|
-
ctx.ui.notify(message2, "info");
|
|
7747
|
-
} catch (error) {
|
|
7748
|
-
reportBridgeError(ctx, state, error instanceof Error ? error.message : String(error));
|
|
7749
|
-
}
|
|
7750
|
-
updatePiUi(ctx, state);
|
|
7751
|
-
}
|
|
7752
|
-
});
|
|
7753
|
-
} catch {}
|
|
7754
|
-
}
|
|
7755
|
-
}
|
|
7756
|
-
async function connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands) {
|
|
7757
|
-
const ready = await waitForWorkerReady(options, ctx, state);
|
|
7758
|
-
if (!ready)
|
|
7759
|
-
return;
|
|
7760
|
-
let catchupDone = false;
|
|
7761
|
-
const buffered = [];
|
|
7762
|
-
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
7763
|
-
const socket = new WebSocket(wsUrl);
|
|
7764
|
-
const closePromise = new Promise((resolve22) => {
|
|
7431
|
+
|
|
7432
|
+
class RigRemoteSessionController {
|
|
7433
|
+
context;
|
|
7434
|
+
runId;
|
|
7435
|
+
status = emptyRemoteStatus();
|
|
7436
|
+
transport;
|
|
7437
|
+
hooks = {};
|
|
7438
|
+
session = null;
|
|
7439
|
+
socket = null;
|
|
7440
|
+
closed = false;
|
|
7441
|
+
pendingShells = [];
|
|
7442
|
+
pendingCompactions = [];
|
|
7443
|
+
constructor(input) {
|
|
7444
|
+
this.context = input.context;
|
|
7445
|
+
this.runId = input.runId;
|
|
7446
|
+
this.transport = input.transport ?? defaultTransport();
|
|
7447
|
+
}
|
|
7448
|
+
ingestEnvelope(envelopeValue) {
|
|
7449
|
+
this.applyEnvelope(envelopeValue);
|
|
7450
|
+
}
|
|
7451
|
+
bindSession(session) {
|
|
7452
|
+
this.session = session;
|
|
7453
|
+
}
|
|
7454
|
+
setUiHooks(hooks) {
|
|
7455
|
+
this.hooks = hooks;
|
|
7456
|
+
}
|
|
7457
|
+
async connect() {
|
|
7458
|
+
const ready = await this.waitForReady();
|
|
7459
|
+
if (!ready || this.closed)
|
|
7460
|
+
return;
|
|
7461
|
+
let catchupDone = false;
|
|
7462
|
+
const buffered = [];
|
|
7463
|
+
const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
|
|
7464
|
+
const socket = new WebSocket(wsUrl);
|
|
7465
|
+
this.socket = socket;
|
|
7765
7466
|
socket.onopen = () => {
|
|
7766
|
-
|
|
7767
|
-
|
|
7768
|
-
updatePiUi(ctx, state);
|
|
7467
|
+
this.hooks.onConnectionChange?.(true);
|
|
7468
|
+
this.hooks.onStatusText?.("worker session live");
|
|
7769
7469
|
};
|
|
7770
7470
|
socket.onmessage = (message2) => {
|
|
7771
7471
|
try {
|
|
7772
|
-
const payload =
|
|
7472
|
+
const payload = typeof message2.data === "string" ? JSON.parse(message2.data) : JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
7773
7473
|
if (!catchupDone)
|
|
7774
7474
|
buffered.push(payload);
|
|
7775
|
-
else
|
|
7776
|
-
applyEnvelope(
|
|
7777
|
-
updatePiUi(ctx, state);
|
|
7778
|
-
}
|
|
7475
|
+
else
|
|
7476
|
+
this.applyEnvelope(payload);
|
|
7779
7477
|
} catch (error) {
|
|
7780
|
-
|
|
7781
|
-
updatePiUi(ctx, state);
|
|
7478
|
+
this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
7782
7479
|
}
|
|
7783
7480
|
};
|
|
7784
7481
|
socket.onerror = () => socket.close();
|
|
7785
7482
|
socket.onclose = () => {
|
|
7786
|
-
|
|
7787
|
-
|
|
7788
|
-
|
|
7789
|
-
resolve22();
|
|
7483
|
+
this.hooks.onConnectionChange?.(false);
|
|
7484
|
+
if (!this.closed)
|
|
7485
|
+
this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
|
|
7790
7486
|
};
|
|
7791
|
-
|
|
7792
|
-
|
|
7793
|
-
|
|
7794
|
-
|
|
7795
|
-
|
|
7796
|
-
|
|
7797
|
-
|
|
7798
|
-
|
|
7799
|
-
|
|
7800
|
-
|
|
7801
|
-
|
|
7487
|
+
try {
|
|
7488
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
7489
|
+
this.transport.getMessages(this.context, this.runId),
|
|
7490
|
+
this.transport.getStatus(this.context, this.runId),
|
|
7491
|
+
this.transport.getCommands(this.context, this.runId)
|
|
7492
|
+
]);
|
|
7493
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
7494
|
+
this.applyStatusPayload(statusPayload);
|
|
7495
|
+
this.session?.replaceRemoteMessages(messages);
|
|
7496
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
7497
|
+
this.hooks.onCatchUp?.(messages, commands);
|
|
7498
|
+
catchupDone = true;
|
|
7499
|
+
for (const payload of buffered.splice(0))
|
|
7500
|
+
this.applyEnvelope(payload);
|
|
7501
|
+
} catch (error) {
|
|
7502
|
+
catchupDone = true;
|
|
7503
|
+
this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
7504
|
+
}
|
|
7505
|
+
}
|
|
7506
|
+
close() {
|
|
7507
|
+
this.closed = true;
|
|
7508
|
+
this.socket?.close();
|
|
7509
|
+
for (const shell of this.pendingShells.splice(0))
|
|
7510
|
+
shell.reject(new Error("Remote session closed."));
|
|
7511
|
+
for (const compaction of this.pendingCompactions.splice(0))
|
|
7512
|
+
compaction.reject(new Error("Remote session closed."));
|
|
7513
|
+
}
|
|
7514
|
+
async sendPrompt(text2, streamingBehavior) {
|
|
7515
|
+
await this.transport.sendPrompt(this.context, this.runId, text2, streamingBehavior);
|
|
7516
|
+
}
|
|
7517
|
+
async sendCommand(text2) {
|
|
7518
|
+
const result = await this.transport.runCommand(this.context, this.runId, text2);
|
|
7519
|
+
return typeof result.message === "string" ? result.message : "worker command accepted";
|
|
7520
|
+
}
|
|
7521
|
+
async sendShell(text2) {
|
|
7522
|
+
await this.transport.sendShell(this.context, this.runId, text2);
|
|
7523
|
+
}
|
|
7524
|
+
async abort() {
|
|
7525
|
+
await this.transport.abort(this.context, this.runId);
|
|
7526
|
+
}
|
|
7527
|
+
registerPendingShell(shell) {
|
|
7528
|
+
this.pendingShells.push(shell);
|
|
7529
|
+
}
|
|
7530
|
+
failPendingShell(shell, error) {
|
|
7531
|
+
const index = this.pendingShells.indexOf(shell);
|
|
7532
|
+
if (index !== -1)
|
|
7533
|
+
this.pendingShells.splice(index, 1);
|
|
7534
|
+
shell.reject(error);
|
|
7535
|
+
}
|
|
7536
|
+
registerPendingCompaction(pending) {
|
|
7537
|
+
this.pendingCompactions.push(pending);
|
|
7538
|
+
}
|
|
7539
|
+
async waitForReady() {
|
|
7540
|
+
const startedAt = Date.now();
|
|
7541
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
7542
|
+
let consecutiveFailures = 0;
|
|
7543
|
+
while (!this.closed) {
|
|
7544
|
+
let requestFailed = false;
|
|
7545
|
+
const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
|
|
7546
|
+
requestFailed = true;
|
|
7547
|
+
return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
|
|
7548
|
+
});
|
|
7549
|
+
if (session.ready !== false)
|
|
7550
|
+
return true;
|
|
7551
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
7552
|
+
const status = String(session.status ?? "starting");
|
|
7553
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
7554
|
+
this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
|
|
7555
|
+
return false;
|
|
7556
|
+
}
|
|
7557
|
+
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`);
|
|
7558
|
+
if (Date.now() >= deadline) {
|
|
7559
|
+
this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
|
|
7560
|
+
return false;
|
|
7561
|
+
}
|
|
7562
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
7563
|
+
}
|
|
7564
|
+
return false;
|
|
7565
|
+
}
|
|
7566
|
+
applyEnvelope(envelopeValue) {
|
|
7567
|
+
const envelope = recordOf(envelopeValue);
|
|
7568
|
+
if (!envelope)
|
|
7569
|
+
return;
|
|
7570
|
+
const type = String(envelope.type ?? "");
|
|
7571
|
+
if (type === "status.update") {
|
|
7572
|
+
this.applyStatusPayload(envelope);
|
|
7573
|
+
return;
|
|
7574
|
+
}
|
|
7575
|
+
if (type === "activity.update") {
|
|
7576
|
+
const activity = recordOf(envelope.activity);
|
|
7577
|
+
this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
|
|
7578
|
+
return;
|
|
7579
|
+
}
|
|
7580
|
+
if (type === "extension_ui_request") {
|
|
7581
|
+
const request = recordOf(envelope.request);
|
|
7582
|
+
if (request)
|
|
7583
|
+
this.hooks.onExtensionUiRequest?.(request);
|
|
7584
|
+
return;
|
|
7585
|
+
}
|
|
7586
|
+
if (type === "pi.ui_event") {
|
|
7587
|
+
this.applyShellUiEvent(envelope.event);
|
|
7588
|
+
return;
|
|
7589
|
+
}
|
|
7590
|
+
if (type === "pi.event") {
|
|
7591
|
+
this.session?.handleRemoteSessionEvent(envelope.event);
|
|
7592
|
+
this.settlePendingCompaction(envelope.event);
|
|
7593
|
+
return;
|
|
7594
|
+
}
|
|
7595
|
+
if (type === "error") {
|
|
7596
|
+
this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
|
|
7597
|
+
}
|
|
7598
|
+
}
|
|
7599
|
+
applyStatusPayload(payload) {
|
|
7600
|
+
const status = recordOf(payload.status) ?? payload;
|
|
7601
|
+
const next = this.status;
|
|
7602
|
+
next.isStreaming = status.isStreaming === true;
|
|
7603
|
+
next.isCompacting = status.isCompacting === true;
|
|
7604
|
+
next.isBashRunning = status.isBashRunning === true;
|
|
7605
|
+
next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
7606
|
+
next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
|
|
7607
|
+
next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
|
|
7608
|
+
next.model = recordOf(status.model) ?? next.model;
|
|
7609
|
+
next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
|
|
7610
|
+
next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
|
|
7611
|
+
next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
|
|
7612
|
+
next.stats = recordOf(status.stats) ?? next.stats;
|
|
7613
|
+
next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
|
|
7614
|
+
}
|
|
7615
|
+
applyShellUiEvent(value) {
|
|
7616
|
+
const event = recordOf(value);
|
|
7617
|
+
if (!event)
|
|
7618
|
+
return;
|
|
7619
|
+
const type = String(event.type ?? "");
|
|
7620
|
+
const pending = this.pendingShells[0];
|
|
7621
|
+
if (type === "shell.chunk" && pending) {
|
|
7622
|
+
pending.sawChunk = true;
|
|
7623
|
+
pending.onData(Buffer.from(String(event.chunk ?? "")));
|
|
7624
|
+
return;
|
|
7625
|
+
}
|
|
7626
|
+
if (type === "shell.end" && pending) {
|
|
7627
|
+
const output = String(event.output ?? "");
|
|
7628
|
+
if (output && !pending.sawChunk)
|
|
7629
|
+
pending.onData(Buffer.from(output));
|
|
7630
|
+
const index = this.pendingShells.indexOf(pending);
|
|
7631
|
+
if (index !== -1)
|
|
7632
|
+
this.pendingShells.splice(index, 1);
|
|
7633
|
+
pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
|
|
7634
|
+
}
|
|
7635
|
+
}
|
|
7636
|
+
settlePendingCompaction(eventValue) {
|
|
7637
|
+
const event = recordOf(eventValue);
|
|
7638
|
+
if (!event)
|
|
7639
|
+
return;
|
|
7640
|
+
const type = String(event.type ?? "");
|
|
7641
|
+
if (type !== "compaction_end" || this.pendingCompactions.length === 0)
|
|
7642
|
+
return;
|
|
7643
|
+
const pending = this.pendingCompactions.shift();
|
|
7644
|
+
const result = recordOf(event.result);
|
|
7645
|
+
if (result)
|
|
7646
|
+
pending.resolve(result);
|
|
7647
|
+
else if (event.aborted === true)
|
|
7648
|
+
pending.reject(new Error("Compaction aborted on the worker."));
|
|
7802
7649
|
else
|
|
7803
|
-
|
|
7804
|
-
|
|
7805
|
-
|
|
7806
|
-
|
|
7807
|
-
|
|
7808
|
-
|
|
7809
|
-
|
|
7650
|
+
pending.resolve({});
|
|
7651
|
+
}
|
|
7652
|
+
}
|
|
7653
|
+
|
|
7654
|
+
class RigRemoteAgentSession extends PiAgentSession {
|
|
7655
|
+
remote;
|
|
7656
|
+
constructor(config, remote) {
|
|
7657
|
+
super(config);
|
|
7658
|
+
this.remote = remote;
|
|
7659
|
+
remote.bindSession(this);
|
|
7660
|
+
}
|
|
7661
|
+
handleRemoteSessionEvent(eventValue) {
|
|
7662
|
+
const event = recordOf(eventValue);
|
|
7663
|
+
if (!event)
|
|
7664
|
+
return;
|
|
7665
|
+
const type = String(event.type ?? "");
|
|
7666
|
+
if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
|
|
7667
|
+
this.agent.state.messages = [...this.agent.state.messages, event.message];
|
|
7668
|
+
}
|
|
7669
|
+
this._emit(eventValue);
|
|
7670
|
+
}
|
|
7671
|
+
replaceRemoteMessages(messages) {
|
|
7672
|
+
this.agent.state.messages = messages;
|
|
7673
|
+
}
|
|
7674
|
+
async prompt(text2, options) {
|
|
7675
|
+
const trimmed = text2.trim();
|
|
7676
|
+
if (!trimmed)
|
|
7677
|
+
return;
|
|
7678
|
+
if (trimmed.startsWith("/")) {
|
|
7679
|
+
if (await this._tryExecuteExtensionCommand(trimmed))
|
|
7680
|
+
return;
|
|
7681
|
+
await this.remote.sendCommand(trimmed);
|
|
7682
|
+
return;
|
|
7683
|
+
}
|
|
7684
|
+
if (trimmed.startsWith("!")) {
|
|
7685
|
+
await this.remote.sendShell(trimmed);
|
|
7686
|
+
return;
|
|
7687
|
+
}
|
|
7688
|
+
const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
7689
|
+
options?.preflightResult?.(true);
|
|
7690
|
+
await this.remote.sendPrompt(trimmed, behavior);
|
|
7691
|
+
}
|
|
7692
|
+
async steer(text2) {
|
|
7693
|
+
await this.remote.sendPrompt(text2, "steer");
|
|
7694
|
+
}
|
|
7695
|
+
async followUp(text2) {
|
|
7696
|
+
await this.remote.sendPrompt(text2, "followUp");
|
|
7697
|
+
}
|
|
7698
|
+
async abort() {
|
|
7699
|
+
await this.remote.abort();
|
|
7700
|
+
}
|
|
7701
|
+
async compact(customInstructions) {
|
|
7702
|
+
const pending = new Promise((resolve22, reject) => {
|
|
7703
|
+
this.remote.registerPendingCompaction({ resolve: resolve22, reject });
|
|
7810
7704
|
});
|
|
7811
|
-
|
|
7812
|
-
|
|
7813
|
-
|
|
7814
|
-
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
|
|
7818
|
-
|
|
7819
|
-
|
|
7705
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
7706
|
+
return pending;
|
|
7707
|
+
}
|
|
7708
|
+
clearQueue() {
|
|
7709
|
+
const cleared = {
|
|
7710
|
+
steering: [...this.remote.status.steeringMessages],
|
|
7711
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
7712
|
+
};
|
|
7713
|
+
this.remote.status.steeringMessages = [];
|
|
7714
|
+
this.remote.status.followUpMessages = [];
|
|
7715
|
+
this.remote.status.pendingMessageCount = 0;
|
|
7716
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
7717
|
+
return cleared;
|
|
7718
|
+
}
|
|
7719
|
+
get isStreaming() {
|
|
7720
|
+
return this.remote.status.isStreaming;
|
|
7721
|
+
}
|
|
7722
|
+
get isCompacting() {
|
|
7723
|
+
return this.remote.status.isCompacting;
|
|
7724
|
+
}
|
|
7725
|
+
get isBashRunning() {
|
|
7726
|
+
return this.remote.status.isBashRunning;
|
|
7727
|
+
}
|
|
7728
|
+
get pendingMessageCount() {
|
|
7729
|
+
return this.remote.status.pendingMessageCount;
|
|
7730
|
+
}
|
|
7731
|
+
getSteeringMessages() {
|
|
7732
|
+
return this.remote.status.steeringMessages;
|
|
7733
|
+
}
|
|
7734
|
+
getFollowUpMessages() {
|
|
7735
|
+
return this.remote.status.followUpMessages;
|
|
7736
|
+
}
|
|
7737
|
+
get model() {
|
|
7738
|
+
return this.remote.status.model ?? super.model;
|
|
7739
|
+
}
|
|
7740
|
+
async setModel(model) {
|
|
7741
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
7742
|
+
this.remote.status.model = model;
|
|
7743
|
+
}
|
|
7744
|
+
get thinkingLevel() {
|
|
7745
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
7746
|
+
}
|
|
7747
|
+
setThinkingLevel(level) {
|
|
7748
|
+
this.remote.status.thinkingLevel = level;
|
|
7749
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
7750
|
+
}
|
|
7751
|
+
get sessionName() {
|
|
7752
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
7753
|
+
}
|
|
7754
|
+
setSessionName(name) {
|
|
7755
|
+
this.remote.status.sessionName = name;
|
|
7756
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
7757
|
+
}
|
|
7758
|
+
getSessionStats() {
|
|
7759
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
7760
|
+
}
|
|
7761
|
+
getContextUsage() {
|
|
7762
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
7763
|
+
}
|
|
7764
|
+
dispose() {
|
|
7765
|
+
this.remote.close();
|
|
7766
|
+
super.dispose();
|
|
7820
7767
|
}
|
|
7821
|
-
await closePromise;
|
|
7822
7768
|
}
|
|
7823
|
-
function createRemoteBashOperations(
|
|
7769
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
7824
7770
|
return {
|
|
7825
7771
|
exec(command, _cwd, execOptions) {
|
|
7826
7772
|
return new Promise((resolve22, reject) => {
|
|
7827
|
-
const pending = {
|
|
7828
|
-
command,
|
|
7829
|
-
onData: execOptions.onData,
|
|
7830
|
-
resolve: resolve22,
|
|
7831
|
-
reject,
|
|
7832
|
-
sawChunk: false
|
|
7833
|
-
};
|
|
7773
|
+
const pending = { onData: execOptions.onData, resolve: resolve22, reject, sawChunk: false };
|
|
7834
7774
|
const cleanup = () => {
|
|
7835
7775
|
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
7836
7776
|
if (timer)
|
|
@@ -7838,12 +7778,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
7838
7778
|
};
|
|
7839
7779
|
const onAbort = () => {
|
|
7840
7780
|
cleanup();
|
|
7841
|
-
failPendingShell(
|
|
7781
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
7842
7782
|
};
|
|
7843
7783
|
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
7844
7784
|
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
7845
7785
|
cleanup();
|
|
7846
|
-
failPendingShell(
|
|
7786
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
7847
7787
|
}, timeoutMs) : null;
|
|
7848
7788
|
const wrappedResolve = pending.resolve;
|
|
7849
7789
|
const wrappedReject = pending.reject;
|
|
@@ -7856,125 +7796,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
7856
7796
|
wrappedReject(error);
|
|
7857
7797
|
};
|
|
7858
7798
|
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
7859
|
-
|
|
7860
|
-
|
|
7799
|
+
controller.registerPendingShell(pending);
|
|
7800
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
7861
7801
|
cleanup();
|
|
7862
|
-
failPendingShell(
|
|
7802
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
7863
7803
|
});
|
|
7864
7804
|
});
|
|
7865
7805
|
}
|
|
7866
7806
|
};
|
|
7867
7807
|
}
|
|
7868
|
-
|
|
7869
|
-
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
if (line === "/cancel") {
|
|
7873
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
7874
|
-
} else if (pending.method === "confirm") {
|
|
7875
|
-
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
7876
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
7877
|
-
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
7878
|
-
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
7879
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
7880
|
-
} else {
|
|
7881
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
7882
|
-
}
|
|
7883
|
-
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
7884
|
-
state.pendingUi = null;
|
|
7885
|
-
return true;
|
|
7808
|
+
|
|
7809
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
7810
|
+
function recordOf2(value) {
|
|
7811
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
7886
7812
|
}
|
|
7887
|
-
|
|
7888
|
-
|
|
7889
|
-
|
|
7890
|
-
|
|
7891
|
-
|
|
7892
|
-
|
|
7893
|
-
return;
|
|
7894
|
-
|
|
7895
|
-
|
|
7896
|
-
|
|
7897
|
-
|
|
7898
|
-
ctx.shutdown();
|
|
7899
|
-
return;
|
|
7813
|
+
function asText(value) {
|
|
7814
|
+
if (typeof value === "string")
|
|
7815
|
+
return value;
|
|
7816
|
+
if (value === null || value === undefined)
|
|
7817
|
+
return "";
|
|
7818
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
7819
|
+
return String(value);
|
|
7820
|
+
try {
|
|
7821
|
+
return JSON.stringify(value);
|
|
7822
|
+
} catch {
|
|
7823
|
+
return String(value);
|
|
7900
7824
|
}
|
|
7901
|
-
|
|
7902
|
-
|
|
7903
|
-
|
|
7904
|
-
|
|
7905
|
-
|
|
7906
|
-
|
|
7825
|
+
}
|
|
7826
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
7827
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
7828
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
7829
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
7830
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
7831
|
+
const choices = rawOptions.map((option) => {
|
|
7832
|
+
const record = recordOf2(option);
|
|
7833
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
7834
|
+
}).filter(Boolean);
|
|
7835
|
+
try {
|
|
7836
|
+
if (method === "confirm") {
|
|
7837
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
7838
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
7839
|
+
return;
|
|
7840
|
+
}
|
|
7841
|
+
if (choices.length > 0) {
|
|
7842
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
7843
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
7844
|
+
return;
|
|
7845
|
+
}
|
|
7846
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
7847
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
7848
|
+
} catch (error) {
|
|
7849
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
7907
7850
|
}
|
|
7908
|
-
|
|
7909
|
-
|
|
7910
|
-
|
|
7911
|
-
|
|
7912
|
-
|
|
7913
|
-
const
|
|
7914
|
-
const
|
|
7915
|
-
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
7851
|
+
}
|
|
7852
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
7853
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
7854
|
+
for (const command of commands) {
|
|
7855
|
+
const record = recordOf2(command);
|
|
7856
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
7857
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
7858
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
7859
|
+
continue;
|
|
7860
|
+
registered.add(name);
|
|
7861
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
7862
|
+
try {
|
|
7863
|
+
pi.registerCommand(name, {
|
|
7864
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
7865
|
+
handler: async (args) => {
|
|
7866
|
+
try {
|
|
7867
|
+
const message2 = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
7868
|
+
ctx.ui.notify(message2, "info");
|
|
7869
|
+
} catch (error) {
|
|
7870
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
7871
|
+
}
|
|
7872
|
+
}
|
|
7873
|
+
});
|
|
7874
|
+
} catch {}
|
|
7919
7875
|
}
|
|
7920
|
-
updatePiUi(ctx, state);
|
|
7921
7876
|
}
|
|
7922
7877
|
function createRigWorkerPiBridgeExtension(options) {
|
|
7923
7878
|
return (pi) => {
|
|
7924
|
-
const state = {
|
|
7925
|
-
transcript: [],
|
|
7926
|
-
status: "starting worker Pi daemon bridge",
|
|
7927
|
-
activity: "",
|
|
7928
|
-
cwd: "",
|
|
7929
|
-
model: "",
|
|
7930
|
-
commands: [],
|
|
7931
|
-
streaming: false,
|
|
7932
|
-
pendingUi: null,
|
|
7933
|
-
pendingShells: [],
|
|
7934
|
-
wsConnected: false,
|
|
7935
|
-
nativeStream: false
|
|
7936
|
-
};
|
|
7937
|
-
if (options.initialMessageSent)
|
|
7938
|
-
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
7939
7879
|
const registeredDaemonCommands = new Set;
|
|
7940
|
-
|
|
7941
|
-
|
|
7942
|
-
|
|
7943
|
-
|
|
7880
|
+
pi.registerCommand("detach", {
|
|
7881
|
+
description: "Detach from this run; the worker keeps going",
|
|
7882
|
+
handler: async (_args, ctx) => {
|
|
7883
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
7884
|
+
ctx.shutdown();
|
|
7885
|
+
}
|
|
7944
7886
|
});
|
|
7887
|
+
pi.registerCommand("stop", {
|
|
7888
|
+
description: "Stop the worker Pi run and detach",
|
|
7889
|
+
handler: async (_args, ctx) => {
|
|
7890
|
+
await options.controller.abort();
|
|
7891
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
7892
|
+
ctx.shutdown();
|
|
7893
|
+
}
|
|
7894
|
+
});
|
|
7895
|
+
pi.on("user_bash", (event) => ({
|
|
7896
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
7897
|
+
}));
|
|
7945
7898
|
pi.on("session_start", async (_event, ctx) => {
|
|
7946
|
-
|
|
7947
|
-
|
|
7948
|
-
|
|
7949
|
-
|
|
7950
|
-
|
|
7951
|
-
|
|
7952
|
-
|
|
7953
|
-
|
|
7899
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
7900
|
+
ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
|
|
7901
|
+
ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
|
|
7902
|
+
if (options.initialMessageSent)
|
|
7903
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
7904
|
+
const nativeUi = ctx.ui;
|
|
7905
|
+
options.controller.setUiHooks({
|
|
7906
|
+
onStatusText: (text2) => ctx.ui.setStatus("rig-worker-pi", text2),
|
|
7907
|
+
onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
|
|
7908
|
+
onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
|
|
7909
|
+
onError: (message2) => ctx.ui.notify(message2, "error"),
|
|
7910
|
+
onExtensionUiRequest: (request) => {
|
|
7911
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
7912
|
+
},
|
|
7913
|
+
onCatchUp: (messages, commands) => {
|
|
7914
|
+
if (nativeUi.appendSessionMessages)
|
|
7915
|
+
nativeUi.appendSessionMessages(messages);
|
|
7916
|
+
const cwd = options.controller.status.cwd;
|
|
7917
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
7918
|
+
nativeUi.setDisplayCwd(cwd);
|
|
7919
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
7954
7920
|
}
|
|
7955
|
-
if (!data.includes("\r") && !data.includes(`
|
|
7956
|
-
`))
|
|
7957
|
-
return;
|
|
7958
|
-
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
7959
|
-
const editorText = ctx.ui.getEditorText().trim();
|
|
7960
|
-
const text2 = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
7961
|
-
if (!text2)
|
|
7962
|
-
return;
|
|
7963
|
-
if (text2.startsWith("!"))
|
|
7964
|
-
return;
|
|
7965
|
-
ctx.ui.setEditorText("");
|
|
7966
|
-
routeInput(options, ctx, state, text2).catch((error) => {
|
|
7967
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
7968
|
-
updatePiUi(ctx, state);
|
|
7969
|
-
});
|
|
7970
|
-
return { consume: true };
|
|
7971
7921
|
});
|
|
7972
|
-
|
|
7973
|
-
|
|
7974
|
-
updatePiUi(ctx, state);
|
|
7922
|
+
options.controller.connect().catch((error) => {
|
|
7923
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
7975
7924
|
});
|
|
7976
7925
|
});
|
|
7977
|
-
pi.on("session_shutdown", () => {
|
|
7926
|
+
pi.on("session_shutdown", () => {
|
|
7927
|
+
options.controller.close();
|
|
7928
|
+
});
|
|
7978
7929
|
};
|
|
7979
7930
|
}
|
|
7980
7931
|
|
|
@@ -7995,43 +7946,47 @@ function setTemporaryEnv(updates) {
|
|
|
7995
7946
|
};
|
|
7996
7947
|
}
|
|
7997
7948
|
async function attachRunBundledPiFrontend(context, input) {
|
|
7998
|
-
const
|
|
7999
|
-
const cwd = join2(tempRoot, "workspace");
|
|
8000
|
-
const agentDir = join2(tempRoot, "agent");
|
|
8001
|
-
const sessionDir = join2(tempRoot, "sessions");
|
|
8002
|
-
const previousCwd = process.cwd();
|
|
7949
|
+
const tempSessionDir = mkdtempSync(join2(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
8003
7950
|
const restoreEnv = setTemporaryEnv({
|
|
8004
|
-
|
|
8005
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
8006
|
-
PI_OFFLINE: "1",
|
|
7951
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
8007
7952
|
PI_SKIP_VERSION_CHECK: "1"
|
|
8008
7953
|
});
|
|
7954
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
7955
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
7956
|
+
const services = await createAgentSessionServices({
|
|
7957
|
+
cwd,
|
|
7958
|
+
agentDir,
|
|
7959
|
+
resourceLoaderOptions: {
|
|
7960
|
+
extensionFactories: [
|
|
7961
|
+
createRigWorkerPiBridgeExtension({
|
|
7962
|
+
context,
|
|
7963
|
+
controller,
|
|
7964
|
+
runId: input.runId,
|
|
7965
|
+
initialMessageSent: input.steered === true
|
|
7966
|
+
})
|
|
7967
|
+
],
|
|
7968
|
+
noContextFiles: true
|
|
7969
|
+
}
|
|
7970
|
+
});
|
|
7971
|
+
const created = await createAgentSessionFromServices({
|
|
7972
|
+
services,
|
|
7973
|
+
sessionManager,
|
|
7974
|
+
sessionStartEvent,
|
|
7975
|
+
noTools: "all",
|
|
7976
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
7977
|
+
});
|
|
7978
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
7979
|
+
};
|
|
8009
7980
|
let detached = false;
|
|
8010
7981
|
try {
|
|
8011
|
-
await
|
|
8012
|
-
|
|
8013
|
-
await runPiMain([
|
|
8014
|
-
"--offline",
|
|
8015
|
-
"--no-session",
|
|
8016
|
-
"--no-tools",
|
|
8017
|
-
"--no-builtin-tools",
|
|
8018
|
-
"--no-skills",
|
|
8019
|
-
"--no-context-files",
|
|
8020
|
-
"--no-approve"
|
|
8021
|
-
], {
|
|
8022
|
-
extensionFactories: [
|
|
8023
|
-
createRigWorkerPiBridgeExtension({
|
|
8024
|
-
context,
|
|
8025
|
-
runId: input.runId,
|
|
8026
|
-
initialMessageSent: input.steered === true
|
|
8027
|
-
})
|
|
8028
|
-
]
|
|
7982
|
+
await runPiMain([], {
|
|
7983
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
8029
7984
|
});
|
|
8030
7985
|
detached = true;
|
|
8031
7986
|
} finally {
|
|
8032
|
-
process.chdir(previousCwd);
|
|
8033
7987
|
restoreEnv();
|
|
8034
|
-
|
|
7988
|
+
controller.close();
|
|
7989
|
+
rmSync5(tempSessionDir, { recursive: true, force: true });
|
|
8035
7990
|
}
|
|
8036
7991
|
let run = { runId: input.runId, status: "unknown" };
|
|
8037
7992
|
try {
|
|
@@ -8044,7 +7999,7 @@ async function attachRunBundledPiFrontend(context, input) {
|
|
|
8044
7999
|
timelineCursor: null,
|
|
8045
8000
|
steered: input.steered === true,
|
|
8046
8001
|
detached,
|
|
8047
|
-
rendered: "
|
|
8002
|
+
rendered: "native bundled Pi frontend with remote worker session runtime"
|
|
8048
8003
|
};
|
|
8049
8004
|
}
|
|
8050
8005
|
|