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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,11 @@
3
3
  import { mkdtempSync, rmSync } from "fs";
4
4
  import { tmpdir } from "os";
5
5
  import { join } from "path";
6
- import { main as runPiMain } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ createAgentSessionFromServices,
8
+ createAgentSessionServices,
9
+ main as runPiMain
10
+ } from "@earendil-works/pi-coding-agent";
7
11
 
8
12
  // packages/cli/src/commands/_server-client.ts
9
13
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
@@ -258,433 +262,394 @@ async function buildRunPiEventsWebSocketUrl(context, runId) {
258
262
  return url.toString();
259
263
  }
260
264
 
261
- // packages/cli/src/commands/_pi-worker-bridge-extension.ts
265
+ // packages/cli/src/commands/_pi-remote-session.ts
266
+ import { AgentSession as PiAgentSession } from "@earendil-works/pi-coding-agent";
262
267
  var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
263
- var MAX_TRANSCRIPT_LINES = 120;
268
+ function defaultTransport() {
269
+ return {
270
+ getSession: getRunPiSessionViaServer,
271
+ getMessages: getRunPiMessagesViaServer,
272
+ getStatus: getRunPiStatusViaServer,
273
+ getCommands: getRunPiCommandsViaServer,
274
+ sendPrompt: sendRunPiPromptViaServer,
275
+ sendShell: sendRunPiShellViaServer,
276
+ runCommand: runRunPiCommandViaServer,
277
+ abort: abortRunPiViaServer,
278
+ buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
279
+ };
280
+ }
264
281
  function recordOf(value) {
265
282
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
266
283
  }
