@h-rig/cli 0.0.6-alpha.64 → 0.0.6-alpha.66

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.
Files changed (46) hide show
  1. package/dist/bin/rig.js +1349 -1599
  2. package/dist/src/commands/_connection-state.js +14 -5
  3. package/dist/src/commands/_doctor-checks.js +71 -11
  4. package/dist/src/commands/_help-catalog.js +99 -60
  5. package/dist/src/commands/_json-output.js +56 -0
  6. package/dist/src/commands/_operator-view.js +97 -784
  7. package/dist/src/commands/_parsers.js +18 -9
  8. package/dist/src/commands/_pi-frontend.js +96 -788
  9. package/dist/src/commands/_policy.js +12 -3
  10. package/dist/src/commands/_preflight.js +73 -13
  11. package/dist/src/commands/_run-driver-helpers.js +31 -5
  12. package/dist/src/commands/_run-replay.js +2 -2
  13. package/dist/src/commands/_server-client.js +76 -16
  14. package/dist/src/commands/_snapshot-upload.js +70 -10
  15. package/dist/src/commands/agent.js +21 -11
  16. package/dist/src/commands/browser.js +24 -15
  17. package/dist/src/commands/connect.js +22 -17
  18. package/dist/src/commands/dist.js +15 -6
  19. package/dist/src/commands/doctor.js +70 -10
  20. package/dist/src/commands/github.js +79 -19
  21. package/dist/src/commands/inbox.js +215 -131
  22. package/dist/src/commands/init.js +202 -35
  23. package/dist/src/commands/inspect.js +77 -17
  24. package/dist/src/commands/inspector.js +18 -9
  25. package/dist/src/commands/pi.js +18 -9
  26. package/dist/src/commands/plugin.js +19 -10
  27. package/dist/src/commands/profile-and-review.js +22 -13
  28. package/dist/src/commands/queue.js +19 -9
  29. package/dist/src/commands/remote.js +25 -16
  30. package/dist/src/commands/repo-git-harness.js +18 -9
  31. package/dist/src/commands/run.js +158 -805
  32. package/dist/src/commands/server.js +85 -25
  33. package/dist/src/commands/setup.js +73 -13
  34. package/dist/src/commands/stats.js +681 -0
  35. package/dist/src/commands/task-report-bug.js +24 -15
  36. package/dist/src/commands/task-run-driver.js +121 -49
  37. package/dist/src/commands/task.js +254 -893
  38. package/dist/src/commands/test.js +12 -3
  39. package/dist/src/commands/workspace.js +14 -5
  40. package/dist/src/commands.js +1339 -1650
  41. package/dist/src/index.js +1349 -1599
  42. package/dist/src/launcher.js +72 -10
  43. package/dist/src/runner.js +14 -5
  44. package/package.json +10 -7
  45. package/dist/src/commands/_pi-remote-session.js +0 -771
  46. package/dist/src/commands/_pi-worker-bridge-extension.js +0 -834
@@ -3,11 +3,8 @@
3
3
  import { mkdtempSync, rmSync } from "fs";
4
4
  import { tmpdir } from "os";
5
5
  import { join } from "path";
6
- import {
7
- createAgentSessionFromServices,
8
- createAgentSessionServices,
9
- main as runPiMain
10
- } from "@earendil-works/pi-coding-agent";
6
+ import { main as runPiMain } from "@earendil-works/pi-coding-agent";
7
+ import createPiRigExtension from "@rig/pi-rig";
11
8
 
12
9
  // packages/cli/src/commands/_server-client.ts
13
10
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
@@ -15,10 +12,19 @@ import { resolve as resolve2 } from "path";
15
12
 
16
13
  // packages/cli/src/runner.ts
17
14
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
18
- import { CliError } from "@rig/runtime/control-plane/errors";
15
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
19
16
  import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
20
17
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
21
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
18
+
19
+ class CliError extends RuntimeCliError {
20
+ hint;
21
+ constructor(message, exitCode = 1, options = {}) {
22
+ super(message, exitCode);
23
+ if (options.hint?.trim()) {
24
+ this.hint = options.hint.trim();
25
+ }
26
+ }
27
+ }
22
28
 
23
29
  // packages/cli/src/commands/_server-client.ts
24
30
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
@@ -45,7 +51,7 @@ function readJsonFile(path) {
45
51
  try {
46
52
  return JSON.parse(readFileSync(path, "utf8"));
47
53
  } catch (error) {
48
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
54
+ throw new CliError(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1, { hint: "Fix or delete that file, then re-select a server with `rig server use <alias|local>`." });
49
55
  }
50
56
  }
