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