@h-rig/cli 0.0.6-alpha.4 → 0.0.6-alpha.40
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 +3947 -1190
- package/dist/src/commands/_cli-format.js +369 -0
- package/dist/src/commands/_connection-state.js +1 -3
- package/dist/src/commands/_doctor-checks.js +13 -27
- package/dist/src/commands/_help-catalog.js +445 -0
- package/dist/src/commands/_operator-surface.js +220 -0
- package/dist/src/commands/_operator-view.js +942 -56
- package/dist/src/commands/_parsers.js +0 -2
- package/dist/src/commands/_pi-frontend.js +906 -0
- package/dist/src/commands/_pi-install.js +4 -3
- package/dist/src/commands/_pi-worker-bridge-extension.js +826 -0
- package/dist/src/commands/_policy.js +0 -2
- package/dist/src/commands/_preflight.js +32 -109
- package/dist/src/commands/_run-driver-helpers.js +21 -2
- package/dist/src/commands/_server-client.js +152 -31
- package/dist/src/commands/_snapshot-upload.js +8 -23
- package/dist/src/commands/_task-picker.js +44 -16
- package/dist/src/commands/agent.js +8 -9
- package/dist/src/commands/browser.js +4 -6
- package/dist/src/commands/connect.js +132 -25
- package/dist/src/commands/dist.js +4 -6
- package/dist/src/commands/doctor.js +13 -27
- package/dist/src/commands/github.js +10 -25
- package/dist/src/commands/inbox.js +351 -31
- package/dist/src/commands/init.js +298 -71
- package/dist/src/commands/inspect.js +237 -23
- package/dist/src/commands/inspector.js +2 -4
- package/dist/src/commands/pi.js +168 -0
- package/dist/src/commands/plugin.js +81 -22
- package/dist/src/commands/profile-and-review.js +8 -10
- package/dist/src/commands/queue.js +2 -3
- package/dist/src/commands/remote.js +18 -20
- package/dist/src/commands/repo-git-harness.js +6 -8
- package/dist/src/commands/run.js +1240 -123
- package/dist/src/commands/server.js +222 -33
- package/dist/src/commands/setup.js +17 -37
- package/dist/src/commands/task-report-bug.js +5 -7
- package/dist/src/commands/task-run-driver.js +649 -71
- package/dist/src/commands/task.js +1679 -252
- package/dist/src/commands/test.js +3 -5
- package/dist/src/commands/workspace.js +4 -6
- package/dist/src/commands.js +3927 -1164
- package/dist/src/index.js +3940 -1186
- package/dist/src/launcher.js +5 -3
- package/dist/src/report-bug.js +3 -3
- package/dist/src/runner.js +5 -19
- package/package.json +6 -4
|
@@ -1,9 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
// packages/cli/src/commands/_operator-view.ts
|
|
3
|
-
import { createInterface } from "readline";
|
|
4
|
-
|
|
5
2
|
// packages/cli/src/commands/_server-client.ts
|
|
6
|
-
import { spawnSync } from "child_process";
|
|
7
3
|
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
8
4
|
import { resolve as resolve2 } from "path";
|
|
9
5
|
|
|
@@ -11,8 +7,6 @@ import { resolve as resolve2 } from "path";
|
|
|
11
7
|
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
12
8
|
import { CliError } from "@rig/runtime/control-plane/errors";
|
|
13
9
|
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
14
|
-
import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
|
|
15
|
-
import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
|
|
16
10
|
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
17
11
|
import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
|
|
18
12
|
|
|
@@ -96,13 +90,13 @@ function resolveSelectedConnection(projectRoot, options = {}) {
|
|
|
96
90
|
const global = readGlobalConnections(options);
|
|
97
91
|
const connection = global.connections[repo.selected];
|
|
98
92
|
if (!connection) {
|
|
99
|
-
throw new CliError2(`Selected Rig
|
|
93
|
+
throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
100
94
|
}
|
|
101
95
|
return { alias: repo.selected, connection };
|
|
102
96
|
}
|
|
103
97
|
|
|
104
98
|
// packages/cli/src/commands/_server-client.ts
|
|
105
|
-
var
|
|
99
|
+
var scopedGitHubBearerTokens = new Map;
|
|
106
100
|
function cleanToken(value) {
|
|
107
101
|
const trimmed = value?.trim();
|
|
108
102
|
return trimmed ? trimmed : null;
|
|
@@ -119,25 +113,13 @@ function readPrivateRemoteSessionToken(projectRoot) {
|
|
|
119
113
|
}
|
|
120
114
|
}
|
|
121
115
|
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
122
|
-
|
|
123
|
-
|
|
116
|
+
const scopedKey = resolve2(projectRoot);
|
|
117
|
+
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
118
|
+
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
124
119
|
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
125
|
-
if (privateSession)
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
}
|
|
129
|
-
const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
|
|
130
|
-
if (envToken) {
|
|
131
|
-
cachedGitHubBearerToken = envToken;
|
|
132
|
-
return cachedGitHubBearerToken;
|
|
133
|
-
}
|
|
134
|
-
const result = spawnSync("gh", ["auth", "token"], {
|
|
135
|
-
encoding: "utf8",
|
|
136
|
-
timeout: 5000,
|
|
137
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
138
|
-
});
|
|
139
|
-
cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
|
|
140
|
-
return cachedGitHubBearerToken;
|
|
120
|
+
if (privateSession)
|
|
121
|
+
return privateSession;
|
|
122
|
+
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
141
123
|
}
|
|
142
124
|
async function ensureServerForCli(projectRoot) {
|
|
143
125
|
try {
|
|
@@ -218,6 +200,15 @@ async function getRunLogsViaServer(context, runId, options = {}) {
|
|
|
218
200
|
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
219
201
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
220
202
|
}
|
|
203
|
+
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
204
|
+
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
205
|
+
if (options.limit !== undefined)
|
|
206
|
+
url.searchParams.set("limit", String(options.limit));
|
|
207
|
+
if (options.cursor)
|
|
208
|
+
url.searchParams.set("cursor", options.cursor);
|
|
209
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
210
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
211
|
+
}
|
|
221
212
|
async function stopRunViaServer(context, runId) {
|
|
222
213
|
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
223
214
|
method: "POST",
|
|
@@ -234,9 +225,69 @@ async function steerRunViaServer(context, runId, message) {
|
|
|
234
225
|
});
|
|
235
226
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
236
227
|
}
|
|
228
|
+
async function getRunPiSessionViaServer(context, runId) {
|
|
229
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
230
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
231
|
+
}
|
|
232
|
+
async function getRunPiMessagesViaServer(context, runId) {
|
|
233
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
234
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
235
|
+
}
|
|
236
|
+
async function getRunPiStatusViaServer(context, runId) {
|
|
237
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
238
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
239
|
+
}
|
|
240
|
+
async function getRunPiCommandsViaServer(context, runId) {
|
|
241
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
242
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
243
|
+
}
|
|
244
|
+
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
245
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
246
|
+
method: "POST",
|
|
247
|
+
headers: { "content-type": "application/json" },
|
|
248
|
+
body: JSON.stringify({ text, streamingBehavior })
|
|
249
|
+
});
|
|
250
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
251
|
+
}
|
|
252
|
+
async function sendRunPiShellViaServer(context, runId, text) {
|
|
253
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
254
|
+
method: "POST",
|
|
255
|
+
headers: { "content-type": "application/json" },
|
|
256
|
+
body: JSON.stringify({ text })
|
|
257
|
+
});
|
|
258
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
259
|
+
}
|
|
260
|
+
async function runRunPiCommandViaServer(context, runId, text) {
|
|
261
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
262
|
+
method: "POST",
|
|
263
|
+
headers: { "content-type": "application/json" },
|
|
264
|
+
body: JSON.stringify({ text })
|
|
265
|
+
});
|
|
266
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
267
|
+
}
|
|
268
|
+
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
269
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
270
|
+
method: "POST",
|
|
271
|
+
headers: { "content-type": "application/json" },
|
|
272
|
+
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
273
|
+
});
|
|
274
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
275
|
+
}
|
|
276
|
+
async function abortRunPiViaServer(context, runId) {
|
|
277
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
278
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
279
|
+
}
|
|
280
|
+
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
281
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
282
|
+
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
283
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
284
|
+
if (server.authToken)
|
|
285
|
+
url.searchParams.set("token", server.authToken);
|
|
286
|
+
return url.toString();
|
|
287
|
+
}
|
|
237
288
|
|
|
238
|
-
// packages/cli/src/commands/_operator-
|
|
239
|
-
|
|
289
|
+
// packages/cli/src/commands/_operator-surface.ts
|
|
290
|
+
import { createInterface } from "readline";
|
|
240
291
|
var CANONICAL_STAGES = [
|
|
241
292
|
"Connect",
|
|
242
293
|
"GitHub/task sync",
|
|
@@ -251,18 +302,834 @@ var CANONICAL_STAGES = [
|
|
|
251
302
|
"Merge",
|
|
252
303
|
"Complete"
|
|
253
304
|
];
|
|
305
|
+
function logDetail(log) {
|
|
306
|
+
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
307
|
+
}
|
|
308
|
+
function parseProviderProtocolLog(title, detail) {
|
|
309
|
+
if (title.trim().toLowerCase() !== "agent output")
|
|
310
|
+
return null;
|
|
311
|
+
if (!detail.startsWith("{") || !detail.endsWith("}"))
|
|
312
|
+
return null;
|
|
313
|
+
try {
|
|
314
|
+
const record = JSON.parse(detail);
|
|
315
|
+
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
316
|
+
return null;
|
|
317
|
+
const type = record.type;
|
|
318
|
+
return typeof type === "string" && [
|
|
319
|
+
"assistant",
|
|
320
|
+
"message_start",
|
|
321
|
+
"message_update",
|
|
322
|
+
"message_end",
|
|
323
|
+
"stream_event",
|
|
324
|
+
"tool_result",
|
|
325
|
+
"tool_execution_start",
|
|
326
|
+
"tool_execution_update",
|
|
327
|
+
"tool_execution_end",
|
|
328
|
+
"turn_start",
|
|
329
|
+
"turn_end"
|
|
330
|
+
].includes(type) ? record : null;
|
|
331
|
+
} catch {
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function renderProviderProtocolLog(record) {
|
|
336
|
+
const type = typeof record.type === "string" ? record.type : "";
|
|
337
|
+
if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
|
|
338
|
+
const toolName = String(record.toolName ?? record.name ?? "tool");
|
|
339
|
+
const status = type === "tool_execution_start" ? "started" : type === "tool_execution_end" ? record.isError === true || record.result && typeof record.result === "object" && !Array.isArray(record.result) && record.result.isError === true ? "failed" : "completed" : "running";
|
|
340
|
+
return `[Pi tool] ${toolName} ${status}`;
|
|
341
|
+
}
|
|
342
|
+
return null;
|
|
343
|
+
}
|
|
344
|
+
function entryId(entry, fallback) {
|
|
345
|
+
return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
|
|
346
|
+
}
|
|
254
347
|
function renderOperatorSnapshot(snapshot) {
|
|
255
348
|
const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
|
|
256
349
|
const runId = String(run.runId ?? run.id ?? "run");
|
|
257
350
|
const status = String(run.status ?? "unknown");
|
|
258
351
|
const logs = snapshot.logs ?? [];
|
|
352
|
+
const latestByStage = new Map;
|
|
353
|
+
for (const log of logs) {
|
|
354
|
+
const title = String(log.title ?? "").toLowerCase();
|
|
355
|
+
const stageName = String(log.stage ?? "").toLowerCase();
|
|
356
|
+
const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
357
|
+
if (stage)
|
|
358
|
+
latestByStage.set(stage, log);
|
|
359
|
+
}
|
|
259
360
|
const stageLines = CANONICAL_STAGES.flatMap((stage) => {
|
|
260
|
-
const match =
|
|
261
|
-
return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
|
|
361
|
+
const match = latestByStage.get(stage);
|
|
362
|
+
return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
|
|
262
363
|
});
|
|
263
364
|
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
264
365
|
`);
|
|
265
366
|
}
|
|
367
|
+
function createPiRunStreamRenderer(output = process.stdout) {
|
|
368
|
+
let lastSnapshot = "";
|
|
369
|
+
const assistantTextById = new Map;
|
|
370
|
+
const seenTimeline = new Set;
|
|
371
|
+
const seenLogs = new Set;
|
|
372
|
+
const writeLine = (line) => output.write(`${line}
|
|
373
|
+
`);
|
|
374
|
+
return {
|
|
375
|
+
renderSnapshot(snapshot) {
|
|
376
|
+
const rendered = renderOperatorSnapshot(snapshot);
|
|
377
|
+
if (rendered && rendered !== lastSnapshot) {
|
|
378
|
+
writeLine(rendered);
|
|
379
|
+
lastSnapshot = rendered;
|
|
380
|
+
}
|
|
381
|
+
},
|
|
382
|
+
renderTimeline(entries) {
|
|
383
|
+
for (const [index, entry] of entries.entries()) {
|
|
384
|
+
const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
|
|
385
|
+
if (entry.type === "assistant_message" && typeof entry.text === "string") {
|
|
386
|
+
const text = entry.text;
|
|
387
|
+
const previousText = assistantTextById.get(id) ?? "";
|
|
388
|
+
if (!previousText && text.trim()) {
|
|
389
|
+
writeLine("[Pi assistant]");
|
|
390
|
+
}
|
|
391
|
+
if (text.startsWith(previousText)) {
|
|
392
|
+
const delta = text.slice(previousText.length);
|
|
393
|
+
if (delta)
|
|
394
|
+
output.write(delta);
|
|
395
|
+
} else if (text.trim() && text !== previousText) {
|
|
396
|
+
if (previousText)
|
|
397
|
+
writeLine(`
|
|
398
|
+
[Pi assistant]`);
|
|
399
|
+
output.write(text);
|
|
400
|
+
}
|
|
401
|
+
assistantTextById.set(id, text);
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
if (seenTimeline.has(id))
|
|
405
|
+
continue;
|
|
406
|
+
seenTimeline.add(id);
|
|
407
|
+
if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
|
|
408
|
+
writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
if (entry.type === "timeline_warning") {
|
|
412
|
+
writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
if (entry.type === "action") {
|
|
416
|
+
const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
|
|
417
|
+
if (text)
|
|
418
|
+
writeLine(`[Rig action] ${text}`);
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
if (entry.type === "user_message") {
|
|
422
|
+
const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
|
|
423
|
+
if (text)
|
|
424
|
+
writeLine(`[Operator] ${text}`);
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
|
|
428
|
+
if (fallback)
|
|
429
|
+
writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
renderLogs(entries) {
|
|
433
|
+
for (const [index, entry] of entries.entries()) {
|
|
434
|
+
const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
|
|
435
|
+
if (seenLogs.has(id))
|
|
436
|
+
continue;
|
|
437
|
+
seenLogs.add(id);
|
|
438
|
+
const title = String(entry.title ?? "");
|
|
439
|
+
if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
|
|
440
|
+
continue;
|
|
441
|
+
const detail = logDetail(entry);
|
|
442
|
+
if (!detail)
|
|
443
|
+
continue;
|
|
444
|
+
const protocolRecord = parseProviderProtocolLog(title, detail);
|
|
445
|
+
if (protocolRecord) {
|
|
446
|
+
const protocolLine = renderProviderProtocolLog(protocolRecord);
|
|
447
|
+
if (protocolLine)
|
|
448
|
+
writeLine(protocolLine);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
writeLine(`[${title || "Rig log"}] ${detail}`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
function createOperatorSurface(options = {}) {
|
|
457
|
+
const input = options.input ?? process.stdin;
|
|
458
|
+
const output = options.output ?? process.stdout;
|
|
459
|
+
const errorOutput = options.errorOutput ?? process.stderr;
|
|
460
|
+
const renderer = createPiRunStreamRenderer(output);
|
|
461
|
+
const writeLine = (line) => output.write(`${line}
|
|
462
|
+
`);
|
|
463
|
+
return {
|
|
464
|
+
mode: "pi-compatible-text",
|
|
465
|
+
...renderer,
|
|
466
|
+
info: writeLine,
|
|
467
|
+
error: (message) => errorOutput.write(`${message}
|
|
468
|
+
`),
|
|
469
|
+
attachCommandInput(handler) {
|
|
470
|
+
if (options.interactive === false || !input.isTTY)
|
|
471
|
+
return null;
|
|
472
|
+
const rl = createInterface({ input, output: process.stdout, terminal: false });
|
|
473
|
+
rl.on("line", (line) => {
|
|
474
|
+
Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
475
|
+
});
|
|
476
|
+
return { close: () => rl.close() };
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
482
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
483
|
+
import { tmpdir } from "os";
|
|
484
|
+
import { join } from "path";
|
|
485
|
+
import { main as runPiMain } from "@earendil-works/pi-coding-agent";
|
|
486
|
+
|
|
487
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
488
|
+
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
489
|
+
var MAX_TRANSCRIPT_LINES = 120;
|
|
490
|
+
function recordOf(value) {
|
|
491
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
492
|
+
}
|
|
493
|
+
function asText(value) {
|
|
494
|
+
if (typeof value === "string")
|
|
495
|
+
return value;
|
|
496
|
+
if (value === null || value === undefined)
|
|
497
|
+
return "";
|
|
498
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
499
|
+
return String(value);
|
|
500
|
+
try {
|
|
501
|
+
return JSON.stringify(value);
|
|
502
|
+
} catch {
|
|
503
|
+
return String(value);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function textFromContent(content) {
|
|
507
|
+
if (typeof content === "string")
|
|
508
|
+
return content;
|
|
509
|
+
if (!Array.isArray(content))
|
|
510
|
+
return asText(content);
|
|
511
|
+
return content.flatMap((part) => {
|
|
512
|
+
const item = recordOf(part);
|
|
513
|
+
if (!item)
|
|
514
|
+
return [];
|
|
515
|
+
if (typeof item.text === "string")
|
|
516
|
+
return [item.text];
|
|
517
|
+
if (typeof item.content === "string")
|
|
518
|
+
return [item.content];
|
|
519
|
+
if (item.type === "toolCall")
|
|
520
|
+
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
521
|
+
if (item.type === "toolResult")
|
|
522
|
+
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
523
|
+
return [];
|
|
524
|
+
}).join(`
|
|
525
|
+
`);
|
|
526
|
+
}
|
|
527
|
+
function appendTranscript(state, label, text) {
|
|
528
|
+
const trimmed = text.trimEnd();
|
|
529
|
+
if (!trimmed)
|
|
530
|
+
return;
|
|
531
|
+
const lines = trimmed.split(/\r?\n/);
|
|
532
|
+
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
533
|
+
for (const line of lines.slice(1))
|
|
534
|
+
state.transcript.push(` ${line}`);
|
|
535
|
+
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
536
|
+
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
function nativePiUi(ctx) {
|
|
540
|
+
const ui = ctx.ui;
|
|
541
|
+
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
542
|
+
}
|
|
543
|
+
function syncNativeDisplayCwd(ctx, state) {
|
|
544
|
+
const ui = nativePiUi(ctx);
|
|
545
|
+
if (ui?.setDisplayCwd && state.cwd)
|
|
546
|
+
ui.setDisplayCwd(state.cwd);
|
|
547
|
+
}
|
|
548
|
+
function parseExtensionUiRequest(value) {
|
|
549
|
+
const request = recordOf(value) ?? {};
|
|
550
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
551
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
552
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
553
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
554
|
+
const options = rawOptions.map((option) => {
|
|
555
|
+
const record = recordOf(option);
|
|
556
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
557
|
+
}).filter(Boolean);
|
|
558
|
+
return { requestId, method, prompt, options };
|
|
559
|
+
}
|
|
560
|
+
function renderBridgeWidget(state) {
|
|
561
|
+
const statusParts = [
|
|
562
|
+
state.wsConnected ? "live" : "connecting",
|
|
563
|
+
state.status,
|
|
564
|
+
state.model,
|
|
565
|
+
state.cwd
|
|
566
|
+
].filter(Boolean);
|
|
567
|
+
const lines = [`Rig worker session \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
568
|
+
if (state.activity)
|
|
569
|
+
lines.push(state.activity);
|
|
570
|
+
if (state.commands.length > 0) {
|
|
571
|
+
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
572
|
+
}
|
|
573
|
+
lines.push("");
|
|
574
|
+
if (state.transcript.length > 0) {
|
|
575
|
+
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
576
|
+
} else {
|
|
577
|
+
lines.push("Waiting for the worker session transcript\u2026 (/detach exits and leaves the worker running)");
|
|
578
|
+
}
|
|
579
|
+
if (state.pendingUi) {
|
|
580
|
+
lines.push("");
|
|
581
|
+
lines.push(`Worker needs input \xB7 ${state.pendingUi.method}`);
|
|
582
|
+
lines.push(state.pendingUi.prompt);
|
|
583
|
+
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
584
|
+
lines.push("Reply in the editor below. /cancel dismisses this request.");
|
|
585
|
+
}
|
|
586
|
+
return lines;
|
|
587
|
+
}
|
|
588
|
+
function reportBridgeError(ctx, state, message) {
|
|
589
|
+
appendTranscript(state, "Error", message);
|
|
590
|
+
state.status = message;
|
|
591
|
+
try {
|
|
592
|
+
ctx.ui.notify(message, "error");
|
|
593
|
+
} catch {}
|
|
594
|
+
updatePiUi(ctx, state);
|
|
595
|
+
}
|
|
596
|
+
function updatePiUi(ctx, state) {
|
|
597
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
598
|
+
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker session live" : state.status);
|
|
599
|
+
syncNativeDisplayCwd(ctx, state);
|
|
600
|
+
if (state.nativeStream && nativePiUi(ctx)) {
|
|
601
|
+
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
ctx.ui.setWorkingVisible(false);
|
|
605
|
+
ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
|
|
606
|
+
}
|
|
607
|
+
function applyStatus(state, payload) {
|
|
608
|
+
const status = recordOf(payload.status) ?? payload;
|
|
609
|
+
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
610
|
+
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
611
|
+
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
612
|
+
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
613
|
+
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
614
|
+
}
|
|
615
|
+
function applyMessage(state, message) {
|
|
616
|
+
const record = recordOf(message);
|
|
617
|
+
if (!record)
|
|
618
|
+
return;
|
|
619
|
+
const role = String(record.role ?? "system");
|
|
620
|
+
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
621
|
+
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
622
|
+
}
|
|
623
|
+
function applyPiEvent(ctx, state, eventValue) {
|
|
624
|
+
const event = recordOf(eventValue);
|
|
625
|
+
if (!event)
|
|
626
|
+
return;
|
|
627
|
+
const type = String(event.type ?? "event");
|
|
628
|
+
if (type === "agent_start") {
|
|
629
|
+
state.streaming = true;
|
|
630
|
+
state.status = "streaming";
|
|
631
|
+
} else if (type === "agent_end") {
|
|
632
|
+
state.streaming = false;
|
|
633
|
+
state.status = "idle";
|
|
634
|
+
} else if (type === "queue_update") {
|
|
635
|
+
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
636
|
+
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
637
|
+
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
638
|
+
}
|
|
639
|
+
const native = nativePiUi(ctx);
|
|
640
|
+
if (state.nativeStream && native?.emitSessionEvent) {
|
|
641
|
+
native.emitSessionEvent(eventValue);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
if (type === "agent_end") {
|
|
645
|
+
appendTranscript(state, "System", "Agent turn complete.");
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
649
|
+
applyMessage(state, event.message);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
if (type === "message_update") {
|
|
653
|
+
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
654
|
+
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
655
|
+
if (delta)
|
|
656
|
+
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
if (type === "tool_execution_start") {
|
|
660
|
+
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
if (type === "tool_execution_update") {
|
|
664
|
+
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
if (type === "tool_execution_end") {
|
|
668
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
function firstPendingShell(state) {
|
|
672
|
+
return state.pendingShells[0];
|
|
673
|
+
}
|
|
674
|
+
function finishPendingShell(state, shell, result) {
|
|
675
|
+
const index = state.pendingShells.indexOf(shell);
|
|
676
|
+
if (index !== -1)
|
|
677
|
+
state.pendingShells.splice(index, 1);
|
|
678
|
+
shell.resolve(result);
|
|
679
|
+
}
|
|
680
|
+
function failPendingShell(state, shell, error) {
|
|
681
|
+
const index = state.pendingShells.indexOf(shell);
|
|
682
|
+
if (index !== -1)
|
|
683
|
+
state.pendingShells.splice(index, 1);
|
|
684
|
+
shell.reject(error);
|
|
685
|
+
}
|
|
686
|
+
function applyUiEvent(state, value) {
|
|
687
|
+
const event = recordOf(value);
|
|
688
|
+
if (!event)
|
|
689
|
+
return;
|
|
690
|
+
const type = String(event.type ?? "ui");
|
|
691
|
+
if (type === "shell.chunk") {
|
|
692
|
+
const pending = firstPendingShell(state);
|
|
693
|
+
const chunk = asText(event.chunk);
|
|
694
|
+
if (pending) {
|
|
695
|
+
pending.sawChunk = true;
|
|
696
|
+
pending.onData(Buffer.from(chunk));
|
|
697
|
+
} else {
|
|
698
|
+
appendTranscript(state, "Tool", chunk);
|
|
699
|
+
}
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
if (type === "shell.end") {
|
|
703
|
+
const pending = firstPendingShell(state);
|
|
704
|
+
const output = asText(event.output ?? "");
|
|
705
|
+
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
706
|
+
if (pending) {
|
|
707
|
+
if (output && !pending.sawChunk)
|
|
708
|
+
pending.onData(Buffer.from(output));
|
|
709
|
+
finishPendingShell(state, pending, { exitCode });
|
|
710
|
+
} else {
|
|
711
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
712
|
+
}
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (type === "shell.start") {
|
|
716
|
+
if (!firstPendingShell(state))
|
|
717
|
+
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
721
|
+
}
|
|
722
|
+
function applyEnvelope(ctx, state, envelopeValue) {
|
|
723
|
+
const envelope = recordOf(envelopeValue);
|
|
724
|
+
if (!envelope)
|
|
725
|
+
return;
|
|
726
|
+
const type = String(envelope.type ?? "");
|
|
727
|
+
if (type === "ready") {
|
|
728
|
+
const metadata = recordOf(envelope.metadata);
|
|
729
|
+
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
730
|
+
state.status = "worker Pi daemon ready";
|
|
731
|
+
if (!state.nativeStream)
|
|
732
|
+
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
733
|
+
} else if (type === "status.update") {
|
|
734
|
+
applyStatus(state, envelope);
|
|
735
|
+
} else if (type === "activity.update") {
|
|
736
|
+
const activity = recordOf(envelope.activity);
|
|
737
|
+
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
738
|
+
} else if (type === "extension_ui_request") {
|
|
739
|
+
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
740
|
+
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
741
|
+
} else if (type === "pi.ui_event") {
|
|
742
|
+
applyUiEvent(state, envelope.event);
|
|
743
|
+
} else if (type === "pi.event") {
|
|
744
|
+
applyPiEvent(ctx, state, envelope.event);
|
|
745
|
+
} else if (type === "error") {
|
|
746
|
+
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
747
|
+
}
|
|
748
|
+
syncNativeDisplayCwd(ctx, state);
|
|
749
|
+
}
|
|
750
|
+
function resolveAttachReadyTimeoutMs() {
|
|
751
|
+
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
752
|
+
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
753
|
+
}
|
|
754
|
+
function formatElapsed(sinceMs) {
|
|
755
|
+
const totalSeconds = Math.floor((Date.now() - sinceMs) / 1000);
|
|
756
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
757
|
+
const seconds = totalSeconds % 60;
|
|
758
|
+
return minutes > 0 ? `${minutes}m${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
|
|
759
|
+
}
|
|
760
|
+
async function waitForWorkerReady(options, ctx, state) {
|
|
761
|
+
const startedAt = Date.now();
|
|
762
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
763
|
+
let consecutiveFailures = 0;
|
|
764
|
+
while (true) {
|
|
765
|
+
let requestFailed = false;
|
|
766
|
+
const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => {
|
|
767
|
+
requestFailed = true;
|
|
768
|
+
return {
|
|
769
|
+
ready: false,
|
|
770
|
+
status: error instanceof Error ? error.message : String(error),
|
|
771
|
+
retryAfterMs: 1000
|
|
772
|
+
};
|
|
773
|
+
});
|
|
774
|
+
if (session.ready === false) {
|
|
775
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
776
|
+
const status = String(session.status ?? "starting");
|
|
777
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
778
|
+
reportBridgeError(ctx, state, `Run ended before worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${options.runId}\`; restart with \`rig task run --task <id>\`.`);
|
|
779
|
+
return false;
|
|
780
|
+
}
|
|
781
|
+
if (consecutiveFailures >= 5) {
|
|
782
|
+
state.status = `Rig server unreachable \xB7 retrying (${formatElapsed(startedAt)}) \xB7 /detach to exit`;
|
|
783
|
+
} else {
|
|
784
|
+
state.status = `waiting for worker Pi daemon \xB7 ${status} \xB7 ${formatElapsed(startedAt)} \xB7 /detach to exit`;
|
|
785
|
+
}
|
|
786
|
+
updatePiUi(ctx, state);
|
|
787
|
+
if (Date.now() >= deadline) {
|
|
788
|
+
reportBridgeError(ctx, state, `Worker Pi daemon did not become ready within ${formatElapsed(startedAt)} (last status: ${status}). ` + `Check \`rig run show ${options.runId}\` and \`rig doctor\`; the run may have been restarted by a server deploy. ` + "Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.");
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
const sessionRecord = recordOf(session) ?? {};
|
|
795
|
+
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
796
|
+
updatePiUi(ctx, state);
|
|
797
|
+
return true;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
function parseWsPayload(message) {
|
|
801
|
+
if (typeof message.data === "string")
|
|
802
|
+
return JSON.parse(message.data);
|
|
803
|
+
return JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
804
|
+
}
|
|
805
|
+
var BRIDGE_LOCAL_COMMANDS = new Set(["detach", "quit", "q", "stop"]);
|
|
806
|
+
function registerDaemonCommandsNatively(pi, options, ctx, state, commands, registered) {
|
|
807
|
+
for (const command of commands) {
|
|
808
|
+
const record = recordOf(command);
|
|
809
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
810
|
+
if (!name || registered.has(name) || BRIDGE_LOCAL_COMMANDS.has(name))
|
|
811
|
+
continue;
|
|
812
|
+
registered.add(name);
|
|
813
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
814
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
815
|
+
try {
|
|
816
|
+
pi.registerCommand(name, {
|
|
817
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
818
|
+
handler: async (args) => {
|
|
819
|
+
const text = `/${name}${args ? ` ${args}` : ""}`;
|
|
820
|
+
appendTranscript(state, "You", text);
|
|
821
|
+
try {
|
|
822
|
+
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
823
|
+
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
824
|
+
appendTranscript(state, "System", message);
|
|
825
|
+
if (state.nativeStream)
|
|
826
|
+
ctx.ui.notify(message, "info");
|
|
827
|
+
} catch (error) {
|
|
828
|
+
reportBridgeError(ctx, state, error instanceof Error ? error.message : String(error));
|
|
829
|
+
}
|
|
830
|
+
updatePiUi(ctx, state);
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
} catch {}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
async function connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands) {
|
|
837
|
+
const ready = await waitForWorkerReady(options, ctx, state);
|
|
838
|
+
if (!ready)
|
|
839
|
+
return;
|
|
840
|
+
let catchupDone = false;
|
|
841
|
+
const buffered = [];
|
|
842
|
+
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
843
|
+
const socket = new WebSocket(wsUrl);
|
|
844
|
+
const closePromise = new Promise((resolve3) => {
|
|
845
|
+
socket.onopen = () => {
|
|
846
|
+
state.wsConnected = true;
|
|
847
|
+
state.status = "live worker Pi WebSocket connected";
|
|
848
|
+
updatePiUi(ctx, state);
|
|
849
|
+
};
|
|
850
|
+
socket.onmessage = (message) => {
|
|
851
|
+
try {
|
|
852
|
+
const payload = parseWsPayload(message);
|
|
853
|
+
if (!catchupDone)
|
|
854
|
+
buffered.push(payload);
|
|
855
|
+
else {
|
|
856
|
+
applyEnvelope(ctx, state, payload);
|
|
857
|
+
updatePiUi(ctx, state);
|
|
858
|
+
}
|
|
859
|
+
} catch (error) {
|
|
860
|
+
appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
861
|
+
updatePiUi(ctx, state);
|
|
862
|
+
}
|
|
863
|
+
};
|
|
864
|
+
socket.onerror = () => socket.close();
|
|
865
|
+
socket.onclose = () => {
|
|
866
|
+
state.wsConnected = false;
|
|
867
|
+
state.status = "worker Pi WebSocket disconnected";
|
|
868
|
+
updatePiUi(ctx, state);
|
|
869
|
+
resolve3();
|
|
870
|
+
};
|
|
871
|
+
});
|
|
872
|
+
try {
|
|
873
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
874
|
+
getRunPiMessagesViaServer(options.context, options.runId),
|
|
875
|
+
getRunPiStatusViaServer(options.context, options.runId),
|
|
876
|
+
getRunPiCommandsViaServer(options.context, options.runId)
|
|
877
|
+
]);
|
|
878
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
879
|
+
const native = nativePiUi(ctx);
|
|
880
|
+
if (state.nativeStream && native?.appendSessionMessages)
|
|
881
|
+
native.appendSessionMessages(messages);
|
|
882
|
+
else
|
|
883
|
+
for (const message of messages)
|
|
884
|
+
applyMessage(state, message);
|
|
885
|
+
applyStatus(state, statusPayload);
|
|
886
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
887
|
+
state.commands = commands.flatMap((command) => {
|
|
888
|
+
const record = recordOf(command);
|
|
889
|
+
return typeof record?.name === "string" ? [`/${record.name}`] : [];
|
|
890
|
+
});
|
|
891
|
+
registerDaemonCommandsNatively(pi, options, ctx, state, commands, registeredDaemonCommands);
|
|
892
|
+
catchupDone = true;
|
|
893
|
+
for (const payload of buffered.splice(0))
|
|
894
|
+
applyEnvelope(ctx, state, payload);
|
|
895
|
+
updatePiUi(ctx, state);
|
|
896
|
+
} catch (error) {
|
|
897
|
+
appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
898
|
+
catchupDone = true;
|
|
899
|
+
updatePiUi(ctx, state);
|
|
900
|
+
}
|
|
901
|
+
await closePromise;
|
|
902
|
+
}
|
|
903
|
+
function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
904
|
+
return {
|
|
905
|
+
exec(command, _cwd, execOptions) {
|
|
906
|
+
return new Promise((resolve3, reject) => {
|
|
907
|
+
const pending = {
|
|
908
|
+
command,
|
|
909
|
+
onData: execOptions.onData,
|
|
910
|
+
resolve: resolve3,
|
|
911
|
+
reject,
|
|
912
|
+
sawChunk: false
|
|
913
|
+
};
|
|
914
|
+
const cleanup = () => {
|
|
915
|
+
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
916
|
+
if (timer)
|
|
917
|
+
clearTimeout(timer);
|
|
918
|
+
};
|
|
919
|
+
const onAbort = () => {
|
|
920
|
+
cleanup();
|
|
921
|
+
failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
|
|
922
|
+
};
|
|
923
|
+
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
924
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
925
|
+
cleanup();
|
|
926
|
+
failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
927
|
+
}, timeoutMs) : null;
|
|
928
|
+
const wrappedResolve = pending.resolve;
|
|
929
|
+
const wrappedReject = pending.reject;
|
|
930
|
+
pending.resolve = (result) => {
|
|
931
|
+
cleanup();
|
|
932
|
+
wrappedResolve(result);
|
|
933
|
+
};
|
|
934
|
+
pending.reject = (error) => {
|
|
935
|
+
cleanup();
|
|
936
|
+
wrappedReject(error);
|
|
937
|
+
};
|
|
938
|
+
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
939
|
+
state.pendingShells.push(pending);
|
|
940
|
+
sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
941
|
+
cleanup();
|
|
942
|
+
failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
|
|
943
|
+
});
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
async function answerPendingUi(options, state, line) {
|
|
949
|
+
const pending = state.pendingUi;
|
|
950
|
+
if (!pending)
|
|
951
|
+
return false;
|
|
952
|
+
if (line === "/cancel") {
|
|
953
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
954
|
+
} else if (pending.method === "confirm") {
|
|
955
|
+
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
956
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
957
|
+
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
958
|
+
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
959
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
960
|
+
} else {
|
|
961
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
962
|
+
}
|
|
963
|
+
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
964
|
+
state.pendingUi = null;
|
|
965
|
+
return true;
|
|
966
|
+
}
|
|
967
|
+
async function routeInput(options, ctx, state, line) {
|
|
968
|
+
const text = line.trim();
|
|
969
|
+
if (!text)
|
|
970
|
+
return;
|
|
971
|
+
if (await answerPendingUi(options, state, text)) {
|
|
972
|
+
updatePiUi(ctx, state);
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
if (text === "/detach" || text === "/quit" || text === "/q") {
|
|
976
|
+
appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
|
|
977
|
+
updatePiUi(ctx, state);
|
|
978
|
+
ctx.shutdown();
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
if (text === "/stop") {
|
|
982
|
+
await abortRunPiViaServer(options.context, options.runId);
|
|
983
|
+
appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
|
|
984
|
+
updatePiUi(ctx, state);
|
|
985
|
+
ctx.shutdown();
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
if (text.startsWith("!")) {
|
|
989
|
+
appendTranscript(state, "You", text);
|
|
990
|
+
await sendRunPiShellViaServer(options.context, options.runId, text);
|
|
991
|
+
} else if (text.startsWith("/")) {
|
|
992
|
+
appendTranscript(state, "You", text);
|
|
993
|
+
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
994
|
+
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
995
|
+
appendTranscript(state, "System", message);
|
|
996
|
+
} else {
|
|
997
|
+
appendTranscript(state, "You", text);
|
|
998
|
+
await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
|
|
999
|
+
}
|
|
1000
|
+
updatePiUi(ctx, state);
|
|
1001
|
+
}
|
|
1002
|
+
function createRigWorkerPiBridgeExtension(options) {
|
|
1003
|
+
return (pi) => {
|
|
1004
|
+
const state = {
|
|
1005
|
+
transcript: [],
|
|
1006
|
+
status: "starting worker Pi daemon bridge",
|
|
1007
|
+
activity: "",
|
|
1008
|
+
cwd: "",
|
|
1009
|
+
model: "",
|
|
1010
|
+
commands: [],
|
|
1011
|
+
streaming: false,
|
|
1012
|
+
pendingUi: null,
|
|
1013
|
+
pendingShells: [],
|
|
1014
|
+
wsConnected: false,
|
|
1015
|
+
nativeStream: false
|
|
1016
|
+
};
|
|
1017
|
+
if (options.initialMessageSent)
|
|
1018
|
+
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
1019
|
+
const registeredDaemonCommands = new Set;
|
|
1020
|
+
let nativePiUiContextAvailable = false;
|
|
1021
|
+
pi.on("user_bash", (event) => {
|
|
1022
|
+
state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
|
|
1023
|
+
return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
|
|
1024
|
+
});
|
|
1025
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1026
|
+
nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
|
|
1027
|
+
state.nativeStream = nativePiUiContextAvailable;
|
|
1028
|
+
updatePiUi(ctx, state);
|
|
1029
|
+
ctx.ui.notify(nativePiUiContextAvailable ? "Connected to the Rig worker session (native stream). /detach exits, /stop cancels the run." : "Connected to the Rig worker session (transcript view). /detach exits, /stop cancels the run.", "info");
|
|
1030
|
+
ctx.ui.onTerminalInput((data) => {
|
|
1031
|
+
if (data.includes("\x04")) {
|
|
1032
|
+
ctx.shutdown();
|
|
1033
|
+
return { consume: true };
|
|
1034
|
+
}
|
|
1035
|
+
if (!data.includes("\r") && !data.includes(`
|
|
1036
|
+
`))
|
|
1037
|
+
return;
|
|
1038
|
+
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
1039
|
+
const editorText = ctx.ui.getEditorText().trim();
|
|
1040
|
+
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
1041
|
+
if (!text)
|
|
1042
|
+
return;
|
|
1043
|
+
if (text.startsWith("!"))
|
|
1044
|
+
return;
|
|
1045
|
+
ctx.ui.setEditorText("");
|
|
1046
|
+
routeInput(options, ctx, state, text).catch((error) => {
|
|
1047
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1048
|
+
updatePiUi(ctx, state);
|
|
1049
|
+
});
|
|
1050
|
+
return { consume: true };
|
|
1051
|
+
});
|
|
1052
|
+
connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands).catch((error) => {
|
|
1053
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1054
|
+
updatePiUi(ctx, state);
|
|
1055
|
+
});
|
|
1056
|
+
});
|
|
1057
|
+
pi.on("session_shutdown", () => {});
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
1062
|
+
function setTemporaryEnv(updates) {
|
|
1063
|
+
const previous = new Map;
|
|
1064
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
1065
|
+
previous.set(key, process.env[key]);
|
|
1066
|
+
process.env[key] = value;
|
|
1067
|
+
}
|
|
1068
|
+
return () => {
|
|
1069
|
+
for (const [key, value] of previous) {
|
|
1070
|
+
if (value === undefined)
|
|
1071
|
+
delete process.env[key];
|
|
1072
|
+
else
|
|
1073
|
+
process.env[key] = value;
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
async function attachRunBundledPiFrontend(context, input) {
|
|
1078
|
+
const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
|
|
1079
|
+
const cwd = join(tempRoot, "workspace");
|
|
1080
|
+
const agentDir = join(tempRoot, "agent");
|
|
1081
|
+
const sessionDir = join(tempRoot, "sessions");
|
|
1082
|
+
const previousCwd = process.cwd();
|
|
1083
|
+
const restoreEnv = setTemporaryEnv({
|
|
1084
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
1085
|
+
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
1086
|
+
PI_OFFLINE: "1",
|
|
1087
|
+
PI_SKIP_VERSION_CHECK: "1"
|
|
1088
|
+
});
|
|
1089
|
+
let detached = false;
|
|
1090
|
+
try {
|
|
1091
|
+
await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
|
|
1092
|
+
process.chdir(cwd);
|
|
1093
|
+
await runPiMain([
|
|
1094
|
+
"--offline",
|
|
1095
|
+
"--no-session",
|
|
1096
|
+
"--no-tools",
|
|
1097
|
+
"--no-builtin-tools",
|
|
1098
|
+
"--no-skills",
|
|
1099
|
+
"--no-context-files",
|
|
1100
|
+
"--no-approve"
|
|
1101
|
+
], {
|
|
1102
|
+
extensionFactories: [
|
|
1103
|
+
createRigWorkerPiBridgeExtension({
|
|
1104
|
+
context,
|
|
1105
|
+
runId: input.runId,
|
|
1106
|
+
initialMessageSent: input.steered === true
|
|
1107
|
+
})
|
|
1108
|
+
]
|
|
1109
|
+
});
|
|
1110
|
+
detached = true;
|
|
1111
|
+
} finally {
|
|
1112
|
+
process.chdir(previousCwd);
|
|
1113
|
+
restoreEnv();
|
|
1114
|
+
rmSync(tempRoot, { recursive: true, force: true });
|
|
1115
|
+
}
|
|
1116
|
+
let run = { runId: input.runId, status: "unknown" };
|
|
1117
|
+
try {
|
|
1118
|
+
run = await getRunDetailsViaServer(context, input.runId);
|
|
1119
|
+
} catch {}
|
|
1120
|
+
return {
|
|
1121
|
+
run,
|
|
1122
|
+
logs: [],
|
|
1123
|
+
timeline: [],
|
|
1124
|
+
timelineCursor: null,
|
|
1125
|
+
steered: input.steered === true,
|
|
1126
|
+
detached,
|
|
1127
|
+
rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// packages/cli/src/commands/_operator-view.ts
|
|
1132
|
+
var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
266
1133
|
function runStatusFromPayload(payload) {
|
|
267
1134
|
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
268
1135
|
return String(run.status ?? "unknown").toLowerCase();
|
|
@@ -284,57 +1151,76 @@ async function applyOperatorCommand(context, input, deps = {}) {
|
|
|
284
1151
|
await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
|
|
285
1152
|
return { action: "continue", message: "Steering message queued." };
|
|
286
1153
|
}
|
|
287
|
-
async function readOperatorSnapshot(context, runId) {
|
|
1154
|
+
async function readOperatorSnapshot(context, runId, options = {}) {
|
|
288
1155
|
const run = await getRunDetailsViaServer(context, runId);
|
|
289
1156
|
const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
|
|
290
|
-
const
|
|
291
|
-
|
|
1157
|
+
const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
|
|
1158
|
+
entries: [{
|
|
1159
|
+
id: `timeline-unavailable:${runId}`,
|
|
1160
|
+
type: "timeline_warning",
|
|
1161
|
+
detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
|
|
1162
|
+
createdAt: new Date().toISOString()
|
|
1163
|
+
}],
|
|
1164
|
+
nextCursor: options.timelineCursor ?? null
|
|
1165
|
+
}));
|
|
1166
|
+
const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
|
|
1167
|
+
const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1168
|
+
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
1169
|
+
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
292
1170
|
}
|
|
293
1171
|
async function attachRunOperatorView(context, input) {
|
|
294
1172
|
let steered = false;
|
|
295
1173
|
if (input.message?.trim()) {
|
|
296
|
-
await steerRunViaServer(context, input.runId, input.message.trim());
|
|
1174
|
+
await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
|
|
297
1175
|
steered = true;
|
|
298
1176
|
}
|
|
1177
|
+
if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
1178
|
+
return attachRunBundledPiFrontend(context, {
|
|
1179
|
+
runId: input.runId,
|
|
1180
|
+
steered
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
299
1184
|
let snapshot = await readOperatorSnapshot(context, input.runId);
|
|
300
1185
|
if (context.outputMode === "text") {
|
|
301
|
-
|
|
1186
|
+
surface.renderSnapshot(snapshot);
|
|
1187
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1188
|
+
surface.renderLogs(snapshot.logs);
|
|
302
1189
|
if (steered)
|
|
303
|
-
|
|
1190
|
+
surface.info("Message submitted to worker Pi.");
|
|
304
1191
|
}
|
|
305
1192
|
let detached = false;
|
|
306
|
-
let
|
|
1193
|
+
let commandInput = null;
|
|
307
1194
|
if (input.follow && !input.once && context.outputMode === "text") {
|
|
308
1195
|
if (input.interactive !== false && process.stdin.isTTY) {
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
}).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
1196
|
+
surface.info("Controls: /user <message>, /stop, /detach");
|
|
1197
|
+
commandInput = surface.attachCommandInput(async (line) => {
|
|
1198
|
+
const result = await applyOperatorCommand(context, { runId: input.runId, line });
|
|
1199
|
+
if (result.message)
|
|
1200
|
+
surface.info(result.message);
|
|
1201
|
+
if (result.action === "detach" || result.action === "stopped") {
|
|
1202
|
+
detached = true;
|
|
1203
|
+
commandInput?.close();
|
|
1204
|
+
}
|
|
320
1205
|
});
|
|
321
1206
|
}
|
|
322
|
-
let lastRendered = snapshot.rendered;
|
|
323
1207
|
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
324
|
-
|
|
1208
|
+
let timelineCursor = snapshot.timelineCursor;
|
|
1209
|
+
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
325
1210
|
await Bun.sleep(pollMs);
|
|
326
|
-
snapshot = await readOperatorSnapshot(context, input.runId);
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
1211
|
+
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
1212
|
+
timelineCursor = snapshot.timelineCursor;
|
|
1213
|
+
surface.renderSnapshot(snapshot);
|
|
1214
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1215
|
+
surface.renderLogs(snapshot.logs);
|
|
331
1216
|
}
|
|
332
|
-
|
|
1217
|
+
commandInput?.close();
|
|
333
1218
|
}
|
|
334
1219
|
return { ...snapshot, steered, detached };
|
|
335
1220
|
}
|
|
336
1221
|
export {
|
|
337
1222
|
renderOperatorSnapshot,
|
|
1223
|
+
createPiRunStreamRenderer,
|
|
338
1224
|
attachRunOperatorView,
|
|
339
1225
|
applyOperatorCommand
|
|
340
1226
|
};
|