51
57
  function writeJsonFile(path, value) {
@@ -109,7 +115,7 @@ function resolveSelectedConnection(projectRoot, options = {}) {
109
115
  const global = readGlobalConnections(options);
110
116
  const connection = global.connections[repo.selected];
111
117
  if (!connection) {
112
- throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
118
+ throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
113
119
  }
114
120
  return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
115
121
  }
@@ -182,7 +188,7 @@ async function ensureServerForCli(projectRoot) {
182
188
  };
183
189
  } catch (error) {
184
190
  if (error instanceof Error) {
185
- throw new CliError2(error.message, 1);
191
+ throw new CliError(error.message, 1);
186
192
  }
187
193
  throw error;
188
194
  }
@@ -232,15 +238,64 @@ function diagnosticMessage(payload) {
232
238
  });
233
239
  return messages.length > 0 ? messages.join("; ") : null;
234
240
  }
241
+ var serverReachabilityCache = new Map;
242
+ async function probeServerReachability(baseUrl, authToken) {
243
+ try {
244
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
245
+ headers: mergeHeaders(undefined, authToken),
246
+ signal: AbortSignal.timeout(1500)
247
+ });
248
+ return response.ok;
249
+ } catch {
250
+ return false;
251
+ }
252
+ }
253
+ function cachedServerReachability(projectRoot, baseUrl, authToken) {
254
+ const key = resolve2(projectRoot);
255
+ const cached = serverReachabilityCache.get(key);
256
+ if (cached)
257
+ return cached;
258
+ const probe = probeServerReachability(baseUrl, authToken);
259
+ serverReachabilityCache.set(key, probe);
260
+ return probe;
261
+ }
262
+ function describeSelectedServer(projectRoot, server) {
263
+ try {
264
+ const selected = resolveSelectedConnection(projectRoot);
265
+ if (selected) {
266
+ return {
267
+ alias: selected.alias,
268
+ target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
269
+ };
270
+ }
271
+ } catch {}
272
+ return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
273
+ }
274
+ async function buildServerFailureContext(projectRoot, server) {
275
+ const { alias, target } = describeSelectedServer(projectRoot, server);
276
+ const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
277
+ const reachability = reachable ? "server is reachable" : "server is unreachable";
278
+ return {
279
+ contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
280
+ hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
281
+ };
282
+ }
235
283
  async function requestServerJson(context, pathname, init = {}) {
236
284
  const server = await ensureServerForCli(context.projectRoot);
237
285
  const headers = mergeHeaders(init.headers, server.authToken);
238
286
  if (server.serverProjectRoot)
239
287
  headers.set("x-rig-project-root", server.serverProjectRoot);
240
- const response = await fetch(`${server.baseUrl}${pathname}`, {
241
- ...init,
242
- headers
243
- });
288
+ let response;
289
+ try {
290
+ response = await fetch(`${server.baseUrl}${pathname}`, {
291
+ ...init,
292
+ headers
293
+ });
294
+ } catch (error) {
295
+ const failure = await buildServerFailureContext(context.projectRoot, server);
296
+ throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
297
+ ${failure.contextLine}`, 1, { hint: failure.hint });
298
+ }
244
299
  const text = await response.text();
245
300
  const payload = text.trim().length > 0 ? (() => {
246
301
  try {
@@ -252,7 +307,9 @@ async function requestServerJson(context, pathname, init = {}) {
252
307
  if (!response.ok) {
253
308
  const diagnostics = diagnosticMessage(payload);
254
309
  const detail = diagnostics ?? (text || response.statusText);
255
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
310
+ const failure = await buildServerFailureContext(context.projectRoot, server);
311
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
312
+ ${failure.contextLine}`, 1, { hint: failure.hint });
256
313
  }
257
314
  return payload;
258
315
  }
@@ -260,743 +317,6 @@ async function getRunDetailsViaServer(context, runId) {
260
317
  const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
261
318
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
262
319
  }