267
- function asText(value) {
268
- if (typeof value === "string")
269
- return value;
270
- if (value === null || value === undefined)
271
- return "";
272
- if (typeof value === "number" || typeof value === "boolean")
273
- return String(value);
274
- try {
275
- return JSON.stringify(value);
276
- } catch {
277
- return String(value);
278
- }
279
- }
280
- function textFromContent(content) {
281
- if (typeof content === "string")
282
- return content;
283
- if (!Array.isArray(content))
284
- return asText(content);
285
- return content.flatMap((part) => {
286
- const item = recordOf(part);
287
- if (!item)
288
- return [];
289
- if (typeof item.text === "string")
290
- return [item.text];
291
- if (typeof item.content === "string")
292
- return [item.content];
293
- if (item.type === "toolCall")
294
- return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
295
- if (item.type === "toolResult")
296
- return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
297
- return [];
298
- }).join(`
299
- `);
300
- }
301
- function appendTranscript(state, label, text) {
302
- const trimmed = text.trimEnd();
303
- if (!trimmed)
304
- return;
305
- const lines = trimmed.split(/\r?\n/);
306
- state.transcript.push(`${label}: ${lines[0] ?? ""}`);
307
- for (const line of lines.slice(1))
308
- state.transcript.push(` ${line}`);
309
- if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
310
- state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
311
- }
312
- }
313
- function nativePiUi(ctx) {
314
- const ui = ctx.ui;
315
- return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
316
- }
317
- function syncNativeDisplayCwd(ctx, state) {
318
- const ui = nativePiUi(ctx);
319
- if (ui?.setDisplayCwd && state.cwd)
320
- ui.setDisplayCwd(state.cwd);
321
- }
322
- function parseExtensionUiRequest(value) {
323
- const request = recordOf(value) ?? {};
324
- const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
325
- const method = String(request.method ?? request.type ?? "input");
326
- const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
327
- const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
328
- const options = rawOptions.map((option) => {
329
- const record = recordOf(option);
330
- return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
331
- }).filter(Boolean);
332
- return { requestId, method, prompt, options };
333
- }
334
- function renderBridgeWidget(state) {
335
- const statusParts = [
336
- state.wsConnected ? "live" : "connecting",
337
- state.status,
338
- state.model,
339
- state.cwd
340
- ].filter(Boolean);
341
- const lines = [`Rig worker session \xB7 ${statusParts.join(" \xB7 ")}`];
342
- if (state.activity)
343
- lines.push(state.activity);
344
- if (state.commands.length > 0) {
345
- lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
346
- }
347
- lines.push("");
348
- if (state.transcript.length > 0) {
349
- lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
350
- } else {
351
- lines.push("Waiting for the worker session transcript\u2026 (/detach exits and leaves the worker running)");
352
- }
353
- if (state.pendingUi) {
354
- lines.push("");
355
- lines.push(`Worker needs input \xB7 ${state.pendingUi.method}`);
356
- lines.push(state.pendingUi.prompt);
357
- state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
358
- lines.push("Reply in the editor below. /cancel dismisses this request.");
359
- }
360
- return lines;
361
- }
362
- function reportBridgeError(ctx, state, message) {
363
- appendTranscript(state, "Error", message);
364
- state.status = message;
365
- try {
366
- ctx.ui.notify(message, "error");
367
- } catch {}
368
- updatePiUi(ctx, state);
369
- }
370
- function updatePiUi(ctx, state) {
371
- ctx.ui.setTitle("Rig \xB7 worker session");
372
- ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker session live" : state.status);
373
- syncNativeDisplayCwd(ctx, state);
374
- if (state.nativeStream && nativePiUi(ctx)) {
375
- ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
376
- return;
377
- }
378
- ctx.ui.setWorkingVisible(false);
379
- ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
380
- }
381
- function applyStatus(state, payload) {
382
- const status = recordOf(payload.status) ?? payload;
383
- state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
384
- state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
385
- state.model = typeof status.model === "string" ? status.model : state.model;
386
- const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
387
- state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
388
- }
389
- function applyMessage(state, message) {
390
- const record = recordOf(message);
391
- if (!record)
392
- return;
393
- const role = String(record.role ?? "system");
394
- const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
395
- appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
396
- }
397
- function applyPiEvent(ctx, state, eventValue) {
398
- const event = recordOf(eventValue);
399
- if (!event)
400
- return;
401
- const type = String(event.type ?? "event");
402
- if (type === "agent_start") {
403
- state.streaming = true;
404
- state.status = "streaming";
405
- } else if (type === "agent_end") {
406
- state.streaming = false;
407
- state.status = "idle";
408
- } else if (type === "queue_update") {
409
- const steering = Array.isArray(event.steering) ? event.steering.length : 0;
410
- const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
411
- state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
412
- }
413
- const native = nativePiUi(ctx);
414
- if (state.nativeStream && native?.emitSessionEvent) {
415
- native.emitSessionEvent(eventValue);
416
- return;
417
- }
418
- if (type === "agent_end") {
419
- appendTranscript(state, "System", "Agent turn complete.");
420
- return;
421
- }
422
- if (type === "message_start" || type === "message_end" || type === "turn_end") {
423
- applyMessage(state, event.message);
424
- return;
425
- }
426
- if (type === "message_update") {
427
- const assistantEvent = recordOf(event.assistantMessageEvent);
428
- const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
429
- if (delta)
430
- appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
431
- return;
432
- }
433
- if (type === "tool_execution_start") {
434
- appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
435
- return;
436
- }
437
- if (type === "tool_execution_update") {
438
- appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
439
- return;
440
- }
441
- if (type === "tool_execution_end") {
442
- appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
443
- }
444
- }
445
- function firstPendingShell(state) {
446
- return state.pendingShells[0];
447
- }
448
- function finishPendingShell(state, shell, result) {
449
- const index = state.pendingShells.indexOf(shell);
450
- if (index !== -1)
451
- state.pendingShells.splice(index, 1);
452
- shell.resolve(result);
453
- }
454
- function failPendingShell(state, shell, error) {
455
- const index = state.pendingShells.indexOf(shell);
456
- if (index !== -1)
457
- state.pendingShells.splice(index, 1);
458
- shell.reject(error);
459
- }
460
- function applyUiEvent(state, value) {
461
- const event = recordOf(value);
462
- if (!event)
463
- return;
464
- const type = String(event.type ?? "ui");
465
- if (type === "shell.chunk") {
466
- const pending = firstPendingShell(state);
467
- const chunk = asText(event.chunk);
468
- if (pending) {
469
- pending.sawChunk = true;
470
- pending.onData(Buffer.from(chunk));
471
- } else {
472
- appendTranscript(state, "Tool", chunk);
473
- }
474
- return;
475
- }
476
- if (type === "shell.end") {
477
- const pending = firstPendingShell(state);
478
- const output = asText(event.output ?? "");
479
- const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
480
- if (pending) {
481
- if (output && !pending.sawChunk)
482
- pending.onData(Buffer.from(output));
483
- finishPendingShell(state, pending, { exitCode });
484
- } else {
485
- appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
486
- }
487
- return;
488
- }
489
- if (type === "shell.start") {
490
- if (!firstPendingShell(state))
491
- appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
492
- return;
493
- }
494
- appendTranscript(state, "System", `${type}: ${asText(event)}`);
495
- }
496
- function applyEnvelope(ctx, state, envelopeValue) {
497
- const envelope = recordOf(envelopeValue);
498
- if (!envelope)
499
- return;
500
- const type = String(envelope.type ?? "");
501
- if (type === "ready") {
502
- const metadata = recordOf(envelope.metadata);
503
- state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
504
- state.status = "worker Pi daemon ready";
505
- if (!state.nativeStream)
506
- appendTranscript(state, "System", "Connected to worker Pi daemon.");
507
- } else if (type === "status.update") {
508
- applyStatus(state, envelope);
509
- } else if (type === "activity.update") {
510
- const activity = recordOf(envelope.activity);
511
- state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
512
- } else if (type === "extension_ui_request") {
513
- state.pendingUi = parseExtensionUiRequest(envelope.request);
514
- appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
515
- } else if (type === "pi.ui_event") {
516
- applyUiEvent(state, envelope.event);
517
- } else if (type === "pi.event") {
518
- applyPiEvent(ctx, state, envelope.event);
519
- } else if (type === "error") {
520
- appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
521
- }
522
- syncNativeDisplayCwd(ctx, state);
284
+ function emptyRemoteStatus() {
285
+ return {
286
+ isStreaming: false,
287
+ isCompacting: false,
288
+ isBashRunning: false,
289
+ pendingMessageCount: 0,
290
+ steeringMessages: [],
291
+ followUpMessages: [],
292
+ model: null,
293
+ thinkingLevel: null,
294
+ sessionName: null,
295
+ cwd: null,
296
+ stats: null,
297
+ contextUsage: null
298
+ };
523
299
  }
524
300
  function resolveAttachReadyTimeoutMs() {
525
301
  const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
526
302
  return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
527
303
  }
528
- function formatElapsed(sinceMs) {
529
- const totalSeconds = Math.floor((Date.now() - sinceMs) / 1000);
530
- const minutes = Math.floor(totalSeconds / 60);
531
- const seconds = totalSeconds % 60;
532
- return minutes > 0 ? `${minutes}m${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
533
- }
534
- async function waitForWorkerReady(options, ctx, state) {
535
- const startedAt = Date.now();
536
- const deadline = startedAt + resolveAttachReadyTimeoutMs();
537
- let consecutiveFailures = 0;
538
- while (true) {
539
- let requestFailed = false;
540
- const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => {
541
- requestFailed = true;
542
- return {
543
- ready: false,
544
- status: error instanceof Error ? error.message : String(error),
545
- retryAfterMs: 1000
546
- };
547
- });
548
- if (session.ready === false) {
549
- consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
550
- const status = String(session.status ?? "starting");
551
- if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
552
- 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>\`.`);
553
- return false;
554
- }
555
- if (consecutiveFailures >= 5) {
556
- state.status = `Rig server unreachable \xB7 retrying (${formatElapsed(startedAt)}) \xB7 /detach to exit`;
557
- } else {
558
- state.status = `waiting for worker Pi daemon \xB7 ${status} \xB7 ${formatElapsed(startedAt)} \xB7 /detach to exit`;
559
- }
560
- updatePiUi(ctx, state);
561
- if (Date.now() >= deadline) {
562
- 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.");
563
- return false;
564
- }
565
- await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
566
- continue;
567
- }
568
- const sessionRecord = recordOf(session) ?? {};
569
- applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
570
- updatePiUi(ctx, state);
571
- return true;
572
- }
573
- }
574
- function parseWsPayload(message) {
575
- if (typeof message.data === "string")
576
- return JSON.parse(message.data);
577
- return JSON.parse(Buffer.from(message.data).toString("utf8"));
578
- }
579
- var BRIDGE_LOCAL_COMMANDS = new Set(["detach", "quit", "q", "stop"]);
580
- function registerDaemonCommandsNatively(pi, options, ctx, state, commands, registered) {
581
- for (const command of commands) {
582
- const record = recordOf(command);
583
- const name = typeof record?.name === "string" ? record.name : "";
584
- if (!name || registered.has(name) || BRIDGE_LOCAL_COMMANDS.has(name))
585
- continue;
586
- registered.add(name);
587
- const description = typeof record?.description === "string" ? record.description : undefined;
588
- const source = typeof record?.source === "string" ? record.source : "worker";
589
- try {
590
- pi.registerCommand(name, {
591
- description: `[worker ${source}] ${description ?? ""}`.trim(),
592
- handler: async (args) => {
593
- const text = `/${name}${args ? ` ${args}` : ""}`;
594
- appendTranscript(state, "You", text);
595
- try {
596
- const result = await runRunPiCommandViaServer(options.context, options.runId, text);
597
- const message = typeof result.message === "string" ? result.message : "worker command accepted";
598
- appendTranscript(state, "System", message);
599
- if (state.nativeStream)
600
- ctx.ui.notify(message, "info");
601
- } catch (error) {
602
- reportBridgeError(ctx, state, error instanceof Error ? error.message : String(error));
603
- }
604
- updatePiUi(ctx, state);
605
- }
606
- });
607
- } catch {}
608
- }
609
- }
610
- async function connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands) {
611
- const ready = await waitForWorkerReady(options, ctx, state);
612
- if (!ready)
613
- return;
614
- let catchupDone = false;
615
- const buffered = [];
616
- const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
617
- const socket = new WebSocket(wsUrl);
618
- const closePromise = new Promise((resolve3) => {
304
+
305
+ class RigRemoteSessionController {
306
+ context;
307
+ runId;
308
+ status = emptyRemoteStatus();
309
+ transport;
310
+ hooks = {};
311
+ session = null;
312
+ socket = null;
313
+ closed = false;
314
+ pendingShells = [];
315
+ pendingCompactions = [];
316
+ constructor(input) {
317
+ this.context = input.context;
318
+ this.runId = input.runId;
319
+ this.transport = input.transport ?? defaultTransport();
320
+ }
321
+ ingestEnvelope(envelopeValue) {
322
+ this.applyEnvelope(envelopeValue);
323
+ }
324
+ bindSession(session) {
325
+ this.session = session;
326
+ }
327
+ setUiHooks(hooks) {
328
+ this.hooks = hooks;
329
+ }
330
+ async connect() {
331
+ const ready = await this.waitForReady();
332
+ if (!ready || this.closed)
333
+ return;
334
+ let catchupDone = false;
335
+ const buffered = [];
336
+ const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
337
+ const socket = new WebSocket(wsUrl);
338
+ this.socket = socket;
619
339
  socket.onopen = () => {
620
- state.wsConnected = true;
621
- state.status = "live worker Pi WebSocket connected";
622
- updatePiUi(ctx, state);
340
+ this.hooks.onConnectionChange?.(true);
341
+ this.hooks.onStatusText?.("worker session live");
623
342
  };
624
343
  socket.onmessage = (message) => {
625
344
  try {
626
- const payload = parseWsPayload(message);
345
+ const payload = typeof message.data === "string" ? JSON.parse(message.data) : JSON.parse(Buffer.from(message.data).toString("utf8"));
627
346
  if (!catchupDone)
628
347
  buffered.push(payload);
629
- else {
630
- applyEnvelope(ctx, state, payload);
631
- updatePiUi(ctx, state);
632
- }
348
+ else
349
+ this.applyEnvelope(payload);
633
350
  } catch (error) {
634
- appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
635
- updatePiUi(ctx, state);
351
+ this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
636
352
  }
637
353
  };
638
354
  socket.onerror = () => socket.close();
639
355
  socket.onclose = () => {
640
- state.wsConnected = false;
641
- state.status = "worker Pi WebSocket disconnected";
642
- updatePiUi(ctx, state);
643
- resolve3();
356
+ this.hooks.onConnectionChange?.(false);
357
+ if (!this.closed)
358
+ this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
644
359
  };
645
- });
646
- try {
647
- const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
648
- getRunPiMessagesViaServer(options.context, options.runId),
649
- getRunPiStatusViaServer(options.context, options.runId),
650
- getRunPiCommandsViaServer(options.context, options.runId)
651
- ]);
652
- const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
653
- const native = nativePiUi(ctx);
654
- if (state.nativeStream && native?.appendSessionMessages)
655
- native.appendSessionMessages(messages);
360
+ try {
361
+ const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
362
+ this.transport.getMessages(this.context, this.runId),
363
+ this.transport.getStatus(this.context, this.runId),
364
+ this.transport.getCommands(this.context, this.runId)
365
+ ]);
366
+ const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
367
+ this.applyStatusPayload(statusPayload);
368
+ this.session?.replaceRemoteMessages(messages);
369
+ const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
370
+ this.hooks.onCatchUp?.(messages, commands);
371
+ catchupDone = true;
372
+ for (const payload of buffered.splice(0))
373
+ this.applyEnvelope(payload);
374
+ } catch (error) {
375
+ catchupDone = true;
376
+ this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
377
+ }
378
+ }
379
+ close() {
380
+ this.closed = true;
381
+ this.socket?.close();
382
+ for (const shell of this.pendingShells.splice(0))
383
+ shell.reject(new Error("Remote session closed."));
384
+ for (const compaction of this.pendingCompactions.splice(0))
385
+ compaction.reject(new Error("Remote session closed."));
386
+ }
387
+ async sendPrompt(text, streamingBehavior) {
388
+ await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
389
+ }
390
+ async sendCommand(text) {
391
+ const result = await this.transport.runCommand(this.context, this.runId, text);
392
+ return typeof result.message === "string" ? result.message : "worker command accepted";
393
+ }
394
+ async sendShell(text) {
395
+ await this.transport.sendShell(this.context, this.runId, text);
396
+ }
397
+ async abort() {
398
+ await this.transport.abort(this.context, this.runId);
399
+ }
400
+ registerPendingShell(shell) {
401
+ this.pendingShells.push(shell);
402
+ }
403
+ failPendingShell(shell, error) {
404
+ const index = this.pendingShells.indexOf(shell);
405
+ if (index !== -1)
406
+ this.pendingShells.splice(index, 1);
407
+ shell.reject(error);
408
+ }
409
+ registerPendingCompaction(pending) {
410
+ this.pendingCompactions.push(pending);
411
+ }
412
+ async waitForReady() {
413
+ const startedAt = Date.now();
414
+ const deadline = startedAt + resolveAttachReadyTimeoutMs();
415
+ let consecutiveFailures = 0;
416
+ while (!this.closed) {
417
+ let requestFailed = false;
418
+ const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
419
+ requestFailed = true;
420
+ return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
421
+ });
422
+ if (session.ready !== false)
423
+ return true;
424
+ consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
425
+ const status = String(session.status ?? "starting");
426
+ if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
427
+ this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
428
+ return false;
429
+ }
430
+ 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`);
431
+ if (Date.now() >= deadline) {
432
+ this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
433
+ return false;
434
+ }
435
+ await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
436
+ }
437
+ return false;
438
+ }
439
+ applyEnvelope(envelopeValue) {
440
+ const envelope = recordOf(envelopeValue);
441
+ if (!envelope)
442
+ return;
443
+ const type = String(envelope.type ?? "");
444
+ if (type === "status.update") {
445
+ this.applyStatusPayload(envelope);
446
+ return;
447
+ }
448
+ if (type === "activity.update") {
449
+ const activity = recordOf(envelope.activity);
450
+ this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
451
+ return;
452
+ }
453
+ if (type === "extension_ui_request") {
454
+ const request = recordOf(envelope.request);
455
+ if (request)
456
+ this.hooks.onExtensionUiRequest?.(request);
457
+ return;
458
+ }
459
+ if (type === "pi.ui_event") {
460
+ this.applyShellUiEvent(envelope.event);
461
+ return;
462
+ }
463
+ if (type === "pi.event") {
464
+ this.session?.handleRemoteSessionEvent(envelope.event);
465
+ this.settlePendingCompaction(envelope.event);
466
+ return;
467
+ }
468
+ if (type === "error") {
469
+ this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
470
+ }
471
+ }
472
+ applyStatusPayload(payload) {
473
+ const status = recordOf(payload.status) ?? payload;
474
+ const next = this.status;
475
+ next.isStreaming = status.isStreaming === true;
476
+ next.isCompacting = status.isCompacting === true;
477
+ next.isBashRunning = status.isBashRunning === true;
478
+ next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
479
+ next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
480
+ next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
481
+ next.model = recordOf(status.model) ?? next.model;
482
+ next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
483
+ next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
484
+ next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
485
+ next.stats = recordOf(status.stats) ?? next.stats;
486
+ next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
487
+ }
488
+ applyShellUiEvent(value) {
489
+ const event = recordOf(value);
490
+ if (!event)
491
+ return;
492
+ const type = String(event.type ?? "");
493
+ const pending = this.pendingShells[0];
494
+ if (type === "shell.chunk" && pending) {
495
+ pending.sawChunk = true;
496
+ pending.onData(Buffer.from(String(event.chunk ?? "")));
497
+ return;
498
+ }
499
+ if (type === "shell.end" && pending) {
500
+ const output = String(event.output ?? "");
501
+ if (output && !pending.sawChunk)
502
+ pending.onData(Buffer.from(output));
503
+ const index = this.pendingShells.indexOf(pending);
504
+ if (index !== -1)
505
+ this.pendingShells.splice(index, 1);
506
+ pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
507
+ }
508
+ }
509
+ settlePendingCompaction(eventValue) {
510
+ const event = recordOf(eventValue);
511
+ if (!event)
512
+ return;
513
+ const type = String(event.type ?? "");
514
+ if (type !== "compaction_end" || this.pendingCompactions.length === 0)
515
+ return;
516
+ const pending = this.pendingCompactions.shift();
517
+ const result = recordOf(event.result);
518
+ if (result)
519
+ pending.resolve(result);
520
+ else if (event.aborted === true)
521
+ pending.reject(new Error("Compaction aborted on the worker."));
656
522
  else
657
- for (const message of messages)
658
- applyMessage(state, message);
659
- applyStatus(state, statusPayload);
660
- const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
661
- state.commands = commands.flatMap((command) => {
662
- const record = recordOf(command);
663
- return typeof record?.name === "string" ? [`/${record.name}`] : [];
523
+ pending.resolve({});
524
+ }
525
+ }
526
+
527
+ class RigRemoteAgentSession extends PiAgentSession {
528
+ remote;
529
+ constructor(config, remote) {
530
+ super(config);
531
+ this.remote = remote;
532
+ remote.bindSession(this);
533
+ }
534
+ handleRemoteSessionEvent(eventValue) {
535
+ const event = recordOf(eventValue);
536
+ if (!event)
537
+ return;
538
+ const type = String(event.type ?? "");
539
+ if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
540
+ this.agent.state.messages = [...this.agent.state.messages, event.message];
541
+ }
542
+ this._emit(eventValue);
543
+ }
544
+ replaceRemoteMessages(messages) {
545
+ this.agent.state.messages = messages;
546
+ }
547
+ async prompt(text, options) {
548
+ const trimmed = text.trim();
549
+ if (!trimmed)
550
+ return;
551
+ if (trimmed.startsWith("/")) {
552
+ if (await this._tryExecuteExtensionCommand(trimmed))
553
+ return;
554
+ await this.remote.sendCommand(trimmed);
555
+ return;
556
+ }
557
+ if (trimmed.startsWith("!")) {
558
+ await this.remote.sendShell(trimmed);
559
+ return;
560
+ }
561
+ const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
562
+ options?.preflightResult?.(true);
563
+ await this.remote.sendPrompt(trimmed, behavior);
564
+ }
565
+ async steer(text) {
566
+ const trimmed = text.trim();
567
+ if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
568
+ return;
569
+ await this.remote.sendPrompt(trimmed, "steer");
570
+ }
571
+ async followUp(text) {
572
+ const trimmed = text.trim();
573
+ if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
574
+ return;
575
+ await this.remote.sendPrompt(trimmed, "followUp");
576
+ }
577
+ async abort() {
578
+ await this.remote.abort();
579
+ }
580
+ async compact(customInstructions) {
581
+ const pending = new Promise((resolve3, reject) => {
582
+ this.remote.registerPendingCompaction({ resolve: resolve3, reject });
664
583
  });
665
- registerDaemonCommandsNatively(pi, options, ctx, state, commands, registeredDaemonCommands);
666
- catchupDone = true;
667
- for (const payload of buffered.splice(0))
668
- applyEnvelope(ctx, state, payload);
669
- updatePiUi(ctx, state);
670
- } catch (error) {
671
- appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
672
- catchupDone = true;
673
- updatePiUi(ctx, state);
584
+ await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
585
+ return pending;
586
+ }
587
+ clearQueue() {
588
+ const cleared = {
589
+ steering: [...this.remote.status.steeringMessages],
590
+ followUp: [...this.remote.status.followUpMessages]
591
+ };
592
+ this.remote.status.steeringMessages = [];
593
+ this.remote.status.followUpMessages = [];
594
+ this.remote.status.pendingMessageCount = 0;
595
+ this.remote.sendCommand("/queue-clear").catch(() => {});
596
+ return cleared;
597
+ }
598
+ get isStreaming() {
599
+ return this.remote.status.isStreaming;
600
+ }
601
+ get isCompacting() {
602
+ return this.remote.status.isCompacting;
603
+ }
604
+ get isBashRunning() {
605
+ return this.remote.status.isBashRunning;
606
+ }
607
+ get pendingMessageCount() {
608
+ return this.remote.status.pendingMessageCount;
609
+ }
610
+ getSteeringMessages() {
611
+ return this.remote.status.steeringMessages;
612
+ }
613
+ getFollowUpMessages() {
614
+ return this.remote.status.followUpMessages;
615
+ }
616
+ get model() {
617
+ return this.remote.status.model ?? super.model;
618
+ }
619
+ async setModel(model) {
620
+ await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
621
+ this.remote.status.model = model;
622
+ }
623
+ get thinkingLevel() {
624
+ return this.remote.status.thinkingLevel ?? super.thinkingLevel;
625
+ }
626
+ setThinkingLevel(level) {
627
+ this.remote.status.thinkingLevel = level;
628
+ this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
629
+ }
630
+ get sessionName() {
631
+ return this.remote.status.sessionName ?? super.sessionName;
632
+ }
633
+ setSessionName(name) {
634
+ this.remote.status.sessionName = name;
635
+ this.remote.sendCommand(`/name ${name}`).catch(() => {});
636
+ }
637
+ getSessionStats() {
638
+ return this.remote.status.stats ?? super.getSessionStats();
639
+ }
640
+ getContextUsage() {
641
+ return this.remote.status.contextUsage ?? super.getContextUsage();
642
+ }
643
+ dispose() {
644
+ this.remote.close();
645
+ super.dispose();
674
646
  }
675
- await closePromise;
676
647
  }
677
- function createRemoteBashOperations(options, state, excludeFromContext) {
648
+ function createRemoteBashOperations(controller, excludeFromContext) {
678
649
  return {
679
650
  exec(command, _cwd, execOptions) {
680
651
  return new Promise((resolve3, reject) => {
681
- const pending = {
682
- command,
683
- onData: execOptions.onData,
684
- resolve: resolve3,
685
- reject,
686
- sawChunk: false
687
- };
652
+ const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
688
653
  const cleanup = () => {
689
654
  execOptions.signal?.removeEventListener("abort", onAbort);
690
655
  if (timer)
@@ -692,12 +657,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
692
657
  };
693
658
  const onAbort = () => {
694
659
  cleanup();
695
- failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
660
+ controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
696
661
  };
697
662
  const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
698
663
  const timer = timeoutMs > 0 ? setTimeout(() => {
699
664
  cleanup();
700
- failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
665
+ controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
701
666
  }, timeoutMs) : null;
702
667
  const wrappedResolve = pending.resolve;
703
668
  const wrappedReject = pending.reject;
@@ -710,125 +675,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
710
675
  wrappedReject(error);
711
676
  };
712
677
  execOptions.signal?.addEventListener("abort", onAbort, { once: true });
713
- state.pendingShells.push(pending);
714
- sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
678
+ controller.registerPendingShell(pending);
679
+ controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
715
680
  cleanup();
716
- failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
681
+ controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
717
682
  });
718
683
  });
719
684
  }
720
685
  };
721
686
  }
722
- async function answerPendingUi(options, state, line) {
723
- const pending = state.pendingUi;
724
- if (!pending)
725
- return false;
726
- if (line === "/cancel") {
727
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
728
- } else if (pending.method === "confirm") {
729
- const confirmed = /^(y|yes|true|1)$/i.test(line);
730
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
731
- } else if (pending.options.length > 0 && /^\d+$/.test(line)) {
732
- const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
733
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
734
- } else {
735
- await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
736
- }
737
- appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
738
- state.pendingUi = null;
739
- return true;
740
- }
741
- async function routeInput(options, ctx, state, line) {
742
- const text = line.trim();
743
- if (!text)
744
- return;
745
- if (await answerPendingUi(options, state, text)) {
746
- updatePiUi(ctx, state);
747
- return;
748
- }
749
- if (text === "/detach" || text === "/quit" || text === "/q") {
750
- appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
751
- updatePiUi(ctx, state);
752
- ctx.shutdown();
753
- return;
754
- }
755
- if (text === "/stop") {
756
- await abortRunPiViaServer(options.context, options.runId);
757
- appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
758
- updatePiUi(ctx, state);
759
- ctx.shutdown();
760
- return;
761
- }
762
- if (text.startsWith("!")) {
763
- appendTranscript(state, "You", text);
764
- await sendRunPiShellViaServer(options.context, options.runId, text);
765
- } else if (text.startsWith("/")) {
766
- appendTranscript(state, "You", text);
767
- const result = await runRunPiCommandViaServer(options.context, options.runId, text);
768
- const message = typeof result.message === "string" ? result.message : "worker command accepted";
769
- appendTranscript(state, "System", message);
770
- } else {
771
- appendTranscript(state, "You", text);
772
- await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
773
- }
774
- updatePiUi(ctx, state);
687
+
688
+ // packages/cli/src/commands/_pi-worker-bridge-extension.ts
689
+ function recordOf2(value) {
690
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
691
+ }
692
+ function asText(value) {
693
+ if (typeof value === "string")
694
+ return value;
695
+ if (value === null || value === undefined)
696
+ return "";
697
+ if (typeof value === "number" || typeof value === "boolean")
698
+ return String(value);
699
+ try {
700
+ return JSON.stringify(value);
701
+ } catch {
702
+ return String(value);
703
+ }
704
+ }
705
+ async function answerExtensionUiRequest(options, ctx, request) {
706
+ const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
707
+ const method = String(request.method ?? request.type ?? "input");
708
+ const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
709
+ const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
710
+ const choices = rawOptions.map((option) => {
711
+ const record = recordOf2(option);
712
+ return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
713
+ }).filter(Boolean);
714
+ try {
715
+ if (method === "confirm") {
716
+ const confirmed = await ctx.ui.confirm("Worker request", prompt);
717
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
718
+ return;
719
+ }
720
+ if (choices.length > 0) {
721
+ const selected = await ctx.ui.select(prompt, choices);
722
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
723
+ return;
724
+ }
725
+ const value = await ctx.ui.input("Worker request", prompt);
726
+ await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
727
+ } catch (error) {
728
+ ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
729
+ }
730
+ }
731
+ var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
732
+ function registerDaemonCommands(pi, options, ctx, commands, registered) {
733
+ for (const command of commands) {
734
+ const record = recordOf2(command);
735
+ const name = typeof record?.name === "string" ? record.name : "";
736
+ const source = typeof record?.source === "string" ? record.source : "worker";
737
+ if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
738
+ continue;
739
+ registered.add(name);
740
+ const description = typeof record?.description === "string" ? record.description : undefined;
741
+ try {
742
+ pi.registerCommand(name, {
743
+ description: `[worker ${source}] ${description ?? ""}`.trim(),
744
+ handler: async (args) => {
745
+ try {
746
+ const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
747
+ ctx.ui.notify(message, "info");
748
+ } catch (error) {
749
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
750
+ }
751
+ }
752
+ });
753
+ } catch {}
754
+ }
775
755
  }
776
756
  function createRigWorkerPiBridgeExtension(options) {
777
757
  return (pi) => {
778
- const state = {
779
- transcript: [],
780
- status: "starting worker Pi daemon bridge",
781
- activity: "",
782
- cwd: "",
783
- model: "",
784
- commands: [],
785
- streaming: false,
786
- pendingUi: null,
787
- pendingShells: [],
788
- wsConnected: false,
789
- nativeStream: false
790
- };
791
- if (options.initialMessageSent)
792
- appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
793
758
  const registeredDaemonCommands = new Set;
794
- let nativePiUiContextAvailable = false;
795
- pi.on("user_bash", (event) => {
796
- state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
797
- return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
759
+ pi.registerCommand("detach", {
760
+ description: "Detach from this run; the worker keeps going",
761
+ handler: async (_args, ctx) => {
762
+ ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
763
+ ctx.shutdown();
764
+ }
798
765
  });
766
+ pi.registerCommand("stop", {
767
+ description: "Stop the worker Pi run and detach",
768
+ handler: async (_args, ctx) => {
769
+ await options.controller.abort();
770
+ ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
771
+ ctx.shutdown();
772
+ }
773
+ });
774
+ pi.on("user_bash", (event) => ({
775
+ operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
776
+ }));
799
777
  pi.on("session_start", async (_event, ctx) => {
800
- nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
801
- state.nativeStream = nativePiUiContextAvailable;
802
- updatePiUi(ctx, state);
803
- 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");
804
- ctx.ui.onTerminalInput((data) => {
805
- if (data.includes("\x04")) {
806
- ctx.shutdown();
807
- return { consume: true };
778
+ ctx.ui.setTitle("Rig \xB7 worker session");
779
+ ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
780
+ ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
781
+ if (options.initialMessageSent)
782
+ ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
783
+ const nativeUi = ctx.ui;
784
+ options.controller.setUiHooks({
785
+ onStatusText: (text) => ctx.ui.setStatus("rig-worker-pi", text),
786
+ onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
787
+ onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
788
+ onError: (message) => ctx.ui.notify(message, "error"),
789
+ onExtensionUiRequest: (request) => {
790
+ answerExtensionUiRequest(options, ctx, request);
791
+ },
792
+ onCatchUp: (messages, commands) => {
793
+ if (nativeUi.appendSessionMessages)
794
+ nativeUi.appendSessionMessages(messages);
795
+ const cwd = options.controller.status.cwd;
796
+ if (nativeUi.setDisplayCwd && cwd)
797
+ nativeUi.setDisplayCwd(cwd);
798
+ registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
808
799
  }
809
- if (!data.includes("\r") && !data.includes(`
810
- `))
811
- return;
812
- const inlineText = data.replace(/[\r\n]+/g, "").trim();
813
- const editorText = ctx.ui.getEditorText().trim();
814
- const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
815
- if (!text)
816
- return;
817
- if (text.startsWith("!"))
818
- return;
819
- ctx.ui.setEditorText("");
820
- routeInput(options, ctx, state, text).catch((error) => {
821
- appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
822
- updatePiUi(ctx, state);
823
- });
824
- return { consume: true };
825
800
  });
826
- connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands).catch((error) => {
827
- appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
828
- updatePiUi(ctx, state);
801
+ options.controller.connect().catch((error) => {
802
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
829
803
  });
830
804
  });
831
- pi.on("session_shutdown", () => {});
805
+ pi.on("session_shutdown", () => {
806
+ options.controller.close();
807
+ });
832
808
  };
833
809
  }
834
810
 
@@ -849,43 +825,47 @@ function setTemporaryEnv(updates) {
849
825
  };
850
826
  }
851
827
  async function attachRunBundledPiFrontend(context, input) {
852
- const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
853
- const cwd = join(tempRoot, "workspace");
854
- const agentDir = join(tempRoot, "agent");
855
- const sessionDir = join(tempRoot, "sessions");
856
- const previousCwd = process.cwd();
828
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
857
829
  const restoreEnv = setTemporaryEnv({
858
- PI_CODING_AGENT_DIR: agentDir,
859
- PI_CODING_AGENT_SESSION_DIR: sessionDir,
860
- PI_OFFLINE: "1",
830
+ PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
861
831
  PI_SKIP_VERSION_CHECK: "1"
862
832
  });
833
+ const controller = new RigRemoteSessionController({ context, runId: input.runId });
834
+ const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
835
+ const services = await createAgentSessionServices({
836
+ cwd,
837
+ agentDir,
838
+ resourceLoaderOptions: {
839
+ extensionFactories: [
840
+ createRigWorkerPiBridgeExtension({
841
+ context,
842
+ controller,
843
+ runId: input.runId,
844
+ initialMessageSent: input.steered === true
845
+ })
846
+ ],
847
+ noContextFiles: true
848
+ }
849
+ });
850
+ const created = await createAgentSessionFromServices({
851
+ services,
852
+ sessionManager,
853
+ sessionStartEvent,
854
+ noTools: "all",
855
+ sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
856
+ });
857
+ return { ...created, services, diagnostics: services.diagnostics };
858
+ };
863
859
  let detached = false;
864
860
  try {
865
- await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
866
- process.chdir(cwd);
867
- await runPiMain([
868
- "--offline",
869
- "--no-session",
870
- "--no-tools",
871
- "--no-builtin-tools",
872
- "--no-skills",
873
- "--no-context-files",
874
- "--no-approve"
875
- ], {
876
- extensionFactories: [
877
- createRigWorkerPiBridgeExtension({
878
- context,
879
- runId: input.runId,
880
- initialMessageSent: input.steered === true
881
- })
882
- ]
861
+ await runPiMain([], {
862
+ createRuntimeOverride: () => createRemoteRuntime
883
863
  });
884
864
  detached = true;
885
865
  } finally {
886
- process.chdir(previousCwd);
887
866
  restoreEnv();
888
- rmSync(tempRoot, { recursive: true, force: true });
867
+ controller.close();
868
+ rmSync(tempSessionDir, { recursive: true, force: true });
889
869
  }
890
870
  let run = { runId: input.runId, status: "unknown" };
891
871
  try {
@@ -898,7 +878,7 @@ async function attachRunBundledPiFrontend(context, input) {
898
878
  timelineCursor: null,
899
879
  steered: input.steered === true,
900
880
  detached,
901
- rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
881
+ rendered: "native bundled Pi frontend with remote worker session runtime"
902
882
  };
903
883
  }
904
884
  export {