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