263
- async function getRunPiSessionViaServer(context, runId) {
264
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
265
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
266
- }
267
- async function getRunPiMessagesViaServer(context, runId) {
268
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
269
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
270
- }
271
- async function getRunPiStatusViaServer(context, runId) {
272
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
273
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
274
- }
275
- async function getRunPiCommandsViaServer(context, runId) {
276
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
277
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
278
- }
279
- async function getRunPiCapabilitiesViaServer(context, runId) {
280
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
281
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
282
- }
283
- async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
284
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
285
- method: "POST",
286
- headers: { "content-type": "application/json" },
287
- body: JSON.stringify({ text, streamingBehavior })
288
- });
289
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
290
- }
291
- async function sendRunPiShellViaServer(context, runId, text) {
292
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
293
- method: "POST",
294
- headers: { "content-type": "application/json" },
295
- body: JSON.stringify({ text })
296
- });
297
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
298
- }
299
- async function runRunPiCommandViaServer(context, runId, text) {
300
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
301
- method: "POST",
302
- headers: { "content-type": "application/json" },
303
- body: JSON.stringify({ text })
304
- });
305
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
306
- }
307
- async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
308
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
309
- method: "POST",
310
- headers: { "content-type": "application/json" },
311
- body: JSON.stringify({ requestId, ...valueOrCancel })
312
- });
313
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
314
- }
315
- async function abortRunPiViaServer(context, runId) {
316
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
317
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
318
- }
319
- async function buildRunPiEventsWebSocketUrl(context, runId) {
320
- const server = await ensureServerForCli(context.projectRoot);
321
- const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
322
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
323
- if (server.authToken)
324
- url.searchParams.set("token", server.authToken);
325
- if (server.serverProjectRoot)
326
- url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
327
- return url.toString();
328
- }
329
-
330
- // packages/cli/src/commands/_pi-remote-session.ts
331
- import { AgentSession as PiAgentSession, expandPromptTemplate } from "@earendil-works/pi-coding-agent";
332
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
333
- function defaultTransport() {
334
- return {
335
- getSession: getRunPiSessionViaServer,
336
- getMessages: getRunPiMessagesViaServer,
337
- getStatus: getRunPiStatusViaServer,
338
- getCommands: getRunPiCommandsViaServer,
339
- getCapabilities: getRunPiCapabilitiesViaServer,
340
- sendPrompt: sendRunPiPromptViaServer,
341
- sendShell: sendRunPiShellViaServer,
342
- runCommand: runRunPiCommandViaServer,
343
- abort: abortRunPiViaServer,
344
- buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
345
- };
346
- }
347
- function recordOf(value) {
348
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
349
- }
350
- function emptyRemoteStatus() {
351
- return {
352
- isStreaming: false,
353
- isCompacting: false,
354
- isBashRunning: false,
355
- pendingMessageCount: 0,
356
- steeringMessages: [],
357
- followUpMessages: [],
358
- model: null,
359
- thinkingLevel: null,
360
- sessionName: null,
361
- cwd: null,
362
- stats: null,
363
- contextUsage: null
364
- };
365
- }
366
- function resolveAttachReadyTimeoutMs() {
367
- const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
368
- return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
369
- }
370
-
371
- class RigRemoteSessionController {
372
- context;
373
- runId;
374
- status = emptyRemoteStatus();
375
- transport;
376
- hooks = {};
377
- session = null;
378
- socket = null;
379
- closed = false;
380
- pendingShells = [];
381
- pendingCompactions = [];
382
- constructor(input) {
383
- this.context = input.context;
384
- this.runId = input.runId;
385
- this.transport = input.transport ?? defaultTransport();
386
- }
387
- ingestEnvelope(envelopeValue) {
388
- this.applyEnvelope(envelopeValue);
389
- }
390
- bindSession(session) {
391
- this.session = session;
392
- }
393
- setUiHooks(hooks) {
394
- this.hooks = hooks;
395
- }
396
- async connect() {
397
- const ready = await this.waitForReady();
398
- if (!ready || this.closed)
399
- return;
400
- let catchupDone = false;
401
- const buffered = [];
402
- const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
403
- const socket = new WebSocket(wsUrl);
404
- this.socket = socket;
405
- socket.onopen = () => {
406
- this.hooks.onConnectionChange?.(true);
407
- this.hooks.onStatusText?.("worker session live");
408
- };
409
- socket.onmessage = (message) => {
410
- try {
411
- const payload = typeof message.data === "string" ? JSON.parse(message.data) : JSON.parse(Buffer.from(message.data).toString("utf8"));
412
- if (!catchupDone)
413
- buffered.push(payload);
414
- else
415
- this.applyEnvelope(payload);
416
- } catch (error) {
417
- this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
418
- }
419
- };
420
- socket.onerror = () => socket.close();
421
- socket.onclose = () => {
422
- this.hooks.onConnectionChange?.(false);
423
- if (!this.closed)
424
- this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
425
- };
426
- try {
427
- const [messagesPayload, statusPayload, commandsPayload, capabilitiesPayload] = await Promise.all([
428
- this.transport.getMessages(this.context, this.runId),
429
- this.transport.getStatus(this.context, this.runId),
430
- this.transport.getCommands(this.context, this.runId),
431
- this.transport.getCapabilities(this.context, this.runId).catch(() => ({ capabilities: null }))
432
- ]);
433
- const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
434
- this.applyStatusPayload(statusPayload);
435
- this.session?.replaceRemoteMessages(messages);
436
- const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
437
- const capabilities = capabilitiesPayload.capabilities && typeof capabilitiesPayload.capabilities === "object" && !Array.isArray(capabilitiesPayload.capabilities) ? capabilitiesPayload.capabilities : null;
438
- this.hooks.onCatchUp?.(messages, commands, capabilities);
439
- catchupDone = true;
440
- for (const payload of buffered.splice(0))
441
- this.applyEnvelope(payload);
442
- } catch (error) {
443
- catchupDone = true;
444
- this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
445
- }
446
- }
447
- close() {
448
- this.closed = true;
449
- this.socket?.close();
450
- for (const shell of this.pendingShells.splice(0))
451
- shell.reject(new Error("Remote session closed."));
452
- for (const compaction of this.pendingCompactions.splice(0))
453
- compaction.reject(new Error("Remote session closed."));
454
- }
455
- async sendPrompt(text, streamingBehavior) {
456
- await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
457
- }
458
- async sendCommand(text) {
459
- const result = await this.transport.runCommand(this.context, this.runId, text);
460
- return typeof result.message === "string" ? result.message : "worker command accepted";
461
- }
462
- async sendShell(text) {
463
- await this.transport.sendShell(this.context, this.runId, text);
464
- }
465
- async abort() {
466
- await this.transport.abort(this.context, this.runId);
467
- }
468
- registerPendingShell(shell) {
469
- this.pendingShells.push(shell);
470
- }
471
- failPendingShell(shell, error) {
472
- const index = this.pendingShells.indexOf(shell);
473
- if (index !== -1)
474
- this.pendingShells.splice(index, 1);
475
- shell.reject(error);
476
- }
477
- registerPendingCompaction(pending) {
478
- this.pendingCompactions.push(pending);
479
- }
480
- async waitForReady() {
481
- const startedAt = Date.now();
482
- const deadline = startedAt + resolveAttachReadyTimeoutMs();
483
- let consecutiveFailures = 0;
484
- while (!this.closed) {
485
- let requestFailed = false;
486
- const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
487
- requestFailed = true;
488
- return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
489
- });
490
- if (session.ready !== false)
491
- return true;
492
- consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
493
- const status = String(session.status ?? "starting");
494
- if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
495
- this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
496
- return false;
497
- }
498
- 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`);
499
- if (Date.now() >= deadline) {
500
- this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
501
- return false;
502
- }
503
- await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
504
- }
505
- return false;
506
- }
507
- applyEnvelope(envelopeValue) {
508
- const envelope = recordOf(envelopeValue);
509
- if (!envelope)
510
- return;
511
- const type = String(envelope.type ?? "");
512
- if (type === "status.update") {
513
- this.applyStatusPayload(envelope);
514
- return;
515
- }
516
- if (type === "activity.update") {
517
- const activity = recordOf(envelope.activity);
518
- this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
519
- return;
520
- }
521
- if (type === "extension_ui_request") {
522
- const request = recordOf(envelope.request);
523
- if (request)
524
- this.hooks.onExtensionUiRequest?.(request);
525
- return;
526
- }
527
- if (type === "pi.ui_event") {
528
- this.applyShellUiEvent(envelope.event);
529
- return;
530
- }
531
- if (type === "pi.event") {
532
- this.session?.handleRemoteSessionEvent(envelope.event);
533
- this.settlePendingCompaction(envelope.event);
534
- return;
535
- }
536
- if (type === "error") {
537
- this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
538
- }
539
- }
540
- applyStatusPayload(payload) {
541
- const status = recordOf(payload.status) ?? payload;
542
- const next = this.status;
543
- next.isStreaming = status.isStreaming === true;
544
- next.isCompacting = status.isCompacting === true;
545
- next.isBashRunning = status.isBashRunning === true;
546
- next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
547
- next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
548
- next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
549
- next.model = recordOf(status.model) ?? next.model;
550
- next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
551
- next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
552
- next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
553
- next.stats = recordOf(status.stats) ?? next.stats;
554
- next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
555
- }
556
- applyShellUiEvent(value) {
557
- const event = recordOf(value);
558
- if (!event)
559
- return;
560
- const type = String(event.type ?? "");
561
- const pending = this.pendingShells[0];
562
- if (type === "shell.chunk" && pending) {
563
- pending.sawChunk = true;
564
- pending.onData(Buffer.from(String(event.chunk ?? "")));
565
- return;
566
- }
567
- if (type === "shell.end" && pending) {
568
- const output = String(event.output ?? "");
569
- if (output && !pending.sawChunk)
570
- pending.onData(Buffer.from(output));
571
- const index = this.pendingShells.indexOf(pending);
572
- if (index !== -1)
573
- this.pendingShells.splice(index, 1);
574
- pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
575
- }
576
- }
577
- settlePendingCompaction(eventValue) {
578
- const event = recordOf(eventValue);
579
- if (!event)
580
- return;
581
- const type = String(event.type ?? "");
582
- if (type !== "compaction_end" || this.pendingCompactions.length === 0)
583
- return;
584
- const pending = this.pendingCompactions.shift();
585
- const result = recordOf(event.result);
586
- if (result)
587
- pending.resolve(result);
588
- else if (event.aborted === true)
589
- pending.reject(new Error("Compaction aborted on the worker."));
590
- else
591
- pending.resolve({});
592
- }
593
- }
594
-
595
- class RigRemoteAgentSession extends PiAgentSession {
596
- remote;
597
- constructor(config, remote) {
598
- super(config);
599
- this.remote = remote;
600
- remote.bindSession(this);
601
- }
602
- handleRemoteSessionEvent(eventValue) {
603
- const event = recordOf(eventValue);
604
- if (!event)
605
- return;
606
- const type = String(event.type ?? "");
607
- if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
608
- this.agent.state.messages = [...this.agent.state.messages, event.message];
609
- }
610
- this._emit(eventValue);
611
- }
612
- replaceRemoteMessages(messages) {
613
- this.agent.state.messages = messages;
614
- }
615
- async expandLocalInput(text) {
616
- let current = text;
617
- const runner = this.extensionRunner;
618
- if (runner.hasHandlers("input")) {
619
- const result = await runner.emitInput(current, undefined, "interactive");
620
- if (result.action === "handled")
621
- return null;
622
- if (result.action === "transform")
623
- current = result.text;
624
- }
625
- current = this._expandSkillCommand(current);
626
- current = expandPromptTemplate(current, [...this.promptTemplates]);
627
- return current;
628
- }
629
- async prompt(text, options) {
630
- const trimmed = text.trim();
631
- if (!trimmed)
632
- return;
633
- if (trimmed.startsWith("/")) {
634
- if (await this._tryExecuteExtensionCommand(trimmed))
635
- return;
636
- const expanded2 = await this.expandLocalInput(trimmed);
637
- if (expanded2 === null)
638
- return;
639
- if (expanded2 !== trimmed) {
640
- const behavior2 = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
641
- options?.preflightResult?.(true);
642
- await this.remote.sendPrompt(expanded2, behavior2);
643
- return;
644
- }
645
- await this.remote.sendCommand(trimmed);
646
- return;
647
- }
648
- if (trimmed.startsWith("!")) {
649
- await this.remote.sendShell(trimmed);
650
- return;
651
- }
652
- const expanded = await this.expandLocalInput(trimmed);
653
- if (expanded === null)
654
- return;
655
- const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
656
- options?.preflightResult?.(true);
657
- await this.remote.sendPrompt(expanded, behavior);
658
- }
659
- async steer(text) {
660
- const trimmed = text.trim();
661
- if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
662
- return;
663
- const expanded = await this.expandLocalInput(trimmed);
664
- if (expanded === null)
665
- return;
666
- await this.remote.sendPrompt(expanded, "steer");
667
- }
668
- async followUp(text) {
669
- const trimmed = text.trim();
670
- if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
671
- return;
672
- const expanded = await this.expandLocalInput(trimmed);
673
- if (expanded === null)
674
- return;
675
- await this.remote.sendPrompt(expanded, "followUp");
676
- }
677
- async abort() {
678
- await this.remote.abort();
679
- }
680
- async compact(customInstructions) {
681
- const pending = new Promise((resolve3, reject) => {
682
- this.remote.registerPendingCompaction({ resolve: resolve3, reject });
683
- });
684
- await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
685
- return pending;
686
- }
687
- clearQueue() {
688
- const cleared = {
689
- steering: [...this.remote.status.steeringMessages],
690
- followUp: [...this.remote.status.followUpMessages]
691
- };
692
- this.remote.status.steeringMessages = [];
693
- this.remote.status.followUpMessages = [];
694
- this.remote.status.pendingMessageCount = 0;
695
- this.remote.sendCommand("/queue-clear").catch(() => {});
696
- return cleared;
697
- }
698
- get isStreaming() {
699
- return this.remote.status.isStreaming;
700
- }
701
- get isCompacting() {
702
- return this.remote.status.isCompacting;
703
- }
704
- get isBashRunning() {
705
- return this.remote.status.isBashRunning;
706
- }
707
- get pendingMessageCount() {
708
- return this.remote.status.pendingMessageCount;
709
- }
710
- getSteeringMessages() {
711
- return this.remote.status.steeringMessages;
712
- }
713
- getFollowUpMessages() {
714
- return this.remote.status.followUpMessages;
715
- }
716
- get model() {
717
- return this.remote.status.model ?? super.model;
718
- }
719
- async setModel(model) {
720
- await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
721
- this.remote.status.model = model;
722
- }
723
- get thinkingLevel() {
724
- return this.remote.status.thinkingLevel ?? super.thinkingLevel;
725
- }
726
- setThinkingLevel(level) {
727
- this.remote.status.thinkingLevel = level;
728
- this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
729
- }
730
- get sessionName() {
731
- return this.remote.status.sessionName ?? super.sessionName;
732
- }
733
- setSessionName(name) {
734
- this.remote.status.sessionName = name;
735
- this.remote.sendCommand(`/name ${name}`).catch(() => {});
736
- }
737
- getSessionStats() {
738
- return this.remote.status.stats ?? super.getSessionStats();
739
- }
740
- getContextUsage() {
741
- return this.remote.status.contextUsage ?? super.getContextUsage();
742
- }
743
- dispose() {
744
- this.remote.close();
745
- super.dispose();
746
- }
747
- }
748
- function createRemoteBashOperations(controller, excludeFromContext) {
749
- return {
750
- exec(command, _cwd, execOptions) {
751
- return new Promise((resolve3, reject) => {
752
- const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
753
- const cleanup = () => {
754
- execOptions.signal?.removeEventListener("abort", onAbort);
755
- if (timer)
756
- clearTimeout(timer);
757
- };
758
- const onAbort = () => {
759
- cleanup();
760
- controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
761
- };
762
- const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
763
- const timer = timeoutMs > 0 ? setTimeout(() => {
764
- cleanup();
765
- controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
766
- }, timeoutMs) : null;
767
- const wrappedResolve = pending.resolve;
768
- const wrappedReject = pending.reject;
769
- pending.resolve = (result) => {
770
- cleanup();
771
- wrappedResolve(result);
772
- };
773
- pending.reject = (error) => {
774
- cleanup();
775
- wrappedReject(error);
776
- };
777
- execOptions.signal?.addEventListener("abort", onAbort, { once: true });
778
- controller.registerPendingShell(pending);
779
- controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
780
- cleanup();
781
- controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
782
- });
783
- });
784
- }
785
- };
786
- }
787
-
788
- // packages/cli/src/commands/_spinner.ts
789
- var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
790
-
791
- // packages/cli/src/commands/_pi-worker-bridge-extension.ts
792
- function recordOf2(value) {
793
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
794
- }
795
- function asText(value) {
796
- if (typeof value === "string")
797
- return value;
798
- if (value === null || value === undefined)
799
- return "";
800
- if (typeof value === "number" || typeof value === "boolean")
801
- return String(value);
802
- try {
803
- return JSON.stringify(value);
804
- } catch {
805
- return String(value);
806
- }
807
- }
808
- function names(value, key = "name") {
809
- if (!Array.isArray(value))
810
- return [];
811
- return value.flatMap((entry) => {
812
- if (typeof entry === "string")
813
- return [entry];
814
- const record = recordOf2(entry);
815
- const name = record?.[key];
816
- return typeof name === "string" ? [name] : [];
817
- });
818
- }
819
- function renderWorkerCapabilities(capabilities) {
820
- const lines = ["Worker session capabilities (in effect for this run)"];
821
- const tools = Array.isArray(capabilities.tools) ? capabilities.tools : [];
822
- const activeTools = tools.flatMap((tool) => {
823
- const record = recordOf2(tool);
824
- return record && record.active === true && typeof record.name === "string" ? [record.name] : [];
825
- });
826
- const inactiveCount = tools.length - activeTools.length;
827
- lines.push(` tools ${activeTools.join(", ") || "(none)"}${inactiveCount > 0 ? ` (+${inactiveCount} inactive)` : ""}`);
828
- const extensions = Array.isArray(capabilities.extensions) ? capabilities.extensions : [];
829
- const extensionLabels = extensions.flatMap((entry) => {
830
- const record = recordOf2(entry);
831
- if (!record)
832
- return [];
833
- const path = typeof record.path === "string" ? record.path : "";
834
- const short = path.split("/").filter(Boolean).slice(-2).join("/") || path || "extension";
835
- return [short];
836
- });
837
- lines.push(` extensions ${extensionLabels.join(", ") || "(none)"}`);
838
- const hookEvents = names(capabilities.hookEvents);
839
- const hookList = Array.isArray(capabilities.hookEvents) ? capabilities.hookEvents.map(asText).filter(Boolean) : hookEvents;
840
- lines.push(` hooks ${hookList.join(", ") || "(none)"}`);
841
- lines.push(` skills ${names(capabilities.skills).join(", ") || "(none)"}`);
842
- lines.push(` prompts ${names(capabilities.prompts).join(", ") || "(none)"}`);
843
- const model = typeof capabilities.model === "string" ? capabilities.model : "(unknown)";
844
- const thinking = typeof capabilities.thinkingLevel === "string" ? capabilities.thinkingLevel : "";
845
- const cwd = typeof capabilities.cwd === "string" ? capabilities.cwd : "";
846
- lines.push(` model ${model}${thinking ? ` \xB7 ${thinking}` : ""}`);
847
- if (cwd)
848
- lines.push(` cwd ${cwd}`);
849
- lines.push(" (worker commands are in your palette as [worker \u2026] \xB7 /worker shows this again)");
850
- return lines;
851
- }
852
- async function answerExtensionUiRequest(options, ctx, request) {
853
- const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
854
- const method = String(request.method ?? request.type ?? "input");
855
- const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
856
- const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
857
- const choices = rawOptions.map((option) => {
858
- const record = recordOf2(option);
859
- return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
860
- }).filter(Boolean);
861
- try {
862
- if (method === "confirm") {
863
- const confirmed = await ctx.ui.confirm("Worker request", prompt);
864
- await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
865
- return;
866
- }
867
- if (choices.length > 0) {
868
- const selected = await ctx.ui.select(prompt, choices);
869
- await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
870
- return;
871
- }
872
- const value = await ctx.ui.input("Worker request", prompt);
873
- await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
874
- } catch (error) {
875
- ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
876
- }
877
- }
878
- var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "worker", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
879
- function registerDaemonCommands(pi, options, ctx, commands, registered) {
880
- for (const command of commands) {
881
- const record = recordOf2(command);
882
- const name = typeof record?.name === "string" ? record.name : "";
883
- const source = typeof record?.source === "string" ? record.source : "worker";
884
- if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
885
- continue;
886
- registered.add(name);
887
- const description = typeof record?.description === "string" ? record.description : undefined;
888
- try {
889
- pi.registerCommand(name, {
890
- description: `[worker ${source}] ${description ?? ""}`.trim(),
891
- handler: async (args) => {
892
- try {
893
- const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
894
- ctx.ui.notify(message, "info");
895
- } catch (error) {
896
- ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
897
- }
898
- }
899
- });
900
- } catch {}
901
- }
902
- }
903
- function createRigWorkerPiBridgeExtension(options) {
904
- return (pi) => {
905
- const registeredDaemonCommands = new Set;
906
- let capabilityLines = null;
907
- let statusText = "connecting to worker session";
908
- let busy = true;
909
- let connected = false;
910
- let frame = 0;
911
- let spinnerTimer = null;
912
- const renderStatus = (ctx) => {
913
- const prefix = busy ? `${SPINNER_FRAMES[frame]} ` : connected ? "\u25CF " : "\u25CB ";
914
- ctx.ui.setStatus("rig-worker-pi", `${prefix}${statusText}`);
915
- };
916
- const setStatus = (ctx, text, isBusy) => {
917
- statusText = text;
918
- busy = isBusy;
919
- renderStatus(ctx);
920
- };
921
- pi.registerCommand("detach", {
922
- description: "Detach from this run; the worker keeps going",
923
- handler: async (_args, ctx) => {
924
- ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
925
- ctx.shutdown();
926
- }
927
- });
928
- pi.registerCommand("stop", {
929
- description: "Stop the worker Pi run and detach",
930
- handler: async (_args, ctx) => {
931
- await options.controller.abort();
932
- ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
933
- ctx.shutdown();
934
- }
935
- });
936
- pi.registerCommand("worker", {
937
- description: "Show the worker session's real capabilities (tools, extensions, hooks, skills)",
938
- handler: async (_args, ctx) => {
939
- if (capabilityLines)
940
- ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
941
- else
942
- ctx.ui.notify("Worker capabilities are not available yet (still connecting).", "info");
943
- }
944
- });
945
- pi.on("user_bash", (event) => ({
946
- operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
947
- }));
948
- pi.on("session_start", async (_event, ctx) => {
949
- ctx.ui.setTitle("Rig \xB7 enriched bundled Pi");
950
- setStatus(ctx, "waiting for worker Pi daemon", true);
951
- spinnerTimer = setInterval(() => {
952
- frame = (frame + 1) % SPINNER_FRAMES.length;
953
- if (busy)
954
- renderStatus(ctx);
955
- }, 150);
956
- ctx.ui.notify(`Enriched bundled Pi \u2014 native UI + Rig layers, worker brain. Attached to run ${options.runId}. /worker shows live capabilities \xB7 /detach exits \xB7 /stop cancels.`, "info");
957
- if (options.initialMessageSent)
958
- ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
959
- const nativeUi = ctx.ui;
960
- options.controller.setUiHooks({
961
- onStatusText: (text) => setStatus(ctx, text, !connected),
962
- onActivity: (label, detail) => {
963
- const active = label !== "idle" && !/complete|ready/i.test(label);
964
- setStatus(ctx, [label, detail].filter(Boolean).join(" \u2014 "), active);
965
- if (/agent running|tool:/.test(label))
966
- ctx.ui.setWidget("rig-worker-capabilities", undefined);
967
- },
968
- onConnectionChange: (nextConnected) => {
969
- connected = nextConnected;
970
- setStatus(ctx, nextConnected ? "worker session live" : "worker session disconnected", false);
971
- },
972
- onError: (message) => ctx.ui.notify(message, "error"),
973
- onExtensionUiRequest: (request) => {
974
- answerExtensionUiRequest(options, ctx, request);
975
- },
976
- onCatchUp: (messages, commands, capabilities) => {
977
- if (nativeUi.appendSessionMessages)
978
- nativeUi.appendSessionMessages(messages);
979
- const cwd = options.controller.status.cwd;
980
- if (nativeUi.setDisplayCwd && cwd)
981
- nativeUi.setDisplayCwd(cwd);
982
- registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
983
- if (capabilities) {
984
- capabilityLines = renderWorkerCapabilities(capabilities);
985
- ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
986
- }
987
- }
988
- });
989
- options.controller.connect().catch((error) => {
990
- ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
991
- });
992
- });
993
- pi.on("session_shutdown", () => {
994
- if (spinnerTimer)
995
- clearInterval(spinnerTimer);
996
- options.controller.close();
997
- });
998
- };
999
- }
1000
320
 
1001
321
  // packages/cli/src/commands/_pi-frontend.ts
1002
322
  function setTemporaryEnv(updates) {
@@ -1014,51 +334,38 @@ function setTemporaryEnv(updates) {
1014
334
  }
1015
335
  };
1016
336
  }
337
+ function buildOperatorPiEnv(input) {
338
+ return {
339
+ PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
340
+ PI_SKIP_VERSION_CHECK: "1",
341
+ RIG_PI_OPERATOR_SESSION: "1",
342
+ RIG_RUN_ID: input.runId,
343
+ RIG_SERVER_URL: input.serverUrl,
344
+ ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
345
+ ...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
346
+ };
347
+ }
1017
348
  async function attachRunBundledPiFrontend(context, input) {
1018
349
  const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1019
- const restoreEnv = setTemporaryEnv({
1020
- PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
1021
- PI_SKIP_VERSION_CHECK: "1",
1022
- PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust"
1023
- });
1024
- const controller = new RigRemoteSessionController({ context, runId: input.runId });
1025
- const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
1026
- const services = await createAgentSessionServices({
1027
- cwd,
1028
- agentDir,
1029
- resourceLoaderOptions: {
1030
- extensionFactories: [
1031
- createRigWorkerPiBridgeExtension({
1032
- context,
1033
- controller,
1034
- runId: input.runId,
1035
- initialMessageSent: input.steered === true
1036
- })
1037
- ],
1038
- noExtensions: true,
1039
- noSkills: true,
1040
- noPromptTemplates: true,
1041
- noContextFiles: true
1042
- }
1043
- });
1044
- const created = await createAgentSessionFromServices({
1045
- services,
1046
- sessionManager,
1047
- sessionStartEvent,
1048
- noTools: "all",
1049
- sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
1050
- });
1051
- return { ...created, services, diagnostics: services.diagnostics };
350
+ const server = await ensureServerForCli(context.projectRoot);
351
+ const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
352
+ runId: input.runId,
353
+ serverUrl: server.baseUrl,
354
+ authToken: server.authToken,
355
+ serverProjectRoot: server.serverProjectRoot,
356
+ sessionDir: tempSessionDir
357
+ }));
358
+ const piRigExtensionFactory = (pi) => {
359
+ createPiRigExtension(pi);
1052
360
  };
1053
361
  let detached = false;
1054
362
  try {
1055
363
  await runPiMain([], {
1056
- createRuntimeOverride: () => createRemoteRuntime
364
+ extensionFactories: [piRigExtensionFactory]
1057
365
  });
1058
366
  detached = true;
1059
367
  } finally {
1060
368
  restoreEnv();
1061
- controller.close();
1062
369
  rmSync(tempSessionDir, { recursive: true, force: true });
1063
370
  }
1064
371
  let run = { runId: input.runId, status: "unknown" };
@@ -1072,9 +379,10 @@ async function attachRunBundledPiFrontend(context, input) {
1072
379
  timelineCursor: null,
1073
380
  steered: input.steered === true,
1074
381
  detached,
1075
- rendered: "enriched bundled Pi frontend with remote worker session runtime"
382
+ rendered: "stock Pi operator console with the pi-rig extension"
1076
383
  };
1077
384
  }
1078
385
  export {
386
+ buildOperatorPiEnv,
1079
387
  attachRunBundledPiFrontend
1080
388
  };