@h-rig/cli 0.0.6-alpha.40 → 0.0.6-alpha.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -963,435 +963,394 @@ 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 { main as runPiMain } from "@earendil-works/pi-coding-agent";
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-worker-bridge-extension.ts
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
- var MAX_TRANSCRIPT_LINES = 120;
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 asText(value) {
975
- if (typeof value === "string")
976
- return value;
977
- if (value === null || value === undefined)
978
- return "";
979
- if (typeof value === "number" || typeof value === "boolean")
980
- return String(value);
981
- try {
982
- return JSON.stringify(value);
983
- } catch {
984
- return String(value);
985
- }
986
- }
987
- function textFromContent(content) {
988
- if (typeof content === "string")
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
- function formatElapsed(sinceMs) {
1236
- const totalSeconds = Math.floor((Date.now() - sinceMs) / 1000);
1237
- const minutes = Math.floor(totalSeconds / 60);
1238
- const seconds = totalSeconds % 60;
1239
- return minutes > 0 ? `${minutes}m${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
1240
- }
1241
- async function waitForWorkerReady(options, ctx, state) {
1242
- const startedAt = Date.now();
1243
- const deadline = startedAt + resolveAttachReadyTimeoutMs();
1244
- let consecutiveFailures = 0;
1245
- while (true) {
1246
- let requestFailed = false;
1247
- const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => {
1248
- requestFailed = true;
1249
- return {
1250
- ready: false,
1251
- status: error instanceof Error ? error.message : String(error),
1252
- retryAfterMs: 1000
1253
- };
1254
- });
1255
- if (session.ready === false) {
1256
- consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
1257
- const status = String(session.status ?? "starting");
1258
- if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
1259
- reportBridgeError(ctx, state, `Run ended before worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${options.runId}\`; restart with \`rig task run --task <id>\`.`);
1260
- return false;
1261
- }
1262
- if (consecutiveFailures >= 5) {
1263
- state.status = `Rig server unreachable \xB7 retrying (${formatElapsed(startedAt)}) \xB7 /detach to exit`;
1264
- } else {
1265
- state.status = `waiting for worker Pi daemon \xB7 ${status} \xB7 ${formatElapsed(startedAt)} \xB7 /detach to exit`;
1266
- }
1267
- updatePiUi(ctx, state);
1268
- if (Date.now() >= deadline) {
1269
- reportBridgeError(ctx, state, `Worker Pi daemon did not become ready within ${formatElapsed(startedAt)} (last status: ${status}). ` + `Check \`rig run show ${options.runId}\` and \`rig doctor\`; the run may have been restarted by a server deploy. ` + "Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.");
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
- state.wsConnected = true;
1328
- state.status = "live worker Pi WebSocket connected";
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 = parseWsPayload(message2);
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(ctx, state, payload);
1338
- updatePiUi(ctx, state);
1339
- }
1055
+ else
1056
+ this.applyEnvelope(payload);
1340
1057
  } catch (error) {
1341
- appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
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
- state.wsConnected = false;
1348
- state.status = "worker Pi WebSocket disconnected";
1349
- updatePiUi(ctx, state);
1350
- resolve3();
1063
+ this.hooks.onConnectionChange?.(false);
1064
+ if (!this.closed)
1065
+ this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
1351
1066
  };
