@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
@@ -1,771 +0,0 @@
1
- // @bun
2
- // packages/cli/src/commands/_pi-remote-session.ts
3
- import { AgentSession as PiAgentSession, expandPromptTemplate } from "@earendil-works/pi-coding-agent";
4
-
5
- // packages/cli/src/commands/_server-client.ts
6
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
7
- import { resolve as resolve2 } from "path";
8
-
9
- // packages/cli/src/runner.ts
10
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
11
- import { CliError } from "@rig/runtime/control-plane/errors";
12
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
13
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
14
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
15
-
16
- // packages/cli/src/commands/_server-client.ts
17
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
18
-
19
- // packages/cli/src/commands/_connection-state.ts
20
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
21
- import { homedir } from "os";
22
- import { dirname, resolve } from "path";
23
- function resolveGlobalConnectionsPath(env = process.env) {
24
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
25
- if (explicit)
26
- return resolve(explicit);
27
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
28
- if (stateDir)
29
- return resolve(stateDir, "connections.json");
30
- return resolve(homedir(), ".rig", "connections.json");
31
- }
32
- function resolveRepoConnectionPath(projectRoot) {
33
- return resolve(projectRoot, ".rig", "state", "connection.json");
34
- }
35
- function readJsonFile(path) {
36
- if (!existsSync(path))
37
- return null;
38
- try {
39
- return JSON.parse(readFileSync(path, "utf8"));
40
- } catch (error) {
41
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
42
- }
43
- }
44
- function writeJsonFile(path, value) {
45
- mkdirSync(dirname(path), { recursive: true });
46
- writeFileSync(path, `${JSON.stringify(value, null, 2)}
47
- `, "utf8");
48
- }
49
- function normalizeConnection(value) {
50
- if (!value || typeof value !== "object" || Array.isArray(value))
51
- return null;
52
- const record = value;
53
- if (record.kind === "local")
54
- return { kind: "local", mode: "auto" };
55
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
56
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
57
- return { kind: "remote", baseUrl };
58
- }
59
- return null;
60
- }
61
- function readGlobalConnections(options = {}) {
62
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
63
- const payload = readJsonFile(path);
64
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
65
- return { connections: {} };
66
- }
67
- const rawConnections = payload.connections;
68
- const connections = {};
69
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
70
- for (const [alias, raw] of Object.entries(rawConnections)) {
71
- const connection = normalizeConnection(raw);
72
- if (connection)
73
- connections[alias] = connection;
74
- }
75
- }
76
- return { connections };
77
- }
78
- function readRepoConnection(projectRoot) {
79
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
80
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
81
- return null;
82
- const record = payload;
83
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
84
- if (!selected)
85
- return null;
86
- return {
87
- selected,
88
- project: typeof record.project === "string" ? record.project : undefined,
89
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
90
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
91
- };
92
- }
93
- function writeRepoConnection(projectRoot, state) {
94
- writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
95
- }
96
- function resolveSelectedConnection(projectRoot, options = {}) {
97
- const repo = readRepoConnection(projectRoot);
98
- if (!repo)
99
- return null;
100
- if (repo.selected === "local")
101
- return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
102
- const global = readGlobalConnections(options);
103
- const connection = global.connections[repo.selected];
104
- if (!connection) {
105
- throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
106
- }
107
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
108
- }
109
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
110
- const repo = readRepoConnection(projectRoot);
111
- if (!repo)
112
- return;
113
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
114
- }
115
-
116
- // packages/cli/src/commands/_server-client.ts
117
- var scopedGitHubBearerTokens = new Map;
118
- function cleanToken(value) {
119
- const trimmed = value?.trim();
120
- return trimmed ? trimmed : null;
121
- }
122
- function readPrivateRemoteSessionToken(projectRoot) {
123
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
124
- if (!existsSync2(path))
125
- return null;
126
- try {
127
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
128
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
129
- } catch {
130
- return null;
131
- }
132
- }
133
- function readGitHubBearerTokenForRemote(projectRoot) {
134
- const scopedKey = resolve2(projectRoot);
135
- if (scopedGitHubBearerTokens.has(scopedKey))
136
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
137
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
138
- if (privateSession)
139
- return privateSession;
140
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
141
- }
142
- function readStoredGitHubAuthToken(projectRoot) {
143
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
144
- if (!existsSync2(path))
145
- return null;
146
- try {
147
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
148
- return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
149
- } catch {
150
- return null;
151
- }
152
- }
153
- function readLocalConnectionFallbackToken(projectRoot) {
154
- return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
155
- }
156
- async function ensureServerForCli(projectRoot) {
157
- try {
158
- const selected = resolveSelectedConnection(projectRoot);
159
- if (selected?.connection.kind === "remote") {
160
- const authToken = readGitHubBearerTokenForRemote(projectRoot);
161
- const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
162
- return {
163
- baseUrl: selected.connection.baseUrl,
164
- authToken,
165
- connectionKind: "remote",
166
- serverProjectRoot
167
- };
168
- }
169
- const connection = await ensureLocalRigServerConnection(projectRoot);
170
- return {
171
- baseUrl: connection.baseUrl,
172
- authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
173
- connectionKind: "local",
174
- serverProjectRoot: resolve2(projectRoot)
175
- };
176
- } catch (error) {
177
- if (error instanceof Error) {
178
- throw new CliError2(error.message, 1);
179
- }
180
- throw error;
181
- }
182
- }
183
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
184
- const repo = readRepoConnection(projectRoot);
185
- const slug = repo?.project?.trim();
186
- if (!slug)
187
- return null;
188
- try {
189
- const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
190
- headers: mergeHeaders(undefined, authToken)
191
- });
192
- if (!response.ok)
193
- return null;
194
- const payload = await response.json();
195
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
196
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
197
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
198
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
199
- if (path)
200
- writeRepoServerProjectRoot(projectRoot, path);
201
- return path;
202
- } catch {
203
- return null;
204
- }
205
- }
206
- function mergeHeaders(headers, authToken) {
207
- const merged = new Headers(headers);
208
- if (authToken) {
209
- merged.set("authorization", `Bearer ${authToken}`);
210
- }
211
- return merged;
212
- }
213
- function diagnosticMessage(payload) {
214
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
215
- return null;
216
- const record = payload;
217
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
218
- const messages = diagnostics.flatMap((entry) => {
219
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
220
- return [];
221
- const diagnostic = entry;
222
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
223
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
224
- return message ? [`${kind}: ${message}`] : [];
225
- });
226
- return messages.length > 0 ? messages.join("; ") : null;
227
- }
228
- async function requestServerJson(context, pathname, init = {}) {
229
- const server = await ensureServerForCli(context.projectRoot);
230
- const headers = mergeHeaders(init.headers, server.authToken);
231
- if (server.serverProjectRoot)
232
- headers.set("x-rig-project-root", server.serverProjectRoot);
233
- const response = await fetch(`${server.baseUrl}${pathname}`, {
234
- ...init,
235
- headers
236
- });
237
- const text = await response.text();
238
- const payload = text.trim().length > 0 ? (() => {
239
- try {
240
- return JSON.parse(text);
241
- } catch {
242
- return null;
243
- }
244
- })() : null;
245
- if (!response.ok) {
246
- const diagnostics = diagnosticMessage(payload);
247
- const detail = diagnostics ?? (text || response.statusText);
248
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
249
- }
250
- return payload;
251
- }
252
- async function getRunPiSessionViaServer(context, runId) {
253
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
254
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
255
- }
256
- async function getRunPiMessagesViaServer(context, runId) {
257
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
258
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
259
- }
260
- async function getRunPiStatusViaServer(context, runId) {
261
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
262
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
263
- }
264
- async function getRunPiCommandsViaServer(context, runId) {
265
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
266
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
267
- }
268
- async function getRunPiCapabilitiesViaServer(context, runId) {
269
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
270
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
271
- }
272
- async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
273
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
274
- method: "POST",
275
- headers: { "content-type": "application/json" },
276
- body: JSON.stringify({ text, streamingBehavior })
277
- });
278
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
279
- }
280
- async function sendRunPiShellViaServer(context, runId, text) {
281
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
282
- method: "POST",
283
- headers: { "content-type": "application/json" },
284
- body: JSON.stringify({ text })
285
- });
286
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
287
- }
288
- async function runRunPiCommandViaServer(context, runId, text) {
289
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
290
- method: "POST",
291
- headers: { "content-type": "application/json" },
292
- body: JSON.stringify({ text })
293
- });
294
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
295
- }
296
- async function abortRunPiViaServer(context, runId) {
297
- const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
298
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
299
- }
300
- async function buildRunPiEventsWebSocketUrl(context, runId) {
301
- const server = await ensureServerForCli(context.projectRoot);
302
- const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
303
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
304
- if (server.authToken)
305
- url.searchParams.set("token", server.authToken);
306
- if (server.serverProjectRoot)
307
- url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
308
- return url.toString();
309
- }
310
-
311
- // packages/cli/src/commands/_pi-remote-session.ts
312
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
313
- function defaultTransport() {
314
- return {
315
- getSession: getRunPiSessionViaServer,
316
- getMessages: getRunPiMessagesViaServer,
317
- getStatus: getRunPiStatusViaServer,
318
- getCommands: getRunPiCommandsViaServer,
319
- getCapabilities: getRunPiCapabilitiesViaServer,
320
- sendPrompt: sendRunPiPromptViaServer,
321
- sendShell: sendRunPiShellViaServer,
322
- runCommand: runRunPiCommandViaServer,
323
- abort: abortRunPiViaServer,
324
- buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
325
- };
326
- }
327
- function recordOf(value) {
328
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
329
- }
330
- function emptyRemoteStatus() {
331
- return {
332
- isStreaming: false,
333
- isCompacting: false,
334
- isBashRunning: false,
335
- pendingMessageCount: 0,
336
- steeringMessages: [],
337
- followUpMessages: [],
338
- model: null,
339
- thinkingLevel: null,
340
- sessionName: null,
341
- cwd: null,
342
- stats: null,
343
- contextUsage: null
344
- };
345
- }
346
- function resolveAttachReadyTimeoutMs() {
347
- const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
348
- return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
349
- }
350
-
351
- class RigRemoteSessionController {
352
- context;
353
- runId;
354
- status = emptyRemoteStatus();
355
- transport;
356
- hooks = {};
357
- session = null;
358
- socket = null;
359
- closed = false;
360
- pendingShells = [];
361
- pendingCompactions = [];
362
- constructor(input) {
363
- this.context = input.context;
364
- this.runId = input.runId;
365
- this.transport = input.transport ?? defaultTransport();
366
- }
367
- ingestEnvelope(envelopeValue) {
368
- this.applyEnvelope(envelopeValue);
369
- }
370
- bindSession(session) {
371
- this.session = session;
372
- }
373
- setUiHooks(hooks) {
374
- this.hooks = hooks;
375
- }
376
- async connect() {
377
- const ready = await this.waitForReady();
378
- if (!ready || this.closed)
379
- return;
380
- let catchupDone = false;
381
- const buffered = [];
382
- const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
383
- const socket = new WebSocket(wsUrl);
384
- this.socket = socket;
385
- socket.onopen = () => {
386
- this.hooks.onConnectionChange?.(true);
387
- this.hooks.onStatusText?.("worker session live");
388
- };
389
- socket.onmessage = (message) => {
390
- try {
391
- const payload = typeof message.data === "string" ? JSON.parse(message.data) : JSON.parse(Buffer.from(message.data).toString("utf8"));
392
- if (!catchupDone)
393
- buffered.push(payload);
394
- else
395
- this.applyEnvelope(payload);
396
- } catch (error) {
397
- this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
398
- }
399
- };
400
- socket.onerror = () => socket.close();
401
- socket.onclose = () => {
402
- this.hooks.onConnectionChange?.(false);
403
- if (!this.closed)
404
- this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
405
- };
406
- try {
407
- const [messagesPayload, statusPayload, commandsPayload, capabilitiesPayload] = await Promise.all([
408
- this.transport.getMessages(this.context, this.runId),
409
- this.transport.getStatus(this.context, this.runId),
410
- this.transport.getCommands(this.context, this.runId),
411
- this.transport.getCapabilities(this.context, this.runId).catch(() => ({ capabilities: null }))
412
- ]);
413
- const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
414
- this.applyStatusPayload(statusPayload);
415
- this.session?.replaceRemoteMessages(messages);
416
- const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
417
- const capabilities = capabilitiesPayload.capabilities && typeof capabilitiesPayload.capabilities === "object" && !Array.isArray(capabilitiesPayload.capabilities) ? capabilitiesPayload.capabilities : null;
418
- this.hooks.onCatchUp?.(messages, commands, capabilities);
419
- catchupDone = true;
420
- for (const payload of buffered.splice(0))
421
- this.applyEnvelope(payload);
422
- } catch (error) {
423
- catchupDone = true;
424
- this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
425
- }
426
- }
427
- close() {
428
- this.closed = true;
429
- this.socket?.close();
430
- for (const shell of this.pendingShells.splice(0))
431
- shell.reject(new Error("Remote session closed."));
432
- for (const compaction of this.pendingCompactions.splice(0))
433
- compaction.reject(new Error("Remote session closed."));
434
- }
435
- async sendPrompt(text, streamingBehavior) {
436
- await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
437
- }
438
- async sendCommand(text) {
439
- const result = await this.transport.runCommand(this.context, this.runId, text);
440
- return typeof result.message === "string" ? result.message : "worker command accepted";
441
- }
442
- async sendShell(text) {
443
- await this.transport.sendShell(this.context, this.runId, text);
444
- }
445
- async abort() {
446
- await this.transport.abort(this.context, this.runId);
447
- }
448
- registerPendingShell(shell) {
449
- this.pendingShells.push(shell);
450
- }
451
- failPendingShell(shell, error) {
452
- const index = this.pendingShells.indexOf(shell);
453
- if (index !== -1)
454
- this.pendingShells.splice(index, 1);
455
- shell.reject(error);
456
- }
457
- registerPendingCompaction(pending) {
458
- this.pendingCompactions.push(pending);
459
- }
460
- async waitForReady() {
461
- const startedAt = Date.now();
462
- const deadline = startedAt + resolveAttachReadyTimeoutMs();
463
- let consecutiveFailures = 0;
464
- while (!this.closed) {
465
- let requestFailed = false;
466
- const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
467
- requestFailed = true;
468
- return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
469
- });
470
- if (session.ready !== false)
471
- return true;
472
- consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
473
- const status = String(session.status ?? "starting");
474
- if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
475
- this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
476
- return false;
477
- }
478
- 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`);
479
- if (Date.now() >= deadline) {
480
- this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
481
- return false;
482
- }
483
- await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
484
- }
485
- return false;
486
- }
487
- applyEnvelope(envelopeValue) {
488
- const envelope = recordOf(envelopeValue);
489
- if (!envelope)
490
- return;
491
- const type = String(envelope.type ?? "");
492
- if (type === "status.update") {
493
- this.applyStatusPayload(envelope);
494
- return;
495
- }
496
- if (type === "activity.update") {
497
- const activity = recordOf(envelope.activity);
498
- this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
499
- return;
500
- }
501
- if (type === "extension_ui_request") {
502
- const request = recordOf(envelope.request);
503
- if (request)
504
- this.hooks.onExtensionUiRequest?.(request);
505
- return;
506
- }
507
- if (type === "pi.ui_event") {
508
- this.applyShellUiEvent(envelope.event);
509
- return;
510
- }
511
- if (type === "pi.event") {
512
- this.session?.handleRemoteSessionEvent(envelope.event);
513
- this.settlePendingCompaction(envelope.event);
514
- return;
515
- }
516
- if (type === "error") {
517
- this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
518
- }
519
- }
520
- applyStatusPayload(payload) {
521
- const status = recordOf(payload.status) ?? payload;
522
- const next = this.status;
523
- next.isStreaming = status.isStreaming === true;
524
- next.isCompacting = status.isCompacting === true;
525
- next.isBashRunning = status.isBashRunning === true;
526
- next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
527
- next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
528
- next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
529
- next.model = recordOf(status.model) ?? next.model;
530
- next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
531
- next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
532
- next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
533
- next.stats = recordOf(status.stats) ?? next.stats;
534
- next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
535
- }
536
- applyShellUiEvent(value) {
537
- const event = recordOf(value);
538
- if (!event)
539
- return;
540
- const type = String(event.type ?? "");
541
- const pending = this.pendingShells[0];
542
- if (type === "shell.chunk" && pending) {
543
- pending.sawChunk = true;
544
- pending.onData(Buffer.from(String(event.chunk ?? "")));
545
- return;
546
- }
547
- if (type === "shell.end" && pending) {
548
- const output = String(event.output ?? "");
549
- if (output && !pending.sawChunk)
550
- pending.onData(Buffer.from(output));
551
- const index = this.pendingShells.indexOf(pending);
552
- if (index !== -1)
553
- this.pendingShells.splice(index, 1);
554
- pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
555
- }
556
- }
557
- settlePendingCompaction(eventValue) {
558
- const event = recordOf(eventValue);
559
- if (!event)
560
- return;
561
- const type = String(event.type ?? "");
562
- if (type !== "compaction_end" || this.pendingCompactions.length === 0)
563
- return;
564
- const pending = this.pendingCompactions.shift();
565
- const result = recordOf(event.result);
566
- if (result)
567
- pending.resolve(result);
568
- else if (event.aborted === true)
569
- pending.reject(new Error("Compaction aborted on the worker."));
570
- else
571
- pending.resolve({});
572
- }
573
- }
574
-
575
- class RigRemoteAgentSession extends PiAgentSession {
576
- remote;
577
- constructor(config, remote) {
578
- super(config);
579
- this.remote = remote;
580
- remote.bindSession(this);
581
- }
582
- handleRemoteSessionEvent(eventValue) {
583
- const event = recordOf(eventValue);
584
- if (!event)
585
- return;
586
- const type = String(event.type ?? "");
587
- if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
588
- this.agent.state.messages = [...this.agent.state.messages, event.message];
589
- }
590
- this._emit(eventValue);
591
- }
592
- replaceRemoteMessages(messages) {
593
- this.agent.state.messages = messages;
594
- }
595
- async expandLocalInput(text) {
596
- let current = text;
597
- const runner = this.extensionRunner;
598
- if (runner.hasHandlers("input")) {
599
- const result = await runner.emitInput(current, undefined, "interactive");
600
- if (result.action === "handled")
601
- return null;
602
- if (result.action === "transform")
603
- current = result.text;
604
- }
605
- current = this._expandSkillCommand(current);
606
- current = expandPromptTemplate(current, [...this.promptTemplates]);
607
- return current;
608
- }
609
- async prompt(text, options) {
610
- const trimmed = text.trim();
611
- if (!trimmed)
612
- return;
613
- if (trimmed.startsWith("/")) {
614
- if (await this._tryExecuteExtensionCommand(trimmed))
615
- return;
616
- const expanded2 = await this.expandLocalInput(trimmed);
617
- if (expanded2 === null)
618
- return;
619
- if (expanded2 !== trimmed) {
620
- const behavior2 = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
621
- options?.preflightResult?.(true);
622
- await this.remote.sendPrompt(expanded2, behavior2);
623
- return;
624
- }
625
- await this.remote.sendCommand(trimmed);
626
- return;
627
- }
628
- if (trimmed.startsWith("!")) {
629
- await this.remote.sendShell(trimmed);
630
- return;
631
- }
632
- const expanded = await this.expandLocalInput(trimmed);
633
- if (expanded === null)
634
- return;
635
- const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
636
- options?.preflightResult?.(true);
637
- await this.remote.sendPrompt(expanded, behavior);
638
- }
639
- async steer(text) {
640
- const trimmed = text.trim();
641
- if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
642
- return;
643
- const expanded = await this.expandLocalInput(trimmed);
644
- if (expanded === null)
645
- return;
646
- await this.remote.sendPrompt(expanded, "steer");
647
- }
648
- async followUp(text) {
649
- const trimmed = text.trim();
650
- if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
651
- return;
652
- const expanded = await this.expandLocalInput(trimmed);
653
- if (expanded === null)
654
- return;
655
- await this.remote.sendPrompt(expanded, "followUp");
656
- }
657
- async abort() {
658
- await this.remote.abort();
659
- }
660
- async compact(customInstructions) {
661
- const pending = new Promise((resolve3, reject) => {
662
- this.remote.registerPendingCompaction({ resolve: resolve3, reject });
663
- });
664
- await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
665
- return pending;
666
- }
667
- clearQueue() {
668
- const cleared = {
669
- steering: [...this.remote.status.steeringMessages],
670
- followUp: [...this.remote.status.followUpMessages]
671
- };
672
- this.remote.status.steeringMessages = [];
673
- this.remote.status.followUpMessages = [];
674
- this.remote.status.pendingMessageCount = 0;
675
- this.remote.sendCommand("/queue-clear").catch(() => {});
676
- return cleared;
677
- }
678
- get isStreaming() {
679
- return this.remote.status.isStreaming;
680
- }
681
- get isCompacting() {
682
- return this.remote.status.isCompacting;
683
- }
684
- get isBashRunning() {
685
- return this.remote.status.isBashRunning;
686
- }
687
- get pendingMessageCount() {
688
- return this.remote.status.pendingMessageCount;
689
- }
690
- getSteeringMessages() {
691
- return this.remote.status.steeringMessages;
692
- }
693
- getFollowUpMessages() {
694
- return this.remote.status.followUpMessages;
695
- }
696
- get model() {
697
- return this.remote.status.model ?? super.model;
698
- }
699
- async setModel(model) {
700
- await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
701
- this.remote.status.model = model;
702
- }
703
- get thinkingLevel() {
704
- return this.remote.status.thinkingLevel ?? super.thinkingLevel;
705
- }
706
- setThinkingLevel(level) {
707
- this.remote.status.thinkingLevel = level;
708
- this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
709
- }
710
- get sessionName() {
711
- return this.remote.status.sessionName ?? super.sessionName;
712
- }
713
- setSessionName(name) {
714
- this.remote.status.sessionName = name;
715
- this.remote.sendCommand(`/name ${name}`).catch(() => {});
716
- }
717
- getSessionStats() {
718
- return this.remote.status.stats ?? super.getSessionStats();
719
- }
720
- getContextUsage() {
721
- return this.remote.status.contextUsage ?? super.getContextUsage();
722
- }
723
- dispose() {
724
- this.remote.close();
725
- super.dispose();
726
- }
727
- }
728
- function createRemoteBashOperations(controller, excludeFromContext) {
729
- return {
730
- exec(command, _cwd, execOptions) {
731
- return new Promise((resolve3, reject) => {
732
- const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
733
- const cleanup = () => {
734
- execOptions.signal?.removeEventListener("abort", onAbort);
735
- if (timer)
736
- clearTimeout(timer);
737
- };
738
- const onAbort = () => {
739
- cleanup();
740
- controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
741
- };
742
- const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
743
- const timer = timeoutMs > 0 ? setTimeout(() => {
744
- cleanup();
745
- controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
746
- }, timeoutMs) : null;
747
- const wrappedResolve = pending.resolve;
748
- const wrappedReject = pending.reject;
749
- pending.resolve = (result) => {
750
- cleanup();
751
- wrappedResolve(result);
752
- };
753
- pending.reject = (error) => {
754
- cleanup();
755
- wrappedReject(error);
756
- };
757
- execOptions.signal?.addEventListener("abort", onAbort, { once: true });
758
- controller.registerPendingShell(pending);
759
- controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
760
- cleanup();
761
- controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
762
- });
763
- });
764
- }
765
- };
766
- }
767
- export {
768
- createRemoteBashOperations,
769
- RigRemoteSessionController,
770
- RigRemoteAgentSession
771
- };