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