1352
- });
1353
- try {
1354
- const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
1355
- getRunPiMessagesViaServer(options.context, options.runId),
1356
- getRunPiStatusViaServer(options.context, options.runId),
1357
- getRunPiCommandsViaServer(options.context, options.runId)
1358
- ]);
1359
- const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
1360
- const native = nativePiUi(ctx);
1361
- if (state.nativeStream && native?.appendSessionMessages)
1362
- native.appendSessionMessages(messages);
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
- for (const message2 of messages)
1365
- applyMessage(state, message2);
1366
- applyStatus(state, statusPayload);
1367
- const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
1368
- state.commands = commands.flatMap((command) => {
1369
- const record = recordOf(command);
1370
- return typeof record?.name === "string" ? [`/${record.name}`] : [];
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
+ await this.remote.sendPrompt(text, "steer");
1274
+ }
1275
+ async followUp(text) {
1276
+ await this.remote.sendPrompt(text, "followUp");
1277
+ }
1278
+ async abort() {
1279
+ await this.remote.abort();
1280
+ }
1281
+ async compact(customInstructions) {
1282
+ const pending = new Promise((resolve3, reject) => {
1283
+ this.remote.registerPendingCompaction({ resolve: resolve3, reject });
1371
1284
  });
1372
- registerDaemonCommandsNatively(pi, options, ctx, state, commands, registeredDaemonCommands);
1373
- catchupDone = true;
1374
- for (const payload of buffered.splice(0))
1375
- applyEnvelope(ctx, state, payload);
1376
- updatePiUi(ctx, state);
1377
- } catch (error) {
1378
- appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
1379
- catchupDone = true;
1380
- updatePiUi(ctx, state);
1285
+ await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
1286
+ return pending;
1287
+ }
1288
+ clearQueue() {
1289
+ const cleared = {
1290
+ steering: [...this.remote.status.steeringMessages],
1291
+ followUp: [...this.remote.status.followUpMessages]
1292
+ };
1293
+ this.remote.status.steeringMessages = [];
1294
+ this.remote.status.followUpMessages = [];
1295
+ this.remote.status.pendingMessageCount = 0;
1296
+ this.remote.sendCommand("/queue-clear").catch(() => {});
1297
+ return cleared;
1298
+ }
1299
+ get isStreaming() {
1300
+ return this.remote.status.isStreaming;
1301
+ }
1302
+ get isCompacting() {
1303
+ return this.remote.status.isCompacting;
1304
+ }
1305
+ get isBashRunning() {
1306
+ return this.remote.status.isBashRunning;
1307
+ }
1308
+ get pendingMessageCount() {
1309
+ return this.remote.status.pendingMessageCount;
1310
+ }
1311
+ getSteeringMessages() {
1312
+ return this.remote.status.steeringMessages;
1313
+ }
1314
+ getFollowUpMessages() {
1315
+ return this.remote.status.followUpMessages;
1316
+ }
1317
+ get model() {
1318
+ return this.remote.status.model ?? super.model;
1319
+ }
1320
+ async setModel(model) {
1321
+ await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
1322
+ this.remote.status.model = model;
1323
+ }
1324
+ get thinkingLevel() {
1325
+ return this.remote.status.thinkingLevel ?? super.thinkingLevel;
1326
+ }
1327
+ setThinkingLevel(level) {
1328
+ this.remote.status.thinkingLevel = level;
1329
+ this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
1330
+ }
1331
+ get sessionName() {
1332
+ return this.remote.status.sessionName ?? super.sessionName;
1333
+ }
1334
+ setSessionName(name) {
1335
+ this.remote.status.sessionName = name;
1336
+ this.remote.sendCommand(`/name ${name}`).catch(() => {});
1337
+ }
1338
+ getSessionStats() {
1339
+ return this.remote.status.stats ?? super.getSessionStats();
1340
+ }
1341
+ getContextUsage() {
1342
+ return this.remote.status.contextUsage ?? super.getContextUsage();
1343
+ }
1344
+ dispose() {
1345
+ this.remote.close();
1346
+ super.dispose();
1381
1347
  }
1382
- await closePromise;
1383
1348
  }
1384
- function createRemoteBashOperations(options, state, excludeFromContext) {
1349
+ function createRemoteBashOperations(controller, excludeFromContext) {
1385
1350
  return {
1386
1351
  exec(command, _cwd, execOptions) {
1387
1352
  return new Promise((resolve3, reject) => {
1388
- const pending = {
1389
- command,
1390
- onData: execOptions.onData,
1391
- resolve: resolve3,
1392
- reject,
1393
- sawChunk: false
1394
- };
1353
+ const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
1395
1354
  const cleanup = () => {
1396
1355
  execOptions.signal?.removeEventListener("abort", onAbort);
1397
1356
  if (timer)
@@ -1399,12 +1358,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
1399
1358
  };
1400
1359
  const onAbort = () => {
1401
1360
  cleanup();
1402
- failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
1361
+ controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
1403
1362
  };
1404
1363
  const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
1405
1364
  const timer = timeoutMs > 0 ? setTimeout(() => {
1406
1365
  cleanup();
1407
- failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
1366
+ controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
1408
1367
  }, timeoutMs) : null;
1409
1368
  const wrappedResolve = pending.resolve;
1410
1369
  const wrappedReject = pending.reject;
@@ -1417,125 +1376,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
1417
1376
  wrappedReject(error);
1418
1377
  };
1419
1378
  execOptions.signal?.addEventListener("abort", onAbort, { once: true });
1420
- state.pendingShells.push(pending);
1421
- sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
1379
+ controller.registerPendingShell(pending);
1380
+ controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
1422
1381
  cleanup();
1423
- failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
1382
+ controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
1424
1383
  });
1425
1384
  });
1426
1385
  }
1427
1386
  };
1428
1387
  }
