@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/commands.js
CHANGED
|
@@ -5966,6 +5966,7 @@ import {
|
|
|
5966
5966
|
writeJsonFile as writeJsonFile4
|
|
5967
5967
|
} from "@rig/runtime/control-plane/authority-files";
|
|
5968
5968
|
import { taskLookup } from "@rig/runtime/control-plane/native/task-ops";
|
|
5969
|
+
import { readPriorPrProgressPromptSection } from "@rig/runtime/control-plane/prompt-context";
|
|
5969
5970
|
import { buildProviderTaskRunInstructionLines } from "@rig/runtime/control-plane/provider/runtime-instructions";
|
|
5970
5971
|
import { loadRigTaskRunSkillBody } from "@rig/runtime/control-plane/provider/rig-task-run-skill";
|
|
5971
5972
|
function patchAuthorityRun(projectRoot, runId, patch) {
|
|
@@ -6112,7 +6113,7 @@ ${acceptance}` : null,
|
|
|
6112
6113
|
${sourceContractLines.join(`
|
|
6113
6114
|
`)}` : null,
|
|
6114
6115
|
scopeText || renderSourceScopeValidation(sourceTask, sourceValidation) || null,
|
|
6115
|
-
|
|
6116
|
+
readPriorPrProgressPromptSection(input.projectRoot, input.taskId),
|
|
6116
6117
|
initialPrompt ? `Additional operator guidance:
|
|
6117
6118
|
${initialPrompt}` : null,
|
|
6118
6119
|
providerLines.length > 0 ? `Provider-specific runtime tooling:
|
|
@@ -6122,26 +6123,6 @@ ${providerLines.join(" ")}` : null,
|
|
|
6122
6123
|
|
|
6123
6124
|
`);
|
|
6124
6125
|
}
|
|
6125
|
-
function readPriorPrProgressForPrompt(projectRoot, taskId) {
|
|
6126
|
-
for (const candidate of [
|
|
6127
|
-
resolve19(projectRoot, ".worktrees", taskId, "artifacts", taskId, "pr-state.json"),
|
|
6128
|
-
resolve19(projectRoot, "artifacts", taskId, "pr-state.json")
|
|
6129
|
-
]) {
|
|
6130
|
-
try {
|
|
6131
|
-
const raw = JSON.parse(readFileSync8(candidate, "utf8"));
|
|
6132
|
-
const entries = Array.isArray(raw) ? raw : [raw];
|
|
6133
|
-
const first = entries.find((entry) => entry && typeof entry === "object" && typeof entry.url === "string");
|
|
6134
|
-
if (!first)
|
|
6135
|
-
continue;
|
|
6136
|
-
return [
|
|
6137
|
-
`Prior progress exists for this task: PR ${first.url}${first.branch ? ` (branch ${first.branch})` : ""} was opened by an earlier run.`,
|
|
6138
|
-
"Check its current state first (diff, checks, review). If the work is already complete and checks are green,",
|
|
6139
|
-
"run `rig-agent completion-verification` to merge and close instead of re-implementing anything."
|
|
6140
|
-
].join(" ");
|
|
6141
|
-
} catch {}
|
|
6142
|
-
}
|
|
6143
|
-
return null;
|
|
6144
|
-
}
|
|
6145
6126
|
function firstPromptString(...values) {
|
|
6146
6127
|
for (const value of values) {
|
|
6147
6128
|
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
@@ -7208,435 +7189,400 @@ async function promptForTaskSelection(question) {
|
|
|
7208
7189
|
import { mkdtempSync, rmSync as rmSync5 } from "fs";
|
|
7209
7190
|
import { tmpdir } from "os";
|
|
7210
7191
|
import { join as join2 } from "path";
|
|
7211
|
-
import {
|
|
7192
|
+
import {
|
|
7193
|
+
createAgentSessionFromServices,
|
|
7194
|
+
createAgentSessionServices,
|
|
7195
|
+
main as runPiMain
|
|
7196
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7212
7197
|
|
|
7213
|
-
// packages/cli/src/commands/_pi-
|
|
7198
|
+
// packages/cli/src/commands/_pi-remote-session.ts
|
|
7199
|
+
import { AgentSession as PiAgentSession } from "@earendil-works/pi-coding-agent";
|
|
7214
7200
|
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
7215
|
-
|
|
7201
|
+
function defaultTransport() {
|
|
7202
|
+
return {
|
|
7203
|
+
getSession: getRunPiSessionViaServer,
|
|
7204
|
+
getMessages: getRunPiMessagesViaServer,
|
|
7205
|
+
getStatus: getRunPiStatusViaServer,
|
|
7206
|
+
getCommands: getRunPiCommandsViaServer,
|
|
7207
|
+
sendPrompt: sendRunPiPromptViaServer,
|
|
7208
|
+
sendShell: sendRunPiShellViaServer,
|
|
7209
|
+
runCommand: runRunPiCommandViaServer,
|
|
7210
|
+
abort: abortRunPiViaServer,
|
|
7211
|
+
buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
|
|
7212
|
+
};
|
|
7213
|
+
}
|
|
7216
7214
|
function recordOf(value) {
|
|
7217
7215
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
7218
7216
|
}
|
|
7219
|
-
function
|
|
7220
|
-
|
|
7221
|
-
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7228
|
-
|
|
7229
|
-
|
|
7230
|
-
|
|
7231
|
-
|
|
7232
|
-
|
|
7233
|
-
|
|
7234
|
-
return content;
|
|
7235
|
-
if (!Array.isArray(content))
|
|
7236
|
-
return asText(content);
|
|
7237
|
-
return content.flatMap((part) => {
|
|
7238
|
-
const item = recordOf(part);
|
|
7239
|
-
if (!item)
|
|
7240
|
-
return [];
|
|
7241
|
-
if (typeof item.text === "string")
|
|
7242
|
-
return [item.text];
|
|
7243
|
-
if (typeof item.content === "string")
|
|
7244
|
-
return [item.content];
|
|
7245
|
-
if (item.type === "toolCall")
|
|
7246
|
-
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
7247
|
-
if (item.type === "toolResult")
|
|
7248
|
-
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
7249
|
-
return [];
|
|
7250
|
-
}).join(`
|
|
7251
|
-
`);
|
|
7252
|
-
}
|
|
7253
|
-
function appendTranscript(state, label, text2) {
|
|
7254
|
-
const trimmed = text2.trimEnd();
|
|
7255
|
-
if (!trimmed)
|
|
7256
|
-
return;
|
|
7257
|
-
const lines = trimmed.split(/\r?\n/);
|
|
7258
|
-
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
7259
|
-
for (const line of lines.slice(1))
|
|
7260
|
-
state.transcript.push(` ${line}`);
|
|
7261
|
-
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
7262
|
-
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
7263
|
-
}
|
|
7264
|
-
}
|
|
7265
|
-
function nativePiUi(ctx) {
|
|
7266
|
-
const ui = ctx.ui;
|
|
7267
|
-
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
7268
|
-
}
|
|
7269
|
-
function syncNativeDisplayCwd(ctx, state) {
|
|
7270
|
-
const ui = nativePiUi(ctx);
|
|
7271
|
-
if (ui?.setDisplayCwd && state.cwd)
|
|
7272
|
-
ui.setDisplayCwd(state.cwd);
|
|
7273
|
-
}
|
|
7274
|
-
function parseExtensionUiRequest(value) {
|
|
7275
|
-
const request = recordOf(value) ?? {};
|
|
7276
|
-
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
7277
|
-
const method = String(request.method ?? request.type ?? "input");
|
|
7278
|
-
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
7279
|
-
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
7280
|
-
const options = rawOptions.map((option) => {
|
|
7281
|
-
const record = recordOf(option);
|
|
7282
|
-
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
7283
|
-
}).filter(Boolean);
|
|
7284
|
-
return { requestId, method, prompt, options };
|
|
7285
|
-
}
|
|
7286
|
-
function renderBridgeWidget(state) {
|
|
7287
|
-
const statusParts = [
|
|
7288
|
-
state.wsConnected ? "live" : "connecting",
|
|
7289
|
-
state.status,
|
|
7290
|
-
state.model,
|
|
7291
|
-
state.cwd
|
|
7292
|
-
].filter(Boolean);
|
|
7293
|
-
const lines = [`Rig worker session \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
7294
|
-
if (state.activity)
|
|
7295
|
-
lines.push(state.activity);
|
|
7296
|
-
if (state.commands.length > 0) {
|
|
7297
|
-
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
7298
|
-
}
|
|
7299
|
-
lines.push("");
|
|
7300
|
-
if (state.transcript.length > 0) {
|
|
7301
|
-
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
7302
|
-
} else {
|
|
7303
|
-
lines.push("Waiting for the worker session transcript\u2026 (/detach exits and leaves the worker running)");
|
|
7304
|
-
}
|
|
7305
|
-
if (state.pendingUi) {
|
|
7306
|
-
lines.push("");
|
|
7307
|
-
lines.push(`Worker needs input \xB7 ${state.pendingUi.method}`);
|
|
7308
|
-
lines.push(state.pendingUi.prompt);
|
|
7309
|
-
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
7310
|
-
lines.push("Reply in the editor below. /cancel dismisses this request.");
|
|
7311
|
-
}
|
|
7312
|
-
return lines;
|
|
7313
|
-
}
|
|
7314
|
-
function reportBridgeError(ctx, state, message2) {
|
|
7315
|
-
appendTranscript(state, "Error", message2);
|
|
7316
|
-
state.status = message2;
|
|
7317
|
-
try {
|
|
7318
|
-
ctx.ui.notify(message2, "error");
|
|
7319
|
-
} catch {}
|
|
7320
|
-
updatePiUi(ctx, state);
|
|
7321
|
-
}
|
|
7322
|
-
function updatePiUi(ctx, state) {
|
|
7323
|
-
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
7324
|
-
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker session live" : state.status);
|
|
7325
|
-
syncNativeDisplayCwd(ctx, state);
|
|
7326
|
-
if (state.nativeStream && nativePiUi(ctx)) {
|
|
7327
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
7328
|
-
return;
|
|
7329
|
-
}
|
|
7330
|
-
ctx.ui.setWorkingVisible(false);
|
|
7331
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
|
|
7332
|
-
}
|
|
7333
|
-
function applyStatus(state, payload) {
|
|
7334
|
-
const status = recordOf(payload.status) ?? payload;
|
|
7335
|
-
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
7336
|
-
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
7337
|
-
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
7338
|
-
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
7339
|
-
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
7340
|
-
}
|
|
7341
|
-
function applyMessage(state, message2) {
|
|
7342
|
-
const record = recordOf(message2);
|
|
7343
|
-
if (!record)
|
|
7344
|
-
return;
|
|
7345
|
-
const role = String(record.role ?? "system");
|
|
7346
|
-
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
7347
|
-
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
7348
|
-
}
|
|
7349
|
-
function applyPiEvent(ctx, state, eventValue) {
|
|
7350
|
-
const event = recordOf(eventValue);
|
|
7351
|
-
if (!event)
|
|
7352
|
-
return;
|
|
7353
|
-
const type = String(event.type ?? "event");
|
|
7354
|
-
if (type === "agent_start") {
|
|
7355
|
-
state.streaming = true;
|
|
7356
|
-
state.status = "streaming";
|
|
7357
|
-
} else if (type === "agent_end") {
|
|
7358
|
-
state.streaming = false;
|
|
7359
|
-
state.status = "idle";
|
|
7360
|
-
} else if (type === "queue_update") {
|
|
7361
|
-
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
7362
|
-
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
7363
|
-
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
7364
|
-
}
|
|
7365
|
-
const native = nativePiUi(ctx);
|
|
7366
|
-
if (state.nativeStream && native?.emitSessionEvent) {
|
|
7367
|
-
native.emitSessionEvent(eventValue);
|
|
7368
|
-
return;
|
|
7369
|
-
}
|
|
7370
|
-
if (type === "agent_end") {
|
|
7371
|
-
appendTranscript(state, "System", "Agent turn complete.");
|
|
7372
|
-
return;
|
|
7373
|
-
}
|
|
7374
|
-
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
7375
|
-
applyMessage(state, event.message);
|
|
7376
|
-
return;
|
|
7377
|
-
}
|
|
7378
|
-
if (type === "message_update") {
|
|
7379
|
-
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
7380
|
-
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
7381
|
-
if (delta)
|
|
7382
|
-
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
7383
|
-
return;
|
|
7384
|
-
}
|
|
7385
|
-
if (type === "tool_execution_start") {
|
|
7386
|
-
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
7387
|
-
return;
|
|
7388
|
-
}
|
|
7389
|
-
if (type === "tool_execution_update") {
|
|
7390
|
-
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
7391
|
-
return;
|
|
7392
|
-
}
|
|
7393
|
-
if (type === "tool_execution_end") {
|
|
7394
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
7395
|
-
}
|
|
7396
|
-
}
|
|
7397
|
-
function firstPendingShell(state) {
|
|
7398
|
-
return state.pendingShells[0];
|
|
7399
|
-
}
|
|
7400
|
-
function finishPendingShell(state, shell, result) {
|
|
7401
|
-
const index = state.pendingShells.indexOf(shell);
|
|
7402
|
-
if (index !== -1)
|
|
7403
|
-
state.pendingShells.splice(index, 1);
|
|
7404
|
-
shell.resolve(result);
|
|
7405
|
-
}
|
|
7406
|
-
function failPendingShell(state, shell, error) {
|
|
7407
|
-
const index = state.pendingShells.indexOf(shell);
|
|
7408
|
-
if (index !== -1)
|
|
7409
|
-
state.pendingShells.splice(index, 1);
|
|
7410
|
-
shell.reject(error);
|
|
7411
|
-
}
|
|
7412
|
-
function applyUiEvent(state, value) {
|
|
7413
|
-
const event = recordOf(value);
|
|
7414
|
-
if (!event)
|
|
7415
|
-
return;
|
|
7416
|
-
const type = String(event.type ?? "ui");
|
|
7417
|
-
if (type === "shell.chunk") {
|
|
7418
|
-
const pending = firstPendingShell(state);
|
|
7419
|
-
const chunk = asText(event.chunk);
|
|
7420
|
-
if (pending) {
|
|
7421
|
-
pending.sawChunk = true;
|
|
7422
|
-
pending.onData(Buffer.from(chunk));
|
|
7423
|
-
} else {
|
|
7424
|
-
appendTranscript(state, "Tool", chunk);
|
|
7425
|
-
}
|
|
7426
|
-
return;
|
|
7427
|
-
}
|
|
7428
|
-
if (type === "shell.end") {
|
|
7429
|
-
const pending = firstPendingShell(state);
|
|
7430
|
-
const output = asText(event.output ?? "");
|
|
7431
|
-
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
7432
|
-
if (pending) {
|
|
7433
|
-
if (output && !pending.sawChunk)
|
|
7434
|
-
pending.onData(Buffer.from(output));
|
|
7435
|
-
finishPendingShell(state, pending, { exitCode });
|
|
7436
|
-
} else {
|
|
7437
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
7438
|
-
}
|
|
7439
|
-
return;
|
|
7440
|
-
}
|
|
7441
|
-
if (type === "shell.start") {
|
|
7442
|
-
if (!firstPendingShell(state))
|
|
7443
|
-
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
7444
|
-
return;
|
|
7445
|
-
}
|
|
7446
|
-
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
7447
|
-
}
|
|
7448
|
-
function applyEnvelope(ctx, state, envelopeValue) {
|
|
7449
|
-
const envelope = recordOf(envelopeValue);
|
|
7450
|
-
if (!envelope)
|
|
7451
|
-
return;
|
|
7452
|
-
const type = String(envelope.type ?? "");
|
|
7453
|
-
if (type === "ready") {
|
|
7454
|
-
const metadata = recordOf(envelope.metadata);
|
|
7455
|
-
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
7456
|
-
state.status = "worker Pi daemon ready";
|
|
7457
|
-
if (!state.nativeStream)
|
|
7458
|
-
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
7459
|
-
} else if (type === "status.update") {
|
|
7460
|
-
applyStatus(state, envelope);
|
|
7461
|
-
} else if (type === "activity.update") {
|
|
7462
|
-
const activity = recordOf(envelope.activity);
|
|
7463
|
-
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
7464
|
-
} else if (type === "extension_ui_request") {
|
|
7465
|
-
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
7466
|
-
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
7467
|
-
} else if (type === "pi.ui_event") {
|
|
7468
|
-
applyUiEvent(state, envelope.event);
|
|
7469
|
-
} else if (type === "pi.event") {
|
|
7470
|
-
applyPiEvent(ctx, state, envelope.event);
|
|
7471
|
-
} else if (type === "error") {
|
|
7472
|
-
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
7473
|
-
}
|
|
7474
|
-
syncNativeDisplayCwd(ctx, state);
|
|
7217
|
+
function emptyRemoteStatus() {
|
|
7218
|
+
return {
|
|
7219
|
+
isStreaming: false,
|
|
7220
|
+
isCompacting: false,
|
|
7221
|
+
isBashRunning: false,
|
|
7222
|
+
pendingMessageCount: 0,
|
|
7223
|
+
steeringMessages: [],
|
|
7224
|
+
followUpMessages: [],
|
|
7225
|
+
model: null,
|
|
7226
|
+
thinkingLevel: null,
|
|
7227
|
+
sessionName: null,
|
|
7228
|
+
cwd: null,
|
|
7229
|
+
stats: null,
|
|
7230
|
+
contextUsage: null
|
|
7231
|
+
};
|
|
7475
7232
|
}
|
|
7476
7233
|
function resolveAttachReadyTimeoutMs() {
|
|
7477
7234
|
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
7478
7235
|
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
7479
7236
|
}
|
|
7480
|
-
|
|
7481
|
-
|
|
7482
|
-
|
|
7483
|
-
|
|
7484
|
-
|
|
7485
|
-
|
|
7486
|
-
|
|
7487
|
-
|
|
7488
|
-
|
|
7489
|
-
|
|
7490
|
-
|
|
7491
|
-
|
|
7492
|
-
|
|
7493
|
-
|
|
7494
|
-
|
|
7495
|
-
|
|
7496
|
-
|
|
7497
|
-
|
|
7498
|
-
|
|
7499
|
-
|
|
7500
|
-
|
|
7501
|
-
|
|
7502
|
-
|
|
7503
|
-
|
|
7504
|
-
|
|
7505
|
-
|
|
7506
|
-
|
|
7507
|
-
|
|
7508
|
-
|
|
7509
|
-
|
|
7510
|
-
|
|
7511
|
-
|
|
7512
|
-
|
|
7513
|
-
|
|
7514
|
-
|
|
7515
|
-
return false;
|
|
7516
|
-
}
|
|
7517
|
-
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
7518
|
-
continue;
|
|
7519
|
-
}
|
|
7520
|
-
const sessionRecord = recordOf(session) ?? {};
|
|
7521
|
-
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
7522
|
-
updatePiUi(ctx, state);
|
|
7523
|
-
return true;
|
|
7524
|
-
}
|
|
7525
|
-
}
|
|
7526
|
-
function parseWsPayload(message2) {
|
|
7527
|
-
if (typeof message2.data === "string")
|
|
7528
|
-
return JSON.parse(message2.data);
|
|
7529
|
-
return JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
7530
|
-
}
|
|
7531
|
-
var BRIDGE_LOCAL_COMMANDS = new Set(["detach", "quit", "q", "stop"]);
|
|
7532
|
-
function registerDaemonCommandsNatively(pi, options, ctx, state, commands, registered) {
|
|
7533
|
-
for (const command of commands) {
|
|
7534
|
-
const record = recordOf(command);
|
|
7535
|
-
const name = typeof record?.name === "string" ? record.name : "";
|
|
7536
|
-
if (!name || registered.has(name) || BRIDGE_LOCAL_COMMANDS.has(name))
|
|
7537
|
-
continue;
|
|
7538
|
-
registered.add(name);
|
|
7539
|
-
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
7540
|
-
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
7541
|
-
try {
|
|
7542
|
-
pi.registerCommand(name, {
|
|
7543
|
-
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
7544
|
-
handler: async (args) => {
|
|
7545
|
-
const text2 = `/${name}${args ? ` ${args}` : ""}`;
|
|
7546
|
-
appendTranscript(state, "You", text2);
|
|
7547
|
-
try {
|
|
7548
|
-
const result = await runRunPiCommandViaServer(options.context, options.runId, text2);
|
|
7549
|
-
const message2 = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
7550
|
-
appendTranscript(state, "System", message2);
|
|
7551
|
-
if (state.nativeStream)
|
|
7552
|
-
ctx.ui.notify(message2, "info");
|
|
7553
|
-
} catch (error) {
|
|
7554
|
-
reportBridgeError(ctx, state, error instanceof Error ? error.message : String(error));
|
|
7555
|
-
}
|
|
7556
|
-
updatePiUi(ctx, state);
|
|
7557
|
-
}
|
|
7558
|
-
});
|
|
7559
|
-
} catch {}
|
|
7560
|
-
}
|
|
7561
|
-
}
|
|
7562
|
-
async function connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands) {
|
|
7563
|
-
const ready = await waitForWorkerReady(options, ctx, state);
|
|
7564
|
-
if (!ready)
|
|
7565
|
-
return;
|
|
7566
|
-
let catchupDone = false;
|
|
7567
|
-
const buffered = [];
|
|
7568
|
-
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
7569
|
-
const socket = new WebSocket(wsUrl);
|
|
7570
|
-
const closePromise = new Promise((resolve21) => {
|
|
7237
|
+
|
|
7238
|
+
class RigRemoteSessionController {
|
|
7239
|
+
context;
|
|
7240
|
+
runId;
|
|
7241
|
+
status = emptyRemoteStatus();
|
|
7242
|
+
transport;
|
|
7243
|
+
hooks = {};
|
|
7244
|
+
session = null;
|
|
7245
|
+
socket = null;
|
|
7246
|
+
closed = false;
|
|
7247
|
+
pendingShells = [];
|
|
7248
|
+
pendingCompactions = [];
|
|
7249
|
+
constructor(input) {
|
|
7250
|
+
this.context = input.context;
|
|
7251
|
+
this.runId = input.runId;
|
|
7252
|
+
this.transport = input.transport ?? defaultTransport();
|
|
7253
|
+
}
|
|
7254
|
+
ingestEnvelope(envelopeValue) {
|
|
7255
|
+
this.applyEnvelope(envelopeValue);
|
|
7256
|
+
}
|
|
7257
|
+
bindSession(session) {
|
|
7258
|
+
this.session = session;
|
|
7259
|
+
}
|
|
7260
|
+
setUiHooks(hooks) {
|
|
7261
|
+
this.hooks = hooks;
|
|
7262
|
+
}
|
|
7263
|
+
async connect() {
|
|
7264
|
+
const ready = await this.waitForReady();
|
|
7265
|
+
if (!ready || this.closed)
|
|
7266
|
+
return;
|
|
7267
|
+
let catchupDone = false;
|
|
7268
|
+
const buffered = [];
|
|
7269
|
+
const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
|
|
7270
|
+
const socket = new WebSocket(wsUrl);
|
|
7271
|
+
this.socket = socket;
|
|
7571
7272
|
socket.onopen = () => {
|
|
7572
|
-
|
|
7573
|
-
|
|
7574
|
-
updatePiUi(ctx, state);
|
|
7273
|
+
this.hooks.onConnectionChange?.(true);
|
|
7274
|
+
this.hooks.onStatusText?.("worker session live");
|
|
7575
7275
|
};
|
|
7576
7276
|
socket.onmessage = (message2) => {
|
|
7577
7277
|
try {
|
|
7578
|
-
const payload =
|
|
7278
|
+
const payload = typeof message2.data === "string" ? JSON.parse(message2.data) : JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
7579
7279
|
if (!catchupDone)
|
|
7580
7280
|
buffered.push(payload);
|
|
7581
|
-
else
|
|
7582
|
-
applyEnvelope(
|
|
7583
|
-
updatePiUi(ctx, state);
|
|
7584
|
-
}
|
|
7281
|
+
else
|
|
7282
|
+
this.applyEnvelope(payload);
|
|
7585
7283
|
} catch (error) {
|
|
7586
|
-
|
|
7587
|
-
updatePiUi(ctx, state);
|
|
7284
|
+
this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
7588
7285
|
}
|
|
7589
7286
|
};
|
|
7590
7287
|
socket.onerror = () => socket.close();
|
|
7591
7288
|
socket.onclose = () => {
|
|
7592
|
-
|
|
7593
|
-
|
|
7594
|
-
|
|
7595
|
-
resolve21();
|
|
7289
|
+
this.hooks.onConnectionChange?.(false);
|
|
7290
|
+
if (!this.closed)
|
|
7291
|
+
this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
|
|
7596
7292
|
};
|
|
7597
|
-
|
|
7598
|
-
|
|
7599
|
-
|
|
7600
|
-
|
|
7601
|
-
|
|
7602
|
-
|
|
7603
|
-
|
|
7604
|
-
|
|
7605
|
-
|
|
7606
|
-
|
|
7607
|
-
|
|
7293
|
+
try {
|
|
7294
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
7295
|
+
this.transport.getMessages(this.context, this.runId),
|
|
7296
|
+
this.transport.getStatus(this.context, this.runId),
|
|
7297
|
+
this.transport.getCommands(this.context, this.runId)
|
|
7298
|
+
]);
|
|
7299
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
7300
|
+
this.applyStatusPayload(statusPayload);
|
|
7301
|
+
this.session?.replaceRemoteMessages(messages);
|
|
7302
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
7303
|
+
this.hooks.onCatchUp?.(messages, commands);
|
|
7304
|
+
catchupDone = true;
|
|
7305
|
+
for (const payload of buffered.splice(0))
|
|
7306
|
+
this.applyEnvelope(payload);
|
|
7307
|
+
} catch (error) {
|
|
7308
|
+
catchupDone = true;
|
|
7309
|
+
this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
7310
|
+
}
|
|
7311
|
+
}
|
|
7312
|
+
close() {
|
|
7313
|
+
this.closed = true;
|
|
7314
|
+
this.socket?.close();
|
|
7315
|
+
for (const shell of this.pendingShells.splice(0))
|
|
7316
|
+
shell.reject(new Error("Remote session closed."));
|
|
7317
|
+
for (const compaction of this.pendingCompactions.splice(0))
|
|
7318
|
+
compaction.reject(new Error("Remote session closed."));
|
|
7319
|
+
}
|
|
7320
|
+
async sendPrompt(text2, streamingBehavior) {
|
|
7321
|
+
await this.transport.sendPrompt(this.context, this.runId, text2, streamingBehavior);
|
|
7322
|
+
}
|
|
7323
|
+
async sendCommand(text2) {
|
|
7324
|
+
const result = await this.transport.runCommand(this.context, this.runId, text2);
|
|
7325
|
+
return typeof result.message === "string" ? result.message : "worker command accepted";
|
|
7326
|
+
}
|
|
7327
|
+
async sendShell(text2) {
|
|
7328
|
+
await this.transport.sendShell(this.context, this.runId, text2);
|
|
7329
|
+
}
|
|
7330
|
+
async abort() {
|
|
7331
|
+
await this.transport.abort(this.context, this.runId);
|
|
7332
|
+
}
|
|
7333
|
+
registerPendingShell(shell) {
|
|
7334
|
+
this.pendingShells.push(shell);
|
|
7335
|
+
}
|
|
7336
|
+
failPendingShell(shell, error) {
|
|
7337
|
+
const index = this.pendingShells.indexOf(shell);
|
|
7338
|
+
if (index !== -1)
|
|
7339
|
+
this.pendingShells.splice(index, 1);
|
|
7340
|
+
shell.reject(error);
|
|
7341
|
+
}
|
|
7342
|
+
registerPendingCompaction(pending) {
|
|
7343
|
+
this.pendingCompactions.push(pending);
|
|
7344
|
+
}
|
|
7345
|
+
async waitForReady() {
|
|
7346
|
+
const startedAt = Date.now();
|
|
7347
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
7348
|
+
let consecutiveFailures = 0;
|
|
7349
|
+
while (!this.closed) {
|
|
7350
|
+
let requestFailed = false;
|
|
7351
|
+
const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
|
|
7352
|
+
requestFailed = true;
|
|
7353
|
+
return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
|
|
7354
|
+
});
|
|
7355
|
+
if (session.ready !== false)
|
|
7356
|
+
return true;
|
|
7357
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
7358
|
+
const status = String(session.status ?? "starting");
|
|
7359
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
7360
|
+
this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
|
|
7361
|
+
return false;
|
|
7362
|
+
}
|
|
7363
|
+
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`);
|
|
7364
|
+
if (Date.now() >= deadline) {
|
|
7365
|
+
this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
|
|
7366
|
+
return false;
|
|
7367
|
+
}
|
|
7368
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
7369
|
+
}
|
|
7370
|
+
return false;
|
|
7371
|
+
}
|
|
7372
|
+
applyEnvelope(envelopeValue) {
|
|
7373
|
+
const envelope = recordOf(envelopeValue);
|
|
7374
|
+
if (!envelope)
|
|
7375
|
+
return;
|
|
7376
|
+
const type = String(envelope.type ?? "");
|
|
7377
|
+
if (type === "status.update") {
|
|
7378
|
+
this.applyStatusPayload(envelope);
|
|
7379
|
+
return;
|
|
7380
|
+
}
|
|
7381
|
+
if (type === "activity.update") {
|
|
7382
|
+
const activity = recordOf(envelope.activity);
|
|
7383
|
+
this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
|
|
7384
|
+
return;
|
|
7385
|
+
}
|
|
7386
|
+
if (type === "extension_ui_request") {
|
|
7387
|
+
const request = recordOf(envelope.request);
|
|
7388
|
+
if (request)
|
|
7389
|
+
this.hooks.onExtensionUiRequest?.(request);
|
|
7390
|
+
return;
|
|
7391
|
+
}
|
|
7392
|
+
if (type === "pi.ui_event") {
|
|
7393
|
+
this.applyShellUiEvent(envelope.event);
|
|
7394
|
+
return;
|
|
7395
|
+
}
|
|
7396
|
+
if (type === "pi.event") {
|
|
7397
|
+
this.session?.handleRemoteSessionEvent(envelope.event);
|
|
7398
|
+
this.settlePendingCompaction(envelope.event);
|
|
7399
|
+
return;
|
|
7400
|
+
}
|
|
7401
|
+
if (type === "error") {
|
|
7402
|
+
this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
|
|
7403
|
+
}
|
|
7404
|
+
}
|
|
7405
|
+
applyStatusPayload(payload) {
|
|
7406
|
+
const status = recordOf(payload.status) ?? payload;
|
|
7407
|
+
const next = this.status;
|
|
7408
|
+
next.isStreaming = status.isStreaming === true;
|
|
7409
|
+
next.isCompacting = status.isCompacting === true;
|
|
7410
|
+
next.isBashRunning = status.isBashRunning === true;
|
|
7411
|
+
next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
7412
|
+
next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
|
|
7413
|
+
next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
|
|
7414
|
+
next.model = recordOf(status.model) ?? next.model;
|
|
7415
|
+
next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
|
|
7416
|
+
next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
|
|
7417
|
+
next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
|
|
7418
|
+
next.stats = recordOf(status.stats) ?? next.stats;
|
|
7419
|
+
next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
|
|
7420
|
+
}
|
|
7421
|
+
applyShellUiEvent(value) {
|
|
7422
|
+
const event = recordOf(value);
|
|
7423
|
+
if (!event)
|
|
7424
|
+
return;
|
|
7425
|
+
const type = String(event.type ?? "");
|
|
7426
|
+
const pending = this.pendingShells[0];
|
|
7427
|
+
if (type === "shell.chunk" && pending) {
|
|
7428
|
+
pending.sawChunk = true;
|
|
7429
|
+
pending.onData(Buffer.from(String(event.chunk ?? "")));
|
|
7430
|
+
return;
|
|
7431
|
+
}
|
|
7432
|
+
if (type === "shell.end" && pending) {
|
|
7433
|
+
const output = String(event.output ?? "");
|
|
7434
|
+
if (output && !pending.sawChunk)
|
|
7435
|
+
pending.onData(Buffer.from(output));
|
|
7436
|
+
const index = this.pendingShells.indexOf(pending);
|
|
7437
|
+
if (index !== -1)
|
|
7438
|
+
this.pendingShells.splice(index, 1);
|
|
7439
|
+
pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
|
|
7440
|
+
}
|
|
7441
|
+
}
|
|
7442
|
+
settlePendingCompaction(eventValue) {
|
|
7443
|
+
const event = recordOf(eventValue);
|
|
7444
|
+
if (!event)
|
|
7445
|
+
return;
|
|
7446
|
+
const type = String(event.type ?? "");
|
|
7447
|
+
if (type !== "compaction_end" || this.pendingCompactions.length === 0)
|
|
7448
|
+
return;
|
|
7449
|
+
const pending = this.pendingCompactions.shift();
|
|
7450
|
+
const result = recordOf(event.result);
|
|
7451
|
+
if (result)
|
|
7452
|
+
pending.resolve(result);
|
|
7453
|
+
else if (event.aborted === true)
|
|
7454
|
+
pending.reject(new Error("Compaction aborted on the worker."));
|
|
7608
7455
|
else
|
|
7609
|
-
|
|
7610
|
-
|
|
7611
|
-
|
|
7612
|
-
|
|
7613
|
-
|
|
7614
|
-
|
|
7615
|
-
|
|
7456
|
+
pending.resolve({});
|
|
7457
|
+
}
|
|
7458
|
+
}
|
|
7459
|
+
|
|
7460
|
+
class RigRemoteAgentSession extends PiAgentSession {
|
|
7461
|
+
remote;
|
|
7462
|
+
constructor(config, remote) {
|
|
7463
|
+
super(config);
|
|
7464
|
+
this.remote = remote;
|
|
7465
|
+
remote.bindSession(this);
|
|
7466
|
+
}
|
|
7467
|
+
handleRemoteSessionEvent(eventValue) {
|
|
7468
|
+
const event = recordOf(eventValue);
|
|
7469
|
+
if (!event)
|
|
7470
|
+
return;
|
|
7471
|
+
const type = String(event.type ?? "");
|
|
7472
|
+
if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
|
|
7473
|
+
this.agent.state.messages = [...this.agent.state.messages, event.message];
|
|
7474
|
+
}
|
|
7475
|
+
this._emit(eventValue);
|
|
7476
|
+
}
|
|
7477
|
+
replaceRemoteMessages(messages) {
|
|
7478
|
+
this.agent.state.messages = messages;
|
|
7479
|
+
}
|
|
7480
|
+
async prompt(text2, options) {
|
|
7481
|
+
const trimmed = text2.trim();
|
|
7482
|
+
if (!trimmed)
|
|
7483
|
+
return;
|
|
7484
|
+
if (trimmed.startsWith("/")) {
|
|
7485
|
+
if (await this._tryExecuteExtensionCommand(trimmed))
|
|
7486
|
+
return;
|
|
7487
|
+
await this.remote.sendCommand(trimmed);
|
|
7488
|
+
return;
|
|
7489
|
+
}
|
|
7490
|
+
if (trimmed.startsWith("!")) {
|
|
7491
|
+
await this.remote.sendShell(trimmed);
|
|
7492
|
+
return;
|
|
7493
|
+
}
|
|
7494
|
+
const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
7495
|
+
options?.preflightResult?.(true);
|
|
7496
|
+
await this.remote.sendPrompt(trimmed, behavior);
|
|
7497
|
+
}
|
|
7498
|
+
async steer(text2) {
|
|
7499
|
+
const trimmed = text2.trim();
|
|
7500
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
7501
|
+
return;
|
|
7502
|
+
await this.remote.sendPrompt(trimmed, "steer");
|
|
7503
|
+
}
|
|
7504
|
+
async followUp(text2) {
|
|
7505
|
+
const trimmed = text2.trim();
|
|
7506
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
7507
|
+
return;
|
|
7508
|
+
await this.remote.sendPrompt(trimmed, "followUp");
|
|
7509
|
+
}
|
|
7510
|
+
async abort() {
|
|
7511
|
+
await this.remote.abort();
|
|
7512
|
+
}
|
|
7513
|
+
async compact(customInstructions) {
|
|
7514
|
+
const pending = new Promise((resolve21, reject) => {
|
|
7515
|
+
this.remote.registerPendingCompaction({ resolve: resolve21, reject });
|
|
7616
7516
|
});
|
|
7617
|
-
|
|
7618
|
-
|
|
7619
|
-
|
|
7620
|
-
|
|
7621
|
-
|
|
7622
|
-
|
|
7623
|
-
|
|
7624
|
-
|
|
7625
|
-
|
|
7517
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
7518
|
+
return pending;
|
|
7519
|
+
}
|
|
7520
|
+
clearQueue() {
|
|
7521
|
+
const cleared = {
|
|
7522
|
+
steering: [...this.remote.status.steeringMessages],
|
|
7523
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
7524
|
+
};
|
|
7525
|
+
this.remote.status.steeringMessages = [];
|
|
7526
|
+
this.remote.status.followUpMessages = [];
|
|
7527
|
+
this.remote.status.pendingMessageCount = 0;
|
|
7528
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
7529
|
+
return cleared;
|
|
7530
|
+
}
|
|
7531
|
+
get isStreaming() {
|
|
7532
|
+
return this.remote.status.isStreaming;
|
|
7533
|
+
}
|
|
7534
|
+
get isCompacting() {
|
|
7535
|
+
return this.remote.status.isCompacting;
|
|
7536
|
+
}
|
|
7537
|
+
get isBashRunning() {
|
|
7538
|
+
return this.remote.status.isBashRunning;
|
|
7539
|
+
}
|
|
7540
|
+
get pendingMessageCount() {
|
|
7541
|
+
return this.remote.status.pendingMessageCount;
|
|
7542
|
+
}
|
|
7543
|
+
getSteeringMessages() {
|
|
7544
|
+
return this.remote.status.steeringMessages;
|
|
7545
|
+
}
|
|
7546
|
+
getFollowUpMessages() {
|
|
7547
|
+
return this.remote.status.followUpMessages;
|
|
7548
|
+
}
|
|
7549
|
+
get model() {
|
|
7550
|
+
return this.remote.status.model ?? super.model;
|
|
7551
|
+
}
|
|
7552
|
+
async setModel(model) {
|
|
7553
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
7554
|
+
this.remote.status.model = model;
|
|
7555
|
+
}
|
|
7556
|
+
get thinkingLevel() {
|
|
7557
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
7558
|
+
}
|
|
7559
|
+
setThinkingLevel(level) {
|
|
7560
|
+
this.remote.status.thinkingLevel = level;
|
|
7561
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
7562
|
+
}
|
|
7563
|
+
get sessionName() {
|
|
7564
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
7565
|
+
}
|
|
7566
|
+
setSessionName(name) {
|
|
7567
|
+
this.remote.status.sessionName = name;
|
|
7568
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
7569
|
+
}
|
|
7570
|
+
getSessionStats() {
|
|
7571
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
7572
|
+
}
|
|
7573
|
+
getContextUsage() {
|
|
7574
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
7575
|
+
}
|
|
7576
|
+
dispose() {
|
|
7577
|
+
this.remote.close();
|
|
7578
|
+
super.dispose();
|
|
7626
7579
|
}
|
|
7627
|
-
await closePromise;
|
|
7628
7580
|
}
|
|
7629
|
-
function createRemoteBashOperations(
|
|
7581
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
7630
7582
|
return {
|
|
7631
7583
|
exec(command, _cwd, execOptions) {
|
|
7632
7584
|
return new Promise((resolve21, reject) => {
|
|
7633
|
-
const pending = {
|
|
7634
|
-
command,
|
|
7635
|
-
onData: execOptions.onData,
|
|
7636
|
-
resolve: resolve21,
|
|
7637
|
-
reject,
|
|
7638
|
-
sawChunk: false
|
|
7639
|
-
};
|
|
7585
|
+
const pending = { onData: execOptions.onData, resolve: resolve21, reject, sawChunk: false };
|
|
7640
7586
|
const cleanup = () => {
|
|
7641
7587
|
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
7642
7588
|
if (timer)
|
|
@@ -7644,12 +7590,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
7644
7590
|
};
|
|
7645
7591
|
const onAbort = () => {
|
|
7646
7592
|
cleanup();
|
|
7647
|
-
failPendingShell(
|
|
7593
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
7648
7594
|
};
|
|
7649
7595
|
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
7650
7596
|
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
7651
7597
|
cleanup();
|
|
7652
|
-
failPendingShell(
|
|
7598
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
7653
7599
|
}, timeoutMs) : null;
|
|
7654
7600
|
const wrappedResolve = pending.resolve;
|
|
7655
7601
|
const wrappedReject = pending.reject;
|
|
@@ -7662,125 +7608,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
7662
7608
|
wrappedReject(error);
|
|
7663
7609
|
};
|
|
7664
7610
|
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
7665
|
-
|
|
7666
|
-
|
|
7611
|
+
controller.registerPendingShell(pending);
|
|
7612
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
7667
7613
|
cleanup();
|
|
7668
|
-
failPendingShell(
|
|
7614
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
7669
7615
|
});
|
|
7670
7616
|
});
|
|
7671
7617
|
}
|
|
7672
7618
|
};
|
|
7673
7619
|
}
|
|
7674
|
-
|
|
7675
|
-
|
|
7676
|
-
|
|
7677
|
-
|
|
7678
|
-
if (line === "/cancel") {
|
|
7679
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
7680
|
-
} else if (pending.method === "confirm") {
|
|
7681
|
-
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
7682
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
7683
|
-
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
7684
|
-
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
7685
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
7686
|
-
} else {
|
|
7687
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
7688
|
-
}
|
|
7689
|
-
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
7690
|
-
state.pendingUi = null;
|
|
7691
|
-
return true;
|
|
7620
|
+
|
|
7621
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
7622
|
+
function recordOf2(value) {
|
|
7623
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
7692
7624
|
}
|
|
7693
|
-
|
|
7694
|
-
|
|
7695
|
-
|
|
7696
|
-
|
|
7697
|
-
|
|
7698
|
-
|
|
7699
|
-
return;
|
|
7700
|
-
|
|
7701
|
-
|
|
7702
|
-
|
|
7703
|
-
|
|
7704
|
-
ctx.shutdown();
|
|
7705
|
-
return;
|
|
7625
|
+
function asText(value) {
|
|
7626
|
+
if (typeof value === "string")
|
|
7627
|
+
return value;
|
|
7628
|
+
if (value === null || value === undefined)
|
|
7629
|
+
return "";
|
|
7630
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
7631
|
+
return String(value);
|
|
7632
|
+
try {
|
|
7633
|
+
return JSON.stringify(value);
|
|
7634
|
+
} catch {
|
|
7635
|
+
return String(value);
|
|
7706
7636
|
}
|
|
7707
|
-
|
|
7708
|
-
|
|
7709
|
-
|
|
7710
|
-
|
|
7711
|
-
|
|
7712
|
-
|
|
7637
|
+
}
|
|
7638
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
7639
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
7640
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
7641
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
7642
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
7643
|
+
const choices = rawOptions.map((option) => {
|
|
7644
|
+
const record = recordOf2(option);
|
|
7645
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
7646
|
+
}).filter(Boolean);
|
|
7647
|
+
try {
|
|
7648
|
+
if (method === "confirm") {
|
|
7649
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
7650
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
7651
|
+
return;
|
|
7652
|
+
}
|
|
7653
|
+
if (choices.length > 0) {
|
|
7654
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
7655
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
7656
|
+
return;
|
|
7657
|
+
}
|
|
7658
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
7659
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
7660
|
+
} catch (error) {
|
|
7661
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
7713
7662
|
}
|
|
7714
|
-
|
|
7715
|
-
|
|
7716
|
-
|
|
7717
|
-
|
|
7718
|
-
|
|
7719
|
-
const
|
|
7720
|
-
const
|
|
7721
|
-
|
|
7722
|
-
|
|
7723
|
-
|
|
7724
|
-
|
|
7663
|
+
}
|
|
7664
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
7665
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
7666
|
+
for (const command of commands) {
|
|
7667
|
+
const record = recordOf2(command);
|
|
7668
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
7669
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
7670
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
7671
|
+
continue;
|
|
7672
|
+
registered.add(name);
|
|
7673
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
7674
|
+
try {
|
|
7675
|
+
pi.registerCommand(name, {
|
|
7676
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
7677
|
+
handler: async (args) => {
|
|
7678
|
+
try {
|
|
7679
|
+
const message2 = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
7680
|
+
ctx.ui.notify(message2, "info");
|
|
7681
|
+
} catch (error) {
|
|
7682
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
7683
|
+
}
|
|
7684
|
+
}
|
|
7685
|
+
});
|
|
7686
|
+
} catch {}
|
|
7725
7687
|
}
|
|
7726
|
-
updatePiUi(ctx, state);
|
|
7727
7688
|
}
|
|
7728
7689
|
function createRigWorkerPiBridgeExtension(options) {
|
|
7729
7690
|
return (pi) => {
|
|
7730
|
-
const state = {
|
|
7731
|
-
transcript: [],
|
|
7732
|
-
status: "starting worker Pi daemon bridge",
|
|
7733
|
-
activity: "",
|
|
7734
|
-
cwd: "",
|
|
7735
|
-
model: "",
|
|
7736
|
-
commands: [],
|
|
7737
|
-
streaming: false,
|
|
7738
|
-
pendingUi: null,
|
|
7739
|
-
pendingShells: [],
|
|
7740
|
-
wsConnected: false,
|
|
7741
|
-
nativeStream: false
|
|
7742
|
-
};
|
|
7743
|
-
if (options.initialMessageSent)
|
|
7744
|
-
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
7745
7691
|
const registeredDaemonCommands = new Set;
|
|
7746
|
-
|
|
7747
|
-
|
|
7748
|
-
|
|
7749
|
-
|
|
7692
|
+
pi.registerCommand("detach", {
|
|
7693
|
+
description: "Detach from this run; the worker keeps going",
|
|
7694
|
+
handler: async (_args, ctx) => {
|
|
7695
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
7696
|
+
ctx.shutdown();
|
|
7697
|
+
}
|
|
7750
7698
|
});
|
|
7699
|
+
pi.registerCommand("stop", {
|
|
7700
|
+
description: "Stop the worker Pi run and detach",
|
|
7701
|
+
handler: async (_args, ctx) => {
|
|
7702
|
+
await options.controller.abort();
|
|
7703
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
7704
|
+
ctx.shutdown();
|
|
7705
|
+
}
|
|
7706
|
+
});
|
|
7707
|
+
pi.on("user_bash", (event) => ({
|
|
7708
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
7709
|
+
}));
|
|
7751
7710
|
pi.on("session_start", async (_event, ctx) => {
|
|
7752
|
-
|
|
7753
|
-
|
|
7754
|
-
|
|
7755
|
-
|
|
7756
|
-
|
|
7757
|
-
|
|
7758
|
-
|
|
7759
|
-
|
|
7711
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
7712
|
+
ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
|
|
7713
|
+
ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
|
|
7714
|
+
if (options.initialMessageSent)
|
|
7715
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
7716
|
+
const nativeUi = ctx.ui;
|
|
7717
|
+
options.controller.setUiHooks({
|
|
7718
|
+
onStatusText: (text2) => ctx.ui.setStatus("rig-worker-pi", text2),
|
|
7719
|
+
onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
|
|
7720
|
+
onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
|
|
7721
|
+
onError: (message2) => ctx.ui.notify(message2, "error"),
|
|
7722
|
+
onExtensionUiRequest: (request) => {
|
|
7723
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
7724
|
+
},
|
|
7725
|
+
onCatchUp: (messages, commands) => {
|
|
7726
|
+
if (nativeUi.appendSessionMessages)
|
|
7727
|
+
nativeUi.appendSessionMessages(messages);
|
|
7728
|
+
const cwd = options.controller.status.cwd;
|
|
7729
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
7730
|
+
nativeUi.setDisplayCwd(cwd);
|
|
7731
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
7760
7732
|
}
|
|
7761
|
-
if (!data.includes("\r") && !data.includes(`
|
|
7762
|
-
`))
|
|
7763
|
-
return;
|
|
7764
|
-
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
7765
|
-
const editorText = ctx.ui.getEditorText().trim();
|
|
7766
|
-
const text2 = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
7767
|
-
if (!text2)
|
|
7768
|
-
return;
|
|
7769
|
-
if (text2.startsWith("!"))
|
|
7770
|
-
return;
|
|
7771
|
-
ctx.ui.setEditorText("");
|
|
7772
|
-
routeInput(options, ctx, state, text2).catch((error) => {
|
|
7773
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
7774
|
-
updatePiUi(ctx, state);
|
|
7775
|
-
});
|
|
7776
|
-
return { consume: true };
|
|
7777
7733
|
});
|
|
7778
|
-
|
|
7779
|
-
|
|
7780
|
-
updatePiUi(ctx, state);
|
|
7734
|
+
options.controller.connect().catch((error) => {
|
|
7735
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
7781
7736
|
});
|
|
7782
7737
|
});
|
|
7783
|
-
pi.on("session_shutdown", () => {
|
|
7738
|
+
pi.on("session_shutdown", () => {
|
|
7739
|
+
options.controller.close();
|
|
7740
|
+
});
|
|
7784
7741
|
};
|
|
7785
7742
|
}
|
|
7786
7743
|
|
|
@@ -7801,43 +7758,47 @@ function setTemporaryEnv(updates) {
|
|
|
7801
7758
|
};
|
|
7802
7759
|
}
|
|
7803
7760
|
async function attachRunBundledPiFrontend(context, input) {
|
|
7804
|
-
const
|
|
7805
|
-
const cwd = join2(tempRoot, "workspace");
|
|
7806
|
-
const agentDir = join2(tempRoot, "agent");
|
|
7807
|
-
const sessionDir = join2(tempRoot, "sessions");
|
|
7808
|
-
const previousCwd = process.cwd();
|
|
7761
|
+
const tempSessionDir = mkdtempSync(join2(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
7809
7762
|
const restoreEnv = setTemporaryEnv({
|
|
7810
|
-
|
|
7811
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
7812
|
-
PI_OFFLINE: "1",
|
|
7763
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
7813
7764
|
PI_SKIP_VERSION_CHECK: "1"
|
|
7814
7765
|
});
|
|
7766
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
7767
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
7768
|
+
const services = await createAgentSessionServices({
|
|
7769
|
+
cwd,
|
|
7770
|
+
agentDir,
|
|
7771
|
+
resourceLoaderOptions: {
|
|
7772
|
+
extensionFactories: [
|
|
7773
|
+
createRigWorkerPiBridgeExtension({
|
|
7774
|
+
context,
|
|
7775
|
+
controller,
|
|
7776
|
+
runId: input.runId,
|
|
7777
|
+
initialMessageSent: input.steered === true
|
|
7778
|
+
})
|
|
7779
|
+
],
|
|
7780
|
+
noContextFiles: true
|
|
7781
|
+
}
|
|
7782
|
+
});
|
|
7783
|
+
const created = await createAgentSessionFromServices({
|
|
7784
|
+
services,
|
|
7785
|
+
sessionManager,
|
|
7786
|
+
sessionStartEvent,
|
|
7787
|
+
noTools: "all",
|
|
7788
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
7789
|
+
});
|
|
7790
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
7791
|
+
};
|
|
7815
7792
|
let detached = false;
|
|
7816
7793
|
try {
|
|
7817
|
-
await
|
|
7818
|
-
|
|
7819
|
-
await runPiMain([
|
|
7820
|
-
"--offline",
|
|
7821
|
-
"--no-session",
|
|
7822
|
-
"--no-tools",
|
|
7823
|
-
"--no-builtin-tools",
|
|
7824
|
-
"--no-skills",
|
|
7825
|
-
"--no-context-files",
|
|
7826
|
-
"--no-approve"
|
|
7827
|
-
], {
|
|
7828
|
-
extensionFactories: [
|
|
7829
|
-
createRigWorkerPiBridgeExtension({
|
|
7830
|
-
context,
|
|
7831
|
-
runId: input.runId,
|
|
7832
|
-
initialMessageSent: input.steered === true
|
|
7833
|
-
})
|
|
7834
|
-
]
|
|
7794
|
+
await runPiMain([], {
|
|
7795
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
7835
7796
|
});
|
|
7836
7797
|
detached = true;
|
|
7837
7798
|
} finally {
|
|
7838
|
-
process.chdir(previousCwd);
|
|
7839
7799
|
restoreEnv();
|
|
7840
|
-
|
|
7800
|
+
controller.close();
|
|
7801
|
+
rmSync5(tempSessionDir, { recursive: true, force: true });
|
|
7841
7802
|
}
|
|
7842
7803
|
let run = { runId: input.runId, status: "unknown" };
|
|
7843
7804
|
try {
|
|
@@ -7850,7 +7811,7 @@ async function attachRunBundledPiFrontend(context, input) {
|
|
|
7850
7811
|
timelineCursor: null,
|
|
7851
7812
|
steered: input.steered === true,
|
|
7852
7813
|
detached,
|
|
7853
|
-
rendered: "
|
|
7814
|
+
rendered: "native bundled Pi frontend with remote worker session runtime"
|
|
7854
7815
|
};
|
|
7855
7816
|
}
|
|
7856
7817
|
|