@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
|
@@ -963,435 +963,400 @@ async function selectTaskWithTextPicker(tasks, io = {}) {
|
|
|
963
963
|
import { mkdtempSync, rmSync } from "fs";
|
|
964
964
|
import { tmpdir } from "os";
|
|
965
965
|
import { join } from "path";
|
|
966
|
-
import {
|
|
966
|
+
import {
|
|
967
|
+
createAgentSessionFromServices,
|
|
968
|
+
createAgentSessionServices,
|
|
969
|
+
main as runPiMain
|
|
970
|
+
} from "@earendil-works/pi-coding-agent";
|
|
967
971
|
|
|
968
|
-
// packages/cli/src/commands/_pi-
|
|
972
|
+
// packages/cli/src/commands/_pi-remote-session.ts
|
|
973
|
+
import { AgentSession as PiAgentSession } from "@earendil-works/pi-coding-agent";
|
|
969
974
|
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
970
|
-
|
|
975
|
+
function defaultTransport() {
|
|
976
|
+
return {
|
|
977
|
+
getSession: getRunPiSessionViaServer,
|
|
978
|
+
getMessages: getRunPiMessagesViaServer,
|
|
979
|
+
getStatus: getRunPiStatusViaServer,
|
|
980
|
+
getCommands: getRunPiCommandsViaServer,
|
|
981
|
+
sendPrompt: sendRunPiPromptViaServer,
|
|
982
|
+
sendShell: sendRunPiShellViaServer,
|
|
983
|
+
runCommand: runRunPiCommandViaServer,
|
|
984
|
+
abort: abortRunPiViaServer,
|
|
985
|
+
buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
|
|
986
|
+
};
|
|
987
|
+
}
|
|
971
988
|
function recordOf(value) {
|
|
972
989
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
973
990
|
}
|
|
974
|
-
function
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
return content;
|
|
990
|
-
if (!Array.isArray(content))
|
|
991
|
-
return asText(content);
|
|
992
|
-
return content.flatMap((part) => {
|
|
993
|
-
const item = recordOf(part);
|
|
994
|
-
if (!item)
|
|
995
|
-
return [];
|
|
996
|
-
if (typeof item.text === "string")
|
|
997
|
-
return [item.text];
|
|
998
|
-
if (typeof item.content === "string")
|
|
999
|
-
return [item.content];
|
|
1000
|
-
if (item.type === "toolCall")
|
|
1001
|
-
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
1002
|
-
if (item.type === "toolResult")
|
|
1003
|
-
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
1004
|
-
return [];
|
|
1005
|
-
}).join(`
|
|
1006
|
-
`);
|
|
1007
|
-
}
|
|
1008
|
-
function appendTranscript(state, label, text) {
|
|
1009
|
-
const trimmed = text.trimEnd();
|
|
1010
|
-
if (!trimmed)
|
|
1011
|
-
return;
|
|
1012
|
-
const lines = trimmed.split(/\r?\n/);
|
|
1013
|
-
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
1014
|
-
for (const line of lines.slice(1))
|
|
1015
|
-
state.transcript.push(` ${line}`);
|
|
1016
|
-
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
1017
|
-
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
function nativePiUi(ctx) {
|
|
1021
|
-
const ui = ctx.ui;
|
|
1022
|
-
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
1023
|
-
}
|
|
1024
|
-
function syncNativeDisplayCwd(ctx, state) {
|
|
1025
|
-
const ui = nativePiUi(ctx);
|
|
1026
|
-
if (ui?.setDisplayCwd && state.cwd)
|
|
1027
|
-
ui.setDisplayCwd(state.cwd);
|
|
1028
|
-
}
|
|
1029
|
-
function parseExtensionUiRequest(value) {
|
|
1030
|
-
const request = recordOf(value) ?? {};
|
|
1031
|
-
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
1032
|
-
const method = String(request.method ?? request.type ?? "input");
|
|
1033
|
-
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
1034
|
-
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
1035
|
-
const options = rawOptions.map((option) => {
|
|
1036
|
-
const record = recordOf(option);
|
|
1037
|
-
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
1038
|
-
}).filter(Boolean);
|
|
1039
|
-
return { requestId, method, prompt, options };
|
|
1040
|
-
}
|
|
1041
|
-
function renderBridgeWidget(state) {
|
|
1042
|
-
const statusParts = [
|
|
1043
|
-
state.wsConnected ? "live" : "connecting",
|
|
1044
|
-
state.status,
|
|
1045
|
-
state.model,
|
|
1046
|
-
state.cwd
|
|
1047
|
-
].filter(Boolean);
|
|
1048
|
-
const lines = [`Rig worker session \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
1049
|
-
if (state.activity)
|
|
1050
|
-
lines.push(state.activity);
|
|
1051
|
-
if (state.commands.length > 0) {
|
|
1052
|
-
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
1053
|
-
}
|
|
1054
|
-
lines.push("");
|
|
1055
|
-
if (state.transcript.length > 0) {
|
|
1056
|
-
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
1057
|
-
} else {
|
|
1058
|
-
lines.push("Waiting for the worker session transcript\u2026 (/detach exits and leaves the worker running)");
|
|
1059
|
-
}
|
|
1060
|
-
if (state.pendingUi) {
|
|
1061
|
-
lines.push("");
|
|
1062
|
-
lines.push(`Worker needs input \xB7 ${state.pendingUi.method}`);
|
|
1063
|
-
lines.push(state.pendingUi.prompt);
|
|
1064
|
-
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
1065
|
-
lines.push("Reply in the editor below. /cancel dismisses this request.");
|
|
1066
|
-
}
|
|
1067
|
-
return lines;
|
|
1068
|
-
}
|
|
1069
|
-
function reportBridgeError(ctx, state, message2) {
|
|
1070
|
-
appendTranscript(state, "Error", message2);
|
|
1071
|
-
state.status = message2;
|
|
1072
|
-
try {
|
|
1073
|
-
ctx.ui.notify(message2, "error");
|
|
1074
|
-
} catch {}
|
|
1075
|
-
updatePiUi(ctx, state);
|
|
1076
|
-
}
|
|
1077
|
-
function updatePiUi(ctx, state) {
|
|
1078
|
-
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
1079
|
-
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker session live" : state.status);
|
|
1080
|
-
syncNativeDisplayCwd(ctx, state);
|
|
1081
|
-
if (state.nativeStream && nativePiUi(ctx)) {
|
|
1082
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
1083
|
-
return;
|
|
1084
|
-
}
|
|
1085
|
-
ctx.ui.setWorkingVisible(false);
|
|
1086
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
|
|
1087
|
-
}
|
|
1088
|
-
function applyStatus(state, payload) {
|
|
1089
|
-
const status = recordOf(payload.status) ?? payload;
|
|
1090
|
-
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
1091
|
-
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
1092
|
-
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
1093
|
-
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
1094
|
-
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
1095
|
-
}
|
|
1096
|
-
function applyMessage(state, message2) {
|
|
1097
|
-
const record = recordOf(message2);
|
|
1098
|
-
if (!record)
|
|
1099
|
-
return;
|
|
1100
|
-
const role = String(record.role ?? "system");
|
|
1101
|
-
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
1102
|
-
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
1103
|
-
}
|
|
1104
|
-
function applyPiEvent(ctx, state, eventValue) {
|
|
1105
|
-
const event = recordOf(eventValue);
|
|
1106
|
-
if (!event)
|
|
1107
|
-
return;
|
|
1108
|
-
const type = String(event.type ?? "event");
|
|
1109
|
-
if (type === "agent_start") {
|
|
1110
|
-
state.streaming = true;
|
|
1111
|
-
state.status = "streaming";
|
|
1112
|
-
} else if (type === "agent_end") {
|
|
1113
|
-
state.streaming = false;
|
|
1114
|
-
state.status = "idle";
|
|
1115
|
-
} else if (type === "queue_update") {
|
|
1116
|
-
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
1117
|
-
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
1118
|
-
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
1119
|
-
}
|
|
1120
|
-
const native = nativePiUi(ctx);
|
|
1121
|
-
if (state.nativeStream && native?.emitSessionEvent) {
|
|
1122
|
-
native.emitSessionEvent(eventValue);
|
|
1123
|
-
return;
|
|
1124
|
-
}
|
|
1125
|
-
if (type === "agent_end") {
|
|
1126
|
-
appendTranscript(state, "System", "Agent turn complete.");
|
|
1127
|
-
return;
|
|
1128
|
-
}
|
|
1129
|
-
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
1130
|
-
applyMessage(state, event.message);
|
|
1131
|
-
return;
|
|
1132
|
-
}
|
|
1133
|
-
if (type === "message_update") {
|
|
1134
|
-
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
1135
|
-
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
1136
|
-
if (delta)
|
|
1137
|
-
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
1138
|
-
return;
|
|
1139
|
-
}
|
|
1140
|
-
if (type === "tool_execution_start") {
|
|
1141
|
-
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
1142
|
-
return;
|
|
1143
|
-
}
|
|
1144
|
-
if (type === "tool_execution_update") {
|
|
1145
|
-
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
1146
|
-
return;
|
|
1147
|
-
}
|
|
1148
|
-
if (type === "tool_execution_end") {
|
|
1149
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
1150
|
-
}
|
|
1151
|
-
}
|
|
1152
|
-
function firstPendingShell(state) {
|
|
1153
|
-
return state.pendingShells[0];
|
|
1154
|
-
}
|
|
1155
|
-
function finishPendingShell(state, shell, result) {
|
|
1156
|
-
const index = state.pendingShells.indexOf(shell);
|
|
1157
|
-
if (index !== -1)
|
|
1158
|
-
state.pendingShells.splice(index, 1);
|
|
1159
|
-
shell.resolve(result);
|
|
1160
|
-
}
|
|
1161
|
-
function failPendingShell(state, shell, error) {
|
|
1162
|
-
const index = state.pendingShells.indexOf(shell);
|
|
1163
|
-
if (index !== -1)
|
|
1164
|
-
state.pendingShells.splice(index, 1);
|
|
1165
|
-
shell.reject(error);
|
|
1166
|
-
}
|
|
1167
|
-
function applyUiEvent(state, value) {
|
|
1168
|
-
const event = recordOf(value);
|
|
1169
|
-
if (!event)
|
|
1170
|
-
return;
|
|
1171
|
-
const type = String(event.type ?? "ui");
|
|
1172
|
-
if (type === "shell.chunk") {
|
|
1173
|
-
const pending = firstPendingShell(state);
|
|
1174
|
-
const chunk = asText(event.chunk);
|
|
1175
|
-
if (pending) {
|
|
1176
|
-
pending.sawChunk = true;
|
|
1177
|
-
pending.onData(Buffer.from(chunk));
|
|
1178
|
-
} else {
|
|
1179
|
-
appendTranscript(state, "Tool", chunk);
|
|
1180
|
-
}
|
|
1181
|
-
return;
|
|
1182
|
-
}
|
|
1183
|
-
if (type === "shell.end") {
|
|
1184
|
-
const pending = firstPendingShell(state);
|
|
1185
|
-
const output = asText(event.output ?? "");
|
|
1186
|
-
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
1187
|
-
if (pending) {
|
|
1188
|
-
if (output && !pending.sawChunk)
|
|
1189
|
-
pending.onData(Buffer.from(output));
|
|
1190
|
-
finishPendingShell(state, pending, { exitCode });
|
|
1191
|
-
} else {
|
|
1192
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
1193
|
-
}
|
|
1194
|
-
return;
|
|
1195
|
-
}
|
|
1196
|
-
if (type === "shell.start") {
|
|
1197
|
-
if (!firstPendingShell(state))
|
|
1198
|
-
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
1199
|
-
return;
|
|
1200
|
-
}
|
|
1201
|
-
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
1202
|
-
}
|
|
1203
|
-
function applyEnvelope(ctx, state, envelopeValue) {
|
|
1204
|
-
const envelope = recordOf(envelopeValue);
|
|
1205
|
-
if (!envelope)
|
|
1206
|
-
return;
|
|
1207
|
-
const type = String(envelope.type ?? "");
|
|
1208
|
-
if (type === "ready") {
|
|
1209
|
-
const metadata = recordOf(envelope.metadata);
|
|
1210
|
-
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
1211
|
-
state.status = "worker Pi daemon ready";
|
|
1212
|
-
if (!state.nativeStream)
|
|
1213
|
-
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
1214
|
-
} else if (type === "status.update") {
|
|
1215
|
-
applyStatus(state, envelope);
|
|
1216
|
-
} else if (type === "activity.update") {
|
|
1217
|
-
const activity = recordOf(envelope.activity);
|
|
1218
|
-
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
1219
|
-
} else if (type === "extension_ui_request") {
|
|
1220
|
-
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
1221
|
-
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
1222
|
-
} else if (type === "pi.ui_event") {
|
|
1223
|
-
applyUiEvent(state, envelope.event);
|
|
1224
|
-
} else if (type === "pi.event") {
|
|
1225
|
-
applyPiEvent(ctx, state, envelope.event);
|
|
1226
|
-
} else if (type === "error") {
|
|
1227
|
-
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
1228
|
-
}
|
|
1229
|
-
syncNativeDisplayCwd(ctx, state);
|
|
991
|
+
function emptyRemoteStatus() {
|
|
992
|
+
return {
|
|
993
|
+
isStreaming: false,
|
|
994
|
+
isCompacting: false,
|
|
995
|
+
isBashRunning: false,
|
|
996
|
+
pendingMessageCount: 0,
|
|
997
|
+
steeringMessages: [],
|
|
998
|
+
followUpMessages: [],
|
|
999
|
+
model: null,
|
|
1000
|
+
thinkingLevel: null,
|
|
1001
|
+
sessionName: null,
|
|
1002
|
+
cwd: null,
|
|
1003
|
+
stats: null,
|
|
1004
|
+
contextUsage: null
|
|
1005
|
+
};
|
|
1230
1006
|
}
|
|
1231
1007
|
function resolveAttachReadyTimeoutMs() {
|
|
1232
1008
|
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
1233
1009
|
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
1234
1010
|
}
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
return false;
|
|
1271
|
-
}
|
|
1272
|
-
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
1273
|
-
continue;
|
|
1274
|
-
}
|
|
1275
|
-
const sessionRecord = recordOf(session) ?? {};
|
|
1276
|
-
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
1277
|
-
updatePiUi(ctx, state);
|
|
1278
|
-
return true;
|
|
1279
|
-
}
|
|
1280
|
-
}
|
|
1281
|
-
function parseWsPayload(message2) {
|
|
1282
|
-
if (typeof message2.data === "string")
|
|
1283
|
-
return JSON.parse(message2.data);
|
|
1284
|
-
return JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
1285
|
-
}
|
|
1286
|
-
var BRIDGE_LOCAL_COMMANDS = new Set(["detach", "quit", "q", "stop"]);
|
|
1287
|
-
function registerDaemonCommandsNatively(pi, options, ctx, state, commands, registered) {
|
|
1288
|
-
for (const command of commands) {
|
|
1289
|
-
const record = recordOf(command);
|
|
1290
|
-
const name = typeof record?.name === "string" ? record.name : "";
|
|
1291
|
-
if (!name || registered.has(name) || BRIDGE_LOCAL_COMMANDS.has(name))
|
|
1292
|
-
continue;
|
|
1293
|
-
registered.add(name);
|
|
1294
|
-
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
1295
|
-
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
1296
|
-
try {
|
|
1297
|
-
pi.registerCommand(name, {
|
|
1298
|
-
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
1299
|
-
handler: async (args) => {
|
|
1300
|
-
const text = `/${name}${args ? ` ${args}` : ""}`;
|
|
1301
|
-
appendTranscript(state, "You", text);
|
|
1302
|
-
try {
|
|
1303
|
-
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
1304
|
-
const message2 = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
1305
|
-
appendTranscript(state, "System", message2);
|
|
1306
|
-
if (state.nativeStream)
|
|
1307
|
-
ctx.ui.notify(message2, "info");
|
|
1308
|
-
} catch (error) {
|
|
1309
|
-
reportBridgeError(ctx, state, error instanceof Error ? error.message : String(error));
|
|
1310
|
-
}
|
|
1311
|
-
updatePiUi(ctx, state);
|
|
1312
|
-
}
|
|
1313
|
-
});
|
|
1314
|
-
} catch {}
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
async function connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands) {
|
|
1318
|
-
const ready = await waitForWorkerReady(options, ctx, state);
|
|
1319
|
-
if (!ready)
|
|
1320
|
-
return;
|
|
1321
|
-
let catchupDone = false;
|
|
1322
|
-
const buffered = [];
|
|
1323
|
-
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
1324
|
-
const socket = new WebSocket(wsUrl);
|
|
1325
|
-
const closePromise = new Promise((resolve3) => {
|
|
1011
|
+
|
|
1012
|
+
class RigRemoteSessionController {
|
|
1013
|
+
context;
|
|
1014
|
+
runId;
|
|
1015
|
+
status = emptyRemoteStatus();
|
|
1016
|
+
transport;
|
|
1017
|
+
hooks = {};
|
|
1018
|
+
session = null;
|
|
1019
|
+
socket = null;
|
|
1020
|
+
closed = false;
|
|
1021
|
+
pendingShells = [];
|
|
1022
|
+
pendingCompactions = [];
|
|
1023
|
+
constructor(input) {
|
|
1024
|
+
this.context = input.context;
|
|
1025
|
+
this.runId = input.runId;
|
|
1026
|
+
this.transport = input.transport ?? defaultTransport();
|
|
1027
|
+
}
|
|
1028
|
+
ingestEnvelope(envelopeValue) {
|
|
1029
|
+
this.applyEnvelope(envelopeValue);
|
|
1030
|
+
}
|
|
1031
|
+
bindSession(session) {
|
|
1032
|
+
this.session = session;
|
|
1033
|
+
}
|
|
1034
|
+
setUiHooks(hooks) {
|
|
1035
|
+
this.hooks = hooks;
|
|
1036
|
+
}
|
|
1037
|
+
async connect() {
|
|
1038
|
+
const ready = await this.waitForReady();
|
|
1039
|
+
if (!ready || this.closed)
|
|
1040
|
+
return;
|
|
1041
|
+
let catchupDone = false;
|
|
1042
|
+
const buffered = [];
|
|
1043
|
+
const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
|
|
1044
|
+
const socket = new WebSocket(wsUrl);
|
|
1045
|
+
this.socket = socket;
|
|
1326
1046
|
socket.onopen = () => {
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
updatePiUi(ctx, state);
|
|
1047
|
+
this.hooks.onConnectionChange?.(true);
|
|
1048
|
+
this.hooks.onStatusText?.("worker session live");
|
|
1330
1049
|
};
|
|
1331
1050
|
socket.onmessage = (message2) => {
|
|
1332
1051
|
try {
|
|
1333
|
-
const payload =
|
|
1052
|
+
const payload = typeof message2.data === "string" ? JSON.parse(message2.data) : JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
1334
1053
|
if (!catchupDone)
|
|
1335
1054
|
buffered.push(payload);
|
|
1336
|
-
else
|
|
1337
|
-
applyEnvelope(
|
|
1338
|
-
updatePiUi(ctx, state);
|
|
1339
|
-
}
|
|
1055
|
+
else
|
|
1056
|
+
this.applyEnvelope(payload);
|
|
1340
1057
|
} catch (error) {
|
|
1341
|
-
|
|
1342
|
-
updatePiUi(ctx, state);
|
|
1058
|
+
this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
1343
1059
|
}
|
|
1344
1060
|
};
|
|
1345
1061
|
socket.onerror = () => socket.close();
|
|
1346
1062
|
socket.onclose = () => {
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
resolve3();
|
|
1063
|
+
this.hooks.onConnectionChange?.(false);
|
|
1064
|
+
if (!this.closed)
|
|
1065
|
+
this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
|
|
1351
1066
|
};
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1067
|
+
try {
|
|
1068
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
1069
|
+
this.transport.getMessages(this.context, this.runId),
|
|
1070
|
+
this.transport.getStatus(this.context, this.runId),
|
|
1071
|
+
this.transport.getCommands(this.context, this.runId)
|
|
1072
|
+
]);
|
|
1073
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
1074
|
+
this.applyStatusPayload(statusPayload);
|
|
1075
|
+
this.session?.replaceRemoteMessages(messages);
|
|
1076
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
1077
|
+
this.hooks.onCatchUp?.(messages, commands);
|
|
1078
|
+
catchupDone = true;
|
|
1079
|
+
for (const payload of buffered.splice(0))
|
|
1080
|
+
this.applyEnvelope(payload);
|
|
1081
|
+
} catch (error) {
|
|
1082
|
+
catchupDone = true;
|
|
1083
|
+
this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
close() {
|
|
1087
|
+
this.closed = true;
|
|
1088
|
+
this.socket?.close();
|
|
1089
|
+
for (const shell of this.pendingShells.splice(0))
|
|
1090
|
+
shell.reject(new Error("Remote session closed."));
|
|
1091
|
+
for (const compaction of this.pendingCompactions.splice(0))
|
|
1092
|
+
compaction.reject(new Error("Remote session closed."));
|
|
1093
|
+
}
|
|
1094
|
+
async sendPrompt(text, streamingBehavior) {
|
|
1095
|
+
await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
|
|
1096
|
+
}
|
|
1097
|
+
async sendCommand(text) {
|
|
1098
|
+
const result = await this.transport.runCommand(this.context, this.runId, text);
|
|
1099
|
+
return typeof result.message === "string" ? result.message : "worker command accepted";
|
|
1100
|
+
}
|
|
1101
|
+
async sendShell(text) {
|
|
1102
|
+
await this.transport.sendShell(this.context, this.runId, text);
|
|
1103
|
+
}
|
|
1104
|
+
async abort() {
|
|
1105
|
+
await this.transport.abort(this.context, this.runId);
|
|
1106
|
+
}
|
|
1107
|
+
registerPendingShell(shell) {
|
|
1108
|
+
this.pendingShells.push(shell);
|
|
1109
|
+
}
|
|
1110
|
+
failPendingShell(shell, error) {
|
|
1111
|
+
const index = this.pendingShells.indexOf(shell);
|
|
1112
|
+
if (index !== -1)
|
|
1113
|
+
this.pendingShells.splice(index, 1);
|
|
1114
|
+
shell.reject(error);
|
|
1115
|
+
}
|
|
1116
|
+
registerPendingCompaction(pending) {
|
|
1117
|
+
this.pendingCompactions.push(pending);
|
|
1118
|
+
}
|
|
1119
|
+
async waitForReady() {
|
|
1120
|
+
const startedAt = Date.now();
|
|
1121
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
1122
|
+
let consecutiveFailures = 0;
|
|
1123
|
+
while (!this.closed) {
|
|
1124
|
+
let requestFailed = false;
|
|
1125
|
+
const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
|
|
1126
|
+
requestFailed = true;
|
|
1127
|
+
return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
|
|
1128
|
+
});
|
|
1129
|
+
if (session.ready !== false)
|
|
1130
|
+
return true;
|
|
1131
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
1132
|
+
const status = String(session.status ?? "starting");
|
|
1133
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
1134
|
+
this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
|
|
1135
|
+
return false;
|
|
1136
|
+
}
|
|
1137
|
+
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`);
|
|
1138
|
+
if (Date.now() >= deadline) {
|
|
1139
|
+
this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
|
|
1140
|
+
return false;
|
|
1141
|
+
}
|
|
1142
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
1143
|
+
}
|
|
1144
|
+
return false;
|
|
1145
|
+
}
|
|
1146
|
+
applyEnvelope(envelopeValue) {
|
|
1147
|
+
const envelope = recordOf(envelopeValue);
|
|
1148
|
+
if (!envelope)
|
|
1149
|
+
return;
|
|
1150
|
+
const type = String(envelope.type ?? "");
|
|
1151
|
+
if (type === "status.update") {
|
|
1152
|
+
this.applyStatusPayload(envelope);
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
if (type === "activity.update") {
|
|
1156
|
+
const activity = recordOf(envelope.activity);
|
|
1157
|
+
this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
if (type === "extension_ui_request") {
|
|
1161
|
+
const request = recordOf(envelope.request);
|
|
1162
|
+
if (request)
|
|
1163
|
+
this.hooks.onExtensionUiRequest?.(request);
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
if (type === "pi.ui_event") {
|
|
1167
|
+
this.applyShellUiEvent(envelope.event);
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
if (type === "pi.event") {
|
|
1171
|
+
this.session?.handleRemoteSessionEvent(envelope.event);
|
|
1172
|
+
this.settlePendingCompaction(envelope.event);
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
if (type === "error") {
|
|
1176
|
+
this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
applyStatusPayload(payload) {
|
|
1180
|
+
const status = recordOf(payload.status) ?? payload;
|
|
1181
|
+
const next = this.status;
|
|
1182
|
+
next.isStreaming = status.isStreaming === true;
|
|
1183
|
+
next.isCompacting = status.isCompacting === true;
|
|
1184
|
+
next.isBashRunning = status.isBashRunning === true;
|
|
1185
|
+
next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
1186
|
+
next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
|
|
1187
|
+
next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
|
|
1188
|
+
next.model = recordOf(status.model) ?? next.model;
|
|
1189
|
+
next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
|
|
1190
|
+
next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
|
|
1191
|
+
next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
|
|
1192
|
+
next.stats = recordOf(status.stats) ?? next.stats;
|
|
1193
|
+
next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
|
|
1194
|
+
}
|
|
1195
|
+
applyShellUiEvent(value) {
|
|
1196
|
+
const event = recordOf(value);
|
|
1197
|
+
if (!event)
|
|
1198
|
+
return;
|
|
1199
|
+
const type = String(event.type ?? "");
|
|
1200
|
+
const pending = this.pendingShells[0];
|
|
1201
|
+
if (type === "shell.chunk" && pending) {
|
|
1202
|
+
pending.sawChunk = true;
|
|
1203
|
+
pending.onData(Buffer.from(String(event.chunk ?? "")));
|
|
1204
|
+
return;
|
|
1205
|
+
}
|
|
1206
|
+
if (type === "shell.end" && pending) {
|
|
1207
|
+
const output = String(event.output ?? "");
|
|
1208
|
+
if (output && !pending.sawChunk)
|
|
1209
|
+
pending.onData(Buffer.from(output));
|
|
1210
|
+
const index = this.pendingShells.indexOf(pending);
|
|
1211
|
+
if (index !== -1)
|
|
1212
|
+
this.pendingShells.splice(index, 1);
|
|
1213
|
+
pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
settlePendingCompaction(eventValue) {
|
|
1217
|
+
const event = recordOf(eventValue);
|
|
1218
|
+
if (!event)
|
|
1219
|
+
return;
|
|
1220
|
+
const type = String(event.type ?? "");
|
|
1221
|
+
if (type !== "compaction_end" || this.pendingCompactions.length === 0)
|
|
1222
|
+
return;
|
|
1223
|
+
const pending = this.pendingCompactions.shift();
|
|
1224
|
+
const result = recordOf(event.result);
|
|
1225
|
+
if (result)
|
|
1226
|
+
pending.resolve(result);
|
|
1227
|
+
else if (event.aborted === true)
|
|
1228
|
+
pending.reject(new Error("Compaction aborted on the worker."));
|
|
1363
1229
|
else
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1230
|
+
pending.resolve({});
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
class RigRemoteAgentSession extends PiAgentSession {
|
|
1235
|
+
remote;
|
|
1236
|
+
constructor(config, remote) {
|
|
1237
|
+
super(config);
|
|
1238
|
+
this.remote = remote;
|
|
1239
|
+
remote.bindSession(this);
|
|
1240
|
+
}
|
|
1241
|
+
handleRemoteSessionEvent(eventValue) {
|
|
1242
|
+
const event = recordOf(eventValue);
|
|
1243
|
+
if (!event)
|
|
1244
|
+
return;
|
|
1245
|
+
const type = String(event.type ?? "");
|
|
1246
|
+
if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
|
|
1247
|
+
this.agent.state.messages = [...this.agent.state.messages, event.message];
|
|
1248
|
+
}
|
|
1249
|
+
this._emit(eventValue);
|
|
1250
|
+
}
|
|
1251
|
+
replaceRemoteMessages(messages) {
|
|
1252
|
+
this.agent.state.messages = messages;
|
|
1253
|
+
}
|
|
1254
|
+
async prompt(text, options) {
|
|
1255
|
+
const trimmed = text.trim();
|
|
1256
|
+
if (!trimmed)
|
|
1257
|
+
return;
|
|
1258
|
+
if (trimmed.startsWith("/")) {
|
|
1259
|
+
if (await this._tryExecuteExtensionCommand(trimmed))
|
|
1260
|
+
return;
|
|
1261
|
+
await this.remote.sendCommand(trimmed);
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
if (trimmed.startsWith("!")) {
|
|
1265
|
+
await this.remote.sendShell(trimmed);
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1268
|
+
const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
1269
|
+
options?.preflightResult?.(true);
|
|
1270
|
+
await this.remote.sendPrompt(trimmed, behavior);
|
|
1271
|
+
}
|
|
1272
|
+
async steer(text) {
|
|
1273
|
+
const trimmed = text.trim();
|
|
1274
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
1275
|
+
return;
|
|
1276
|
+
await this.remote.sendPrompt(trimmed, "steer");
|
|
1277
|
+
}
|
|
1278
|
+
async followUp(text) {
|
|
1279
|
+
const trimmed = text.trim();
|
|
1280
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
1281
|
+
return;
|
|
1282
|
+
await this.remote.sendPrompt(trimmed, "followUp");
|
|
1283
|
+
}
|
|
1284
|
+
async abort() {
|
|
1285
|
+
await this.remote.abort();
|
|
1286
|
+
}
|
|
1287
|
+
async compact(customInstructions) {
|
|
1288
|
+
const pending = new Promise((resolve3, reject) => {
|
|
1289
|
+
this.remote.registerPendingCompaction({ resolve: resolve3, reject });
|
|
1371
1290
|
});
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1291
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
1292
|
+
return pending;
|
|
1293
|
+
}
|
|
1294
|
+
clearQueue() {
|
|
1295
|
+
const cleared = {
|
|
1296
|
+
steering: [...this.remote.status.steeringMessages],
|
|
1297
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
1298
|
+
};
|
|
1299
|
+
this.remote.status.steeringMessages = [];
|
|
1300
|
+
this.remote.status.followUpMessages = [];
|
|
1301
|
+
this.remote.status.pendingMessageCount = 0;
|
|
1302
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
1303
|
+
return cleared;
|
|
1304
|
+
}
|
|
1305
|
+
get isStreaming() {
|
|
1306
|
+
return this.remote.status.isStreaming;
|
|
1307
|
+
}
|
|
1308
|
+
get isCompacting() {
|
|
1309
|
+
return this.remote.status.isCompacting;
|
|
1310
|
+
}
|
|
1311
|
+
get isBashRunning() {
|
|
1312
|
+
return this.remote.status.isBashRunning;
|
|
1313
|
+
}
|
|
1314
|
+
get pendingMessageCount() {
|
|
1315
|
+
return this.remote.status.pendingMessageCount;
|
|
1316
|
+
}
|
|
1317
|
+
getSteeringMessages() {
|
|
1318
|
+
return this.remote.status.steeringMessages;
|
|
1319
|
+
}
|
|
1320
|
+
getFollowUpMessages() {
|
|
1321
|
+
return this.remote.status.followUpMessages;
|
|
1322
|
+
}
|
|
1323
|
+
get model() {
|
|
1324
|
+
return this.remote.status.model ?? super.model;
|
|
1325
|
+
}
|
|
1326
|
+
async setModel(model) {
|
|
1327
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
1328
|
+
this.remote.status.model = model;
|
|
1329
|
+
}
|
|
1330
|
+
get thinkingLevel() {
|
|
1331
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
1332
|
+
}
|
|
1333
|
+
setThinkingLevel(level) {
|
|
1334
|
+
this.remote.status.thinkingLevel = level;
|
|
1335
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
1336
|
+
}
|
|
1337
|
+
get sessionName() {
|
|
1338
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
1339
|
+
}
|
|
1340
|
+
setSessionName(name) {
|
|
1341
|
+
this.remote.status.sessionName = name;
|
|
1342
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
1343
|
+
}
|
|
1344
|
+
getSessionStats() {
|
|
1345
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
1346
|
+
}
|
|
1347
|
+
getContextUsage() {
|
|
1348
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
1349
|
+
}
|
|
1350
|
+
dispose() {
|
|
1351
|
+
this.remote.close();
|
|
1352
|
+
super.dispose();
|
|
1381
1353
|
}
|
|
1382
|
-
await closePromise;
|
|
1383
1354
|
}
|
|
1384
|
-
function createRemoteBashOperations(
|
|
1355
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
1385
1356
|
return {
|
|
1386
1357
|
exec(command, _cwd, execOptions) {
|
|
1387
1358
|
return new Promise((resolve3, reject) => {
|
|
1388
|
-
const pending = {
|
|
1389
|
-
command,
|
|
1390
|
-
onData: execOptions.onData,
|
|
1391
|
-
resolve: resolve3,
|
|
1392
|
-
reject,
|
|
1393
|
-
sawChunk: false
|
|
1394
|
-
};
|
|
1359
|
+
const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
|
|
1395
1360
|
const cleanup = () => {
|
|
1396
1361
|
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
1397
1362
|
if (timer)
|
|
@@ -1399,12 +1364,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
1399
1364
|
};
|
|
1400
1365
|
const onAbort = () => {
|
|
1401
1366
|
cleanup();
|
|
1402
|
-
failPendingShell(
|
|
1367
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
1403
1368
|
};
|
|
1404
1369
|
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
1405
1370
|
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
1406
1371
|
cleanup();
|
|
1407
|
-
failPendingShell(
|
|
1372
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
1408
1373
|
}, timeoutMs) : null;
|
|
1409
1374
|
const wrappedResolve = pending.resolve;
|
|
1410
1375
|
const wrappedReject = pending.reject;
|
|
@@ -1417,125 +1382,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
1417
1382
|
wrappedReject(error);
|
|
1418
1383
|
};
|
|
1419
1384
|
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1420
|
-
|
|
1421
|
-
|
|
1385
|
+
controller.registerPendingShell(pending);
|
|
1386
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
1422
1387
|
cleanup();
|
|
1423
|
-
failPendingShell(
|
|
1388
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
1424
1389
|
});
|
|
1425
1390
|
});
|
|
1426
1391
|
}
|
|
1427
1392
|
};
|
|
1428
1393
|
}
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
if (line === "/cancel") {
|
|
1434
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
1435
|
-
} else if (pending.method === "confirm") {
|
|
1436
|
-
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
1437
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
1438
|
-
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
1439
|
-
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
1440
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
1441
|
-
} else {
|
|
1442
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
1443
|
-
}
|
|
1444
|
-
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
1445
|
-
state.pendingUi = null;
|
|
1446
|
-
return true;
|
|
1394
|
+
|
|
1395
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
1396
|
+
function recordOf2(value) {
|
|
1397
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1447
1398
|
}
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
return;
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
ctx.shutdown();
|
|
1460
|
-
return;
|
|
1399
|
+
function asText(value) {
|
|
1400
|
+
if (typeof value === "string")
|
|
1401
|
+
return value;
|
|
1402
|
+
if (value === null || value === undefined)
|
|
1403
|
+
return "";
|
|
1404
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1405
|
+
return String(value);
|
|
1406
|
+
try {
|
|
1407
|
+
return JSON.stringify(value);
|
|
1408
|
+
} catch {
|
|
1409
|
+
return String(value);
|
|
1461
1410
|
}
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1411
|
+
}
|
|
1412
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
1413
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
1414
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
1415
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
1416
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
1417
|
+
const choices = rawOptions.map((option) => {
|
|
1418
|
+
const record = recordOf2(option);
|
|
1419
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
1420
|
+
}).filter(Boolean);
|
|
1421
|
+
try {
|
|
1422
|
+
if (method === "confirm") {
|
|
1423
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
1424
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
if (choices.length > 0) {
|
|
1428
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
1429
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
1433
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1468
1436
|
}
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
const
|
|
1475
|
-
const
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1437
|
+
}
|
|
1438
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
1439
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
1440
|
+
for (const command of commands) {
|
|
1441
|
+
const record = recordOf2(command);
|
|
1442
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
1443
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
1444
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
1445
|
+
continue;
|
|
1446
|
+
registered.add(name);
|
|
1447
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
1448
|
+
try {
|
|
1449
|
+
pi.registerCommand(name, {
|
|
1450
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
1451
|
+
handler: async (args) => {
|
|
1452
|
+
try {
|
|
1453
|
+
const message2 = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
1454
|
+
ctx.ui.notify(message2, "info");
|
|
1455
|
+
} catch (error) {
|
|
1456
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
});
|
|
1460
|
+
} catch {}
|
|
1480
1461
|
}
|
|
1481
|
-
updatePiUi(ctx, state);
|
|
1482
1462
|
}
|
|
1483
1463
|
function createRigWorkerPiBridgeExtension(options) {
|
|
1484
1464
|
return (pi) => {
|
|
1485
|
-
const state = {
|
|
1486
|
-
transcript: [],
|
|
1487
|
-
status: "starting worker Pi daemon bridge",
|
|
1488
|
-
activity: "",
|
|
1489
|
-
cwd: "",
|
|
1490
|
-
model: "",
|
|
1491
|
-
commands: [],
|
|
1492
|
-
streaming: false,
|
|
1493
|
-
pendingUi: null,
|
|
1494
|
-
pendingShells: [],
|
|
1495
|
-
wsConnected: false,
|
|
1496
|
-
nativeStream: false
|
|
1497
|
-
};
|
|
1498
|
-
if (options.initialMessageSent)
|
|
1499
|
-
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
1500
1465
|
const registeredDaemonCommands = new Set;
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1466
|
+
pi.registerCommand("detach", {
|
|
1467
|
+
description: "Detach from this run; the worker keeps going",
|
|
1468
|
+
handler: async (_args, ctx) => {
|
|
1469
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
1470
|
+
ctx.shutdown();
|
|
1471
|
+
}
|
|
1505
1472
|
});
|
|
1473
|
+
pi.registerCommand("stop", {
|
|
1474
|
+
description: "Stop the worker Pi run and detach",
|
|
1475
|
+
handler: async (_args, ctx) => {
|
|
1476
|
+
await options.controller.abort();
|
|
1477
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
1478
|
+
ctx.shutdown();
|
|
1479
|
+
}
|
|
1480
|
+
});
|
|
1481
|
+
pi.on("user_bash", (event) => ({
|
|
1482
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
1483
|
+
}));
|
|
1506
1484
|
pi.on("session_start", async (_event, ctx) => {
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1485
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
1486
|
+
ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
|
|
1487
|
+
ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
|
|
1488
|
+
if (options.initialMessageSent)
|
|
1489
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
1490
|
+
const nativeUi = ctx.ui;
|
|
1491
|
+
options.controller.setUiHooks({
|
|
1492
|
+
onStatusText: (text) => ctx.ui.setStatus("rig-worker-pi", text),
|
|
1493
|
+
onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
|
|
1494
|
+
onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
|
|
1495
|
+
onError: (message2) => ctx.ui.notify(message2, "error"),
|
|
1496
|
+
onExtensionUiRequest: (request) => {
|
|
1497
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
1498
|
+
},
|
|
1499
|
+
onCatchUp: (messages, commands) => {
|
|
1500
|
+
if (nativeUi.appendSessionMessages)
|
|
1501
|
+
nativeUi.appendSessionMessages(messages);
|
|
1502
|
+
const cwd = options.controller.status.cwd;
|
|
1503
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
1504
|
+
nativeUi.setDisplayCwd(cwd);
|
|
1505
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
1515
1506
|
}
|
|
1516
|
-
if (!data.includes("\r") && !data.includes(`
|
|
1517
|
-
`))
|
|
1518
|
-
return;
|
|
1519
|
-
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
1520
|
-
const editorText = ctx.ui.getEditorText().trim();
|
|
1521
|
-
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
1522
|
-
if (!text)
|
|
1523
|
-
return;
|
|
1524
|
-
if (text.startsWith("!"))
|
|
1525
|
-
return;
|
|
1526
|
-
ctx.ui.setEditorText("");
|
|
1527
|
-
routeInput(options, ctx, state, text).catch((error) => {
|
|
1528
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1529
|
-
updatePiUi(ctx, state);
|
|
1530
|
-
});
|
|
1531
|
-
return { consume: true };
|
|
1532
1507
|
});
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
updatePiUi(ctx, state);
|
|
1508
|
+
options.controller.connect().catch((error) => {
|
|
1509
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1536
1510
|
});
|
|
1537
1511
|
});
|
|
1538
|
-
pi.on("session_shutdown", () => {
|
|
1512
|
+
pi.on("session_shutdown", () => {
|
|
1513
|
+
options.controller.close();
|
|
1514
|
+
});
|
|
1539
1515
|
};
|
|
1540
1516
|
}
|
|
1541
1517
|
|
|
@@ -1556,43 +1532,47 @@ function setTemporaryEnv(updates) {
|
|
|
1556
1532
|
};
|
|
1557
1533
|
}
|
|
1558
1534
|
async function attachRunBundledPiFrontend(context, input) {
|
|
1559
|
-
const
|
|
1560
|
-
const cwd = join(tempRoot, "workspace");
|
|
1561
|
-
const agentDir = join(tempRoot, "agent");
|
|
1562
|
-
const sessionDir = join(tempRoot, "sessions");
|
|
1563
|
-
const previousCwd = process.cwd();
|
|
1535
|
+
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
1564
1536
|
const restoreEnv = setTemporaryEnv({
|
|
1565
|
-
|
|
1566
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
1567
|
-
PI_OFFLINE: "1",
|
|
1537
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
1568
1538
|
PI_SKIP_VERSION_CHECK: "1"
|
|
1569
1539
|
});
|
|
1540
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
1541
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
1542
|
+
const services = await createAgentSessionServices({
|
|
1543
|
+
cwd,
|
|
1544
|
+
agentDir,
|
|
1545
|
+
resourceLoaderOptions: {
|
|
1546
|
+
extensionFactories: [
|
|
1547
|
+
createRigWorkerPiBridgeExtension({
|
|
1548
|
+
context,
|
|
1549
|
+
controller,
|
|
1550
|
+
runId: input.runId,
|
|
1551
|
+
initialMessageSent: input.steered === true
|
|
1552
|
+
})
|
|
1553
|
+
],
|
|
1554
|
+
noContextFiles: true
|
|
1555
|
+
}
|
|
1556
|
+
});
|
|
1557
|
+
const created = await createAgentSessionFromServices({
|
|
1558
|
+
services,
|
|
1559
|
+
sessionManager,
|
|
1560
|
+
sessionStartEvent,
|
|
1561
|
+
noTools: "all",
|
|
1562
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
1563
|
+
});
|
|
1564
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
1565
|
+
};
|
|
1570
1566
|
let detached = false;
|
|
1571
1567
|
try {
|
|
1572
|
-
await
|
|
1573
|
-
|
|
1574
|
-
await runPiMain([
|
|
1575
|
-
"--offline",
|
|
1576
|
-
"--no-session",
|
|
1577
|
-
"--no-tools",
|
|
1578
|
-
"--no-builtin-tools",
|
|
1579
|
-
"--no-skills",
|
|
1580
|
-
"--no-context-files",
|
|
1581
|
-
"--no-approve"
|
|
1582
|
-
], {
|
|
1583
|
-
extensionFactories: [
|
|
1584
|
-
createRigWorkerPiBridgeExtension({
|
|
1585
|
-
context,
|
|
1586
|
-
runId: input.runId,
|
|
1587
|
-
initialMessageSent: input.steered === true
|
|
1588
|
-
})
|
|
1589
|
-
]
|
|
1568
|
+
await runPiMain([], {
|
|
1569
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
1590
1570
|
});
|
|
1591
1571
|
detached = true;
|
|
1592
1572
|
} finally {
|
|
1593
|
-
process.chdir(previousCwd);
|
|
1594
1573
|
restoreEnv();
|
|
1595
|
-
|
|
1574
|
+
controller.close();
|
|
1575
|
+
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
1596
1576
|
}
|
|
1597
1577
|
let run = { runId: input.runId, status: "unknown" };
|
|
1598
1578
|
try {
|
|
@@ -1605,7 +1585,7 @@ async function attachRunBundledPiFrontend(context, input) {
|
|
|
1605
1585
|
timelineCursor: null,
|
|
1606
1586
|
steered: input.steered === true,
|
|
1607
1587
|
detached,
|
|
1608
|
-
rendered: "
|
|
1588
|
+
rendered: "native bundled Pi frontend with remote worker session runtime"
|
|
1609
1589
|
};
|
|
1610
1590
|
}
|
|
1611
1591
|
|