@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/bin/rig.js +506 -551
- package/dist/src/commands/_operator-view.js +504 -530
- package/dist/src/commands/_pi-frontend.js +508 -534
- package/dist/src/commands/_pi-remote-session.js +665 -0
- package/dist/src/commands/_pi-worker-bridge-extension.js +352 -502
- package/dist/src/commands/_run-driver-helpers.js +2 -21
- package/dist/src/commands/run.js +504 -530
- package/dist/src/commands/task-run-driver.js +2 -21
- package/dist/src/commands/task.js +504 -530
- package/dist/src/commands.js +506 -551
- package/dist/src/index.js +506 -551
- package/package.json +6 -6
|
@@ -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 {
|
|
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,388 @@ async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
|
258
262
|
return url.toString();
|
|
259
263
|
}
|
|
260
264
|
|
|
261
|
-
// packages/cli/src/commands/_pi-
|
|
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
|
-
|
|
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
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
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
|
-
|
|
621
|
-
|
|
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 =
|
|
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(
|
|
631
|
-
updatePiUi(ctx, state);
|
|
632
|
-
}
|
|
348
|
+
else
|
|
349
|
+
this.applyEnvelope(payload);
|
|
633
350
|
} catch (error) {
|
|
634
|
-
|
|
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
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
resolve3();
|
|
356
|
+
this.hooks.onConnectionChange?.(false);
|
|
357
|
+
if (!this.closed)
|
|
358
|
+
this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
|
|
644
359
|
};
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
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
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
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
|
+
await this.remote.sendPrompt(text, "steer");
|
|
567
|
+
}
|
|
568
|
+
async followUp(text) {
|
|
569
|
+
await this.remote.sendPrompt(text, "followUp");
|
|
570
|
+
}
|
|
571
|
+
async abort() {
|
|
572
|
+
await this.remote.abort();
|
|
573
|
+
}
|
|
574
|
+
async compact(customInstructions) {
|
|
575
|
+
const pending = new Promise((resolve3, reject) => {
|
|
576
|
+
this.remote.registerPendingCompaction({ resolve: resolve3, reject });
|
|
664
577
|
});
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
578
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
579
|
+
return pending;
|
|
580
|
+
}
|
|
581
|
+
clearQueue() {
|
|
582
|
+
const cleared = {
|
|
583
|
+
steering: [...this.remote.status.steeringMessages],
|
|
584
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
585
|
+
};
|
|
586
|
+
this.remote.status.steeringMessages = [];
|
|
587
|
+
this.remote.status.followUpMessages = [];
|
|
588
|
+
this.remote.status.pendingMessageCount = 0;
|
|
589
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
590
|
+
return cleared;
|
|
591
|
+
}
|
|
592
|
+
get isStreaming() {
|
|
593
|
+
return this.remote.status.isStreaming;
|
|
594
|
+
}
|
|
595
|
+
get isCompacting() {
|
|
596
|
+
return this.remote.status.isCompacting;
|
|
597
|
+
}
|
|
598
|
+
get isBashRunning() {
|
|
599
|
+
return this.remote.status.isBashRunning;
|
|
600
|
+
}
|
|
601
|
+
get pendingMessageCount() {
|
|
602
|
+
return this.remote.status.pendingMessageCount;
|
|
603
|
+
}
|
|
604
|
+
getSteeringMessages() {
|
|
605
|
+
return this.remote.status.steeringMessages;
|
|
606
|
+
}
|
|
607
|
+
getFollowUpMessages() {
|
|
608
|
+
return this.remote.status.followUpMessages;
|
|
609
|
+
}
|
|
610
|
+
get model() {
|
|
611
|
+
return this.remote.status.model ?? super.model;
|
|
612
|
+
}
|
|
613
|
+
async setModel(model) {
|
|
614
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
615
|
+
this.remote.status.model = model;
|
|
616
|
+
}
|
|
617
|
+
get thinkingLevel() {
|
|
618
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
619
|
+
}
|
|
620
|
+
setThinkingLevel(level) {
|
|
621
|
+
this.remote.status.thinkingLevel = level;
|
|
622
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
623
|
+
}
|
|
624
|
+
get sessionName() {
|
|
625
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
626
|
+
}
|
|
627
|
+
setSessionName(name) {
|
|
628
|
+
this.remote.status.sessionName = name;
|
|
629
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
630
|
+
}
|
|
631
|
+
getSessionStats() {
|
|
632
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
633
|
+
}
|
|
634
|
+
getContextUsage() {
|
|
635
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
636
|
+
}
|
|
637
|
+
dispose() {
|
|
638
|
+
this.remote.close();
|
|
639
|
+
super.dispose();
|
|
674
640
|
}
|
|
675
|
-
await closePromise;
|
|
676
641
|
}
|
|
677
|
-
function createRemoteBashOperations(
|
|
642
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
678
643
|
return {
|
|
679
644
|
exec(command, _cwd, execOptions) {
|
|
680
645
|
return new Promise((resolve3, reject) => {
|
|
681
|
-
const pending = {
|
|
682
|
-
command,
|
|
683
|
-
onData: execOptions.onData,
|
|
684
|
-
resolve: resolve3,
|
|
685
|
-
reject,
|
|
686
|
-
sawChunk: false
|
|
687
|
-
};
|
|
646
|
+
const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
|
|
688
647
|
const cleanup = () => {
|
|
689
648
|
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
690
649
|
if (timer)
|
|
@@ -692,12 +651,12 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
692
651
|
};
|
|
693
652
|
const onAbort = () => {
|
|
694
653
|
cleanup();
|
|
695
|
-
failPendingShell(
|
|
654
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
696
655
|
};
|
|
697
656
|
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
698
657
|
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
699
658
|
cleanup();
|
|
700
|
-
failPendingShell(
|
|
659
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
701
660
|
}, timeoutMs) : null;
|
|
702
661
|
const wrappedResolve = pending.resolve;
|
|
703
662
|
const wrappedReject = pending.reject;
|
|
@@ -710,125 +669,136 @@ function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
|
710
669
|
wrappedReject(error);
|
|
711
670
|
};
|
|
712
671
|
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
713
|
-
|
|
714
|
-
|
|
672
|
+
controller.registerPendingShell(pending);
|
|
673
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
715
674
|
cleanup();
|
|
716
|
-
failPendingShell(
|
|
675
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
717
676
|
});
|
|
718
677
|
});
|
|
719
678
|
}
|
|
720
679
|
};
|
|
721
680
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
const
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
return;
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
681
|
+
|
|
682
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
683
|
+
function recordOf2(value) {
|
|
684
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
685
|
+
}
|
|
686
|
+
function asText(value) {
|
|
687
|
+
if (typeof value === "string")
|
|
688
|
+
return value;
|
|
689
|
+
if (value === null || value === undefined)
|
|
690
|
+
return "";
|
|
691
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
692
|
+
return String(value);
|
|
693
|
+
try {
|
|
694
|
+
return JSON.stringify(value);
|
|
695
|
+
} catch {
|
|
696
|
+
return String(value);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
700
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
701
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
702
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
703
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
704
|
+
const choices = rawOptions.map((option) => {
|
|
705
|
+
const record = recordOf2(option);
|
|
706
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
707
|
+
}).filter(Boolean);
|
|
708
|
+
try {
|
|
709
|
+
if (method === "confirm") {
|
|
710
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
711
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
if (choices.length > 0) {
|
|
715
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
716
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
720
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
721
|
+
} catch (error) {
|
|
722
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
726
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
727
|
+
for (const command of commands) {
|
|
728
|
+
const record = recordOf2(command);
|
|
729
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
730
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
731
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
732
|
+
continue;
|
|
733
|
+
registered.add(name);
|
|
734
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
735
|
+
try {
|
|
736
|
+
pi.registerCommand(name, {
|
|
737
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
738
|
+
handler: async (args) => {
|
|
739
|
+
try {
|
|
740
|
+
const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
741
|
+
ctx.ui.notify(message, "info");
|
|
742
|
+
} catch (error) {
|
|
743
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
});
|
|
747
|
+
} catch {}
|
|
748
|
+
}
|
|
775
749
|
}
|
|
776
750
|
function createRigWorkerPiBridgeExtension(options) {
|
|
777
751
|
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
752
|
const registeredDaemonCommands = new Set;
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
753
|
+
pi.registerCommand("detach", {
|
|
754
|
+
description: "Detach from this run; the worker keeps going",
|
|
755
|
+
handler: async (_args, ctx) => {
|
|
756
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
757
|
+
ctx.shutdown();
|
|
758
|
+
}
|
|
798
759
|
});
|
|
760
|
+
pi.registerCommand("stop", {
|
|
761
|
+
description: "Stop the worker Pi run and detach",
|
|
762
|
+
handler: async (_args, ctx) => {
|
|
763
|
+
await options.controller.abort();
|
|
764
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
765
|
+
ctx.shutdown();
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
pi.on("user_bash", (event) => ({
|
|
769
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
770
|
+
}));
|
|
799
771
|
pi.on("session_start", async (_event, ctx) => {
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
772
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
773
|
+
ctx.ui.setStatus("rig-worker-pi", "connecting to worker session");
|
|
774
|
+
ctx.ui.notify(`Attached to Rig run ${options.runId}. Native Pi, remote brain \u2014 /detach exits, /stop cancels the run.`, "info");
|
|
775
|
+
if (options.initialMessageSent)
|
|
776
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
777
|
+
const nativeUi = ctx.ui;
|
|
778
|
+
options.controller.setUiHooks({
|
|
779
|
+
onStatusText: (text) => ctx.ui.setStatus("rig-worker-pi", text),
|
|
780
|
+
onActivity: (label, detail) => ctx.ui.setStatus("rig-worker-pi", [label, detail].filter(Boolean).join(" \u2014 ")),
|
|
781
|
+
onConnectionChange: (connected) => ctx.ui.setStatus("rig-worker-pi", connected ? "worker session live" : "worker session disconnected"),
|
|
782
|
+
onError: (message) => ctx.ui.notify(message, "error"),
|
|
783
|
+
onExtensionUiRequest: (request) => {
|
|
784
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
785
|
+
},
|
|
786
|
+
onCatchUp: (messages, commands) => {
|
|
787
|
+
if (nativeUi.appendSessionMessages)
|
|
788
|
+
nativeUi.appendSessionMessages(messages);
|
|
789
|
+
const cwd = options.controller.status.cwd;
|
|
790
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
791
|
+
nativeUi.setDisplayCwd(cwd);
|
|
792
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
808
793
|
}
|
|
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
794
|
});
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
updatePiUi(ctx, state);
|
|
795
|
+
options.controller.connect().catch((error) => {
|
|
796
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
829
797
|
});
|
|
830
798
|
});
|
|
831
|
-
pi.on("session_shutdown", () => {
|
|
799
|
+
pi.on("session_shutdown", () => {
|
|
800
|
+
options.controller.close();
|
|
801
|
+
});
|
|
832
802
|
};
|
|
833
803
|
}
|
|
834
804
|
|
|
@@ -849,43 +819,47 @@ function setTemporaryEnv(updates) {
|
|
|
849
819
|
};
|
|
850
820
|
}
|
|
851
821
|
async function attachRunBundledPiFrontend(context, input) {
|
|
852
|
-
const
|
|
853
|
-
const cwd = join(tempRoot, "workspace");
|
|
854
|
-
const agentDir = join(tempRoot, "agent");
|
|
855
|
-
const sessionDir = join(tempRoot, "sessions");
|
|
856
|
-
const previousCwd = process.cwd();
|
|
822
|
+
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
857
823
|
const restoreEnv = setTemporaryEnv({
|
|
858
|
-
|
|
859
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
860
|
-
PI_OFFLINE: "1",
|
|
824
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
861
825
|
PI_SKIP_VERSION_CHECK: "1"
|
|
862
826
|
});
|
|
827
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
828
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
829
|
+
const services = await createAgentSessionServices({
|
|
830
|
+
cwd,
|
|
831
|
+
agentDir,
|
|
832
|
+
resourceLoaderOptions: {
|
|
833
|
+
extensionFactories: [
|
|
834
|
+
createRigWorkerPiBridgeExtension({
|
|
835
|
+
context,
|
|
836
|
+
controller,
|
|
837
|
+
runId: input.runId,
|
|
838
|
+
initialMessageSent: input.steered === true
|
|
839
|
+
})
|
|
840
|
+
],
|
|
841
|
+
noContextFiles: true
|
|
842
|
+
}
|
|
843
|
+
});
|
|
844
|
+
const created = await createAgentSessionFromServices({
|
|
845
|
+
services,
|
|
846
|
+
sessionManager,
|
|
847
|
+
sessionStartEvent,
|
|
848
|
+
noTools: "all",
|
|
849
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
850
|
+
});
|
|
851
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
852
|
+
};
|
|
863
853
|
let detached = false;
|
|
864
854
|
try {
|
|
865
|
-
await
|
|
866
|
-
|
|
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
|
-
]
|
|
855
|
+
await runPiMain([], {
|
|
856
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
883
857
|
});
|
|
884
858
|
detached = true;
|
|
885
859
|
} finally {
|
|
886
|
-
process.chdir(previousCwd);
|
|
887
860
|
restoreEnv();
|
|
888
|
-
|
|
861
|
+
controller.close();
|
|
862
|
+
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
889
863
|
}
|
|
890
864
|
let run = { runId: input.runId, status: "unknown" };
|
|
891
865
|
try {
|
|
@@ -898,7 +872,7 @@ async function attachRunBundledPiFrontend(context, input) {
|
|
|
898
872
|
timelineCursor: null,
|
|
899
873
|
steered: input.steered === true,
|
|
900
874
|
detached,
|
|
901
|
-
rendered: "
|
|
875
|
+
rendered: "native bundled Pi frontend with remote worker session runtime"
|
|
902
876
|
};
|
|
903
877
|
}
|
|
904
878
|
export {
|