1429
- async function answerPendingUi(options, state, line) {
1430
- const pending = state.pendingUi;
1431
- if (!pending)
1432
- return false;
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;
1388
+
1389
+ // packages/cli/src/commands/_pi-worker-bridge-extension.ts
1390
+ function recordOf2(value) {
1391
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1447
1392
  }
1448
- async function routeInput(options, ctx, state, line) {
1449
- const text = line.trim();
1450
- if (!text)
1451
- return;
1452
- if (await answerPendingUi(options, state, text)) {
1453
- updatePiUi(ctx, state);
1454
- return;
1455
- }
1456
- if (text === "/detach" || text === "/quit" || text === "/q") {
1457
- appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
1458
- updatePiUi(ctx, state);
1459
- ctx.shutdown();
1460
- return;
1393
+ function asText(value) {
1394
+ if (typeof value === "string")
1395
+ return value;
1396
+ if (value === null || value === undefined)
1397
+ return "";
1398
+ if (typeof value === "number" || typeof value === "boolean")
1399
+ return String(value);
1400
+ try {
1401
+ return JSON.stringify(value);
1402
+ } catch {
1403
+ return String(value);
1461
1404
  }
1462
- if (text === "/stop") {
1463
- await abortRunPiViaServer(options.context, options.runId);
1464
- appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
1465
- updatePiUi(ctx, state);
1466
- ctx.shutdown();
1467
- return;
1405
+ }
1406
+ async function answerExtensionUiRequest(options, ctx, request) {
1407
+ const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
1408
+ const method = String(request.method ?? request.type ?? "input");
1409
+ const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
1410
+ const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
1411
+ const choices = rawOptions.map((option) => {
1412
+ const record = recordOf2(option);
1413
+ return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
1414
+ }).filter(Boolean);
1415
+ try {
1416
+ if (method === "confirm") {
1417
+ const confirmed = await ctx.ui.confirm("Worker request", prompt);
1418
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
1419
+ return;
1420
+ }
1421
+ if (choices.length > 0) {
1422
+ const selected = await ctx.ui.select(prompt, choices);
1423
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
1424
+ return;
1425
+ }
1426
+ const value = await ctx.ui.input("Worker request", prompt);
1427
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
1428
+ } catch (error) {
1429
+ ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
1468
1430
  }
1469
- if (text.startsWith("!")) {
1470
- appendTranscript(state, "You", text);
1471
- await sendRunPiShellViaServer(options.context, options.runId, text);
1472
- } else if (text.startsWith("/")) {
1473
- appendTranscript(state, "You", text);
1474
- const result = await runRunPiCommandViaServer(options.context, options.runId, text);
1475
- const message2 = typeof result.message === "string" ? result.message : "worker command accepted";
1476
- appendTranscript(state, "System", message2);
1477
- } else {
1478
- appendTranscript(state, "You", text);
1479
- await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
1431
+ }
1432
+ var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
1433
+ function registerDaemonCommands(pi, options, ctx, commands, registered) {
1434
+ for (const command of commands) {
1435
+ const record = recordOf2(command);
1436
+ const name = typeof record?.name === "string" ? record.name : "";
1437
+ const source = typeof record?.source === "string" ? record.source : "worker";
1438
+ if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
1439
+ continue;
1440
+ registered.add(name);
1441
+ const description = typeof record?.description === "string" ? record.description : undefined;
1442
+ try {
1443
+ pi.registerCommand(name, {
1444
+ description: `[worker ${source}] ${description ?? ""}`.trim(),
1445
+ handler: async (args) => {
1446
+ try {
1447
+ const message2 = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
1448
+ ctx.ui.notify(message2, "info");
1449
+ } catch (error) {
1450
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1451
+ }
1452
+ }
1453
+ });
1454
+ } catch {}
1480
1455
  }
1481
- updatePiUi(ctx, state);
1482
1456
  }
1483
1457
  function createRigWorkerPiBridgeExtension(options) {
1484
1458
  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
1459
  const registeredDaemonCommands = new Set;
1501
- let nativePiUiContextAvailable = false;
1502
- pi.on("user_bash", (event) => {
1503
- state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
1504
- return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
1460
+ pi.registerCommand("detach", {
1461
+ description: "Detach from this run; the worker keeps going",
1462
+ handler: async (_args, ctx) => {
1463
+ ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
1464
+ ctx.shutdown();
1465
+ }
1505
1466
  });
1467
+ pi.registerCommand("stop", {
1468
+ description: "Stop the worker Pi run and detach",
1469
+ handler: async (_args, ctx) => {
1470
+ await options.controller.abort();
1471
+ ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
1472
+ ctx.shutdown();
1473
+ }
1474
+ });
1475
+ pi.on("user_bash", (event) => ({
1476
+ operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
1477
+ }));
1506
1478
  pi.on("session_start", async (_event, ctx) => {
1507
- nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
1508
- state.nativeStream = nativePiUiContextAvailable;
1509
- updatePiUi(ctx, state);
1510
- ctx.ui.notify(nativePiUiContextAvailable ? "Connected to the Rig worker session (native stream). /detach exits, /stop cancels the run." : "Connected to the Rig worker session (transcript view). /detach exits, /stop cancels the run.", "info");
1511
- ctx.ui.onTerminalInput((data) => {
1512
- if (data.includes("\x04")) {
1513
- ctx.shutdown();
1514
- return { consume: true };
1479
+ ctx.ui.setTitle("Rig \xB7 worker session");
1480
+ ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
1481
+ ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
1482
+ if (options.initialMessageSent)
1483
+ ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
1484
+ const nativeUi = ctx.ui;
1485
+ options.controller.setUiHooks({
1486
+ onStatusText: (text) => ctx.ui.setStatus("rig-worker-pi", text),
1487
+ onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
1488
+ onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
1489
+ onError: (message2) => ctx.ui.notify(message2, "error"),
1490
+ onExtensionUiRequest: (request) => {
1491
+ answerExtensionUiRequest(options, ctx, request);
1492
+ },
1493
+ onCatchUp: (messages, commands) => {
1494
+ if (nativeUi.appendSessionMessages)
1495
+ nativeUi.appendSessionMessages(messages);
1496
+ const cwd = options.controller.status.cwd;
1497
+ if (nativeUi.setDisplayCwd && cwd)
1498
+ nativeUi.setDisplayCwd(cwd);
1499
+ registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
1515
1500
  }
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
1501
  });
1533
- connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands).catch((error) => {
1534
- appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
1535
- updatePiUi(ctx, state);
1502
+ options.controller.connect().catch((error) => {
1503
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
1536
1504
  });
1537
1505
  });
1538
- pi.on("session_shutdown", () => {});
1506
+ pi.on("session_shutdown", () => {
1507
+ options.controller.close();
1508
+ });
1539
1509
  };
1540
1510
  }
1541
1511
 
@@ -1556,43 +1526,47 @@ function setTemporaryEnv(updates) {
1556
1526
  };
1557
1527
  }
1558
1528
  async function attachRunBundledPiFrontend(context, input) {
1559
- const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
1560
- const cwd = join(tempRoot, "workspace");
1561
- const agentDir = join(tempRoot, "agent");
1562
- const sessionDir = join(tempRoot, "sessions");
1563
- const previousCwd = process.cwd();
1529
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1564
1530
  const restoreEnv = setTemporaryEnv({
1565
- PI_CODING_AGENT_DIR: agentDir,
1566
- PI_CODING_AGENT_SESSION_DIR: sessionDir,
1567
- PI_OFFLINE: "1",
1531
+ PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
1568
1532
  PI_SKIP_VERSION_CHECK: "1"
1569
1533
  });
1534
+ const controller = new RigRemoteSessionController({ context, runId: input.runId });
1535
+ const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
1536
+ const services = await createAgentSessionServices({
1537
+ cwd,
1538
+ agentDir,
1539
+ resourceLoaderOptions: {
1540
+ extensionFactories: [
1541
+ createRigWorkerPiBridgeExtension({
1542
+ context,
1543
+ controller,
1544
+ runId: input.runId,
1545
+ initialMessageSent: input.steered === true
1546
+ })
1547
+ ],
1548
+ noContextFiles: true
1549
+ }
1550
+ });
1551
+ const created = await createAgentSessionFromServices({
1552
+ services,
1553
+ sessionManager,
1554
+ sessionStartEvent,
1555
+ noTools: "all",
1556
+ sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
1557
+ });
1558
+ return { ...created, services, diagnostics: services.diagnostics };
1559
+ };
1570
1560
  let detached = false;
1571
1561
  try {
1572
- await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
1573
- process.chdir(cwd);
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
- ]
1562
+ await runPiMain([], {
1563
+ createRuntimeOverride: () => createRemoteRuntime
1590
1564
  });
1591
1565
  detached = true;
1592
1566
  } finally {
1593
- process.chdir(previousCwd);
1594
1567
  restoreEnv();
1595
- rmSync(tempRoot, { recursive: true, force: true });
1568
+ controller.close();
1569
+ rmSync(tempSessionDir, { recursive: true, force: true });
1596
1570
  }
1597
1571
  let run = { runId: input.runId, status: "unknown" };
1598
1572
  try {
@@ -1605,7 +1579,7 @@ async function attachRunBundledPiFrontend(context, input) {
1605
1579
  timelineCursor: null,
1606
1580
  steered: input.steered === true,
1607
1581
  detached,
1608
- rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
1582
+ rendered: "native bundled Pi frontend with remote worker session runtime"
1609
1583
  };
1610
1584
  }
1611
1585