@h-rig/cli 0.0.6-alpha.5 → 0.0.6-alpha.50
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 +4072 -1204
- package/dist/src/commands/_cli-format.js +369 -0
- package/dist/src/commands/_connection-state.js +12 -6
- package/dist/src/commands/_doctor-checks.js +65 -34
- 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 +1109 -63
- package/dist/src/commands/_parsers.js +0 -2
- package/dist/src/commands/_pi-frontend.js +1066 -0
- package/dist/src/commands/_pi-install.js +4 -3
- package/dist/src/commands/_pi-remote-session.js +757 -0
- package/dist/src/commands/_pi-worker-bridge-extension.js +820 -0
- package/dist/src/commands/_policy.js +0 -2
- package/dist/src/commands/_preflight.js +84 -116
- package/dist/src/commands/_run-driver-helpers.js +2 -2
- package/dist/src/commands/_server-client.js +211 -48
- package/dist/src/commands/_snapshot-upload.js +60 -30
- package/dist/src/commands/_spinner.js +63 -0
- 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 +134 -26
- package/dist/src/commands/dist.js +4 -6
- package/dist/src/commands/doctor.js +65 -34
- package/dist/src/commands/github.js +62 -32
- package/dist/src/commands/inbox.js +396 -31
- package/dist/src/commands/init.js +342 -88
- package/dist/src/commands/inspect.js +282 -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 +1407 -130
- package/dist/src/commands/server.js +266 -40
- package/dist/src/commands/setup.js +69 -44
- package/dist/src/commands/task-report-bug.js +5 -7
- package/dist/src/commands/task-run-driver.js +662 -70
- package/dist/src/commands/task.js +1846 -259
- package/dist/src/commands/test.js +3 -5
- package/dist/src/commands/workspace.js +4 -6
- package/dist/src/commands.js +4054 -1180
- package/dist/src/index.js +4065 -1200
- 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 +7 -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
|
|
|
@@ -44,6 +38,11 @@ function readJsonFile(path) {
|
|
|
44
38
|
throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
45
39
|
}
|
|
46
40
|
}
|
|
41
|
+
function writeJsonFile(path, value) {
|
|
42
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
43
|
+
writeFileSync(path, `${JSON.stringify(value, null, 2)}
|
|
44
|
+
`, "utf8");
|
|
45
|
+
}
|
|
47
46
|
function normalizeConnection(value) {
|
|
48
47
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
49
48
|
return null;
|
|
@@ -84,25 +83,35 @@ function readRepoConnection(projectRoot) {
|
|
|
84
83
|
return {
|
|
85
84
|
selected,
|
|
86
85
|
project: typeof record.project === "string" ? record.project : undefined,
|
|
87
|
-
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
|
|
86
|
+
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
|
|
87
|
+
serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
|
|
88
88
|
};
|
|
89
89
|
}
|
|
90
|
+
function writeRepoConnection(projectRoot, state) {
|
|
91
|
+
writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
|
|
92
|
+
}
|
|
90
93
|
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
91
94
|
const repo = readRepoConnection(projectRoot);
|
|
92
95
|
if (!repo)
|
|
93
96
|
return null;
|
|
94
97
|
if (repo.selected === "local")
|
|
95
|
-
return { alias: "local", connection: { kind: "local", mode: "auto" } };
|
|
98
|
+
return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
|
|
96
99
|
const global = readGlobalConnections(options);
|
|
97
100
|
const connection = global.connections[repo.selected];
|
|
98
101
|
if (!connection) {
|
|
99
|
-
throw new CliError2(`Selected Rig
|
|
102
|
+
throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
100
103
|
}
|
|
101
|
-
return { alias: repo.selected, connection };
|
|
104
|
+
return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
|
|
105
|
+
}
|
|
106
|
+
function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
|
|
107
|
+
const repo = readRepoConnection(projectRoot);
|
|
108
|
+
if (!repo)
|
|
109
|
+
return;
|
|
110
|
+
writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
|
|
102
111
|
}
|
|
103
112
|
|
|
104
113
|
// packages/cli/src/commands/_server-client.ts
|
|
105
|
-
var
|
|
114
|
+
var scopedGitHubBearerTokens = new Map;
|
|
106
115
|
function cleanToken(value) {
|
|
107
116
|
const trimmed = value?.trim();
|
|
108
117
|
return trimmed ? trimmed : null;
|
|
@@ -119,41 +128,33 @@ function readPrivateRemoteSessionToken(projectRoot) {
|
|
|
119
128
|
}
|
|
120
129
|
}
|
|
121
130
|
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
122
|
-
|
|
123
|
-
|
|
131
|
+
const scopedKey = resolve2(projectRoot);
|
|
132
|
+
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
133
|
+
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
124
134
|
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;
|
|
135
|
+
if (privateSession)
|
|
136
|
+
return privateSession;
|
|
137
|
+
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
141
138
|
}
|
|
142
139
|
async function ensureServerForCli(projectRoot) {
|
|
143
140
|
try {
|
|
144
141
|
const selected = resolveSelectedConnection(projectRoot);
|
|
145
142
|
if (selected?.connection.kind === "remote") {
|
|
143
|
+
const authToken = readGitHubBearerTokenForRemote(projectRoot);
|
|
144
|
+
const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
|
|
146
145
|
return {
|
|
147
146
|
baseUrl: selected.connection.baseUrl,
|
|
148
|
-
authToken
|
|
149
|
-
connectionKind: "remote"
|
|
147
|
+
authToken,
|
|
148
|
+
connectionKind: "remote",
|
|
149
|
+
serverProjectRoot
|
|
150
150
|
};
|
|
151
151
|
}
|
|
152
152
|
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
153
153
|
return {
|
|
154
154
|
baseUrl: connection.baseUrl,
|
|
155
155
|
authToken: connection.authToken,
|
|
156
|
-
connectionKind: "local"
|
|
156
|
+
connectionKind: "local",
|
|
157
|
+
serverProjectRoot: resolve2(projectRoot)
|
|
157
158
|
};
|
|
158
159
|
} catch (error) {
|
|
159
160
|
if (error instanceof Error) {
|
|
@@ -162,6 +163,29 @@ async function ensureServerForCli(projectRoot) {
|
|
|
162
163
|
throw error;
|
|
163
164
|
}
|
|
164
165
|
}
|
|
166
|
+
async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
|
|
167
|
+
const repo = readRepoConnection(projectRoot);
|
|
168
|
+
const slug = repo?.project?.trim();
|
|
169
|
+
if (!slug)
|
|
170
|
+
return null;
|
|
171
|
+
try {
|
|
172
|
+
const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
|
|
173
|
+
headers: mergeHeaders(undefined, authToken)
|
|
174
|
+
});
|
|
175
|
+
if (!response.ok)
|
|
176
|
+
return null;
|
|
177
|
+
const payload = await response.json();
|
|
178
|
+
const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
|
|
179
|
+
const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
|
|
180
|
+
const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
|
|
181
|
+
const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
|
|
182
|
+
if (path)
|
|
183
|
+
writeRepoServerProjectRoot(projectRoot, path);
|
|
184
|
+
return path;
|
|
185
|
+
} catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
165
189
|
function mergeHeaders(headers, authToken) {
|
|
166
190
|
const merged = new Headers(headers);
|
|
167
191
|
if (authToken) {
|
|
@@ -186,9 +210,12 @@ function diagnosticMessage(payload) {
|
|
|
186
210
|
}
|
|
187
211
|
async function requestServerJson(context, pathname, init = {}) {
|
|
188
212
|
const server = await ensureServerForCli(context.projectRoot);
|
|
213
|
+
const headers = mergeHeaders(init.headers, server.authToken);
|
|
214
|
+
if (server.serverProjectRoot)
|
|
215
|
+
headers.set("x-rig-project-root", server.serverProjectRoot);
|
|
189
216
|
const response = await fetch(`${server.baseUrl}${pathname}`, {
|
|
190
217
|
...init,
|
|
191
|
-
headers
|
|
218
|
+
headers
|
|
192
219
|
});
|
|
193
220
|
const text = await response.text();
|
|
194
221
|
const payload = text.trim().length > 0 ? (() => {
|
|
@@ -218,6 +245,15 @@ async function getRunLogsViaServer(context, runId, options = {}) {
|
|
|
218
245
|
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
219
246
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
220
247
|
}
|
|
248
|
+
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
249
|
+
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
250
|
+
if (options.limit !== undefined)
|
|
251
|
+
url.searchParams.set("limit", String(options.limit));
|
|
252
|
+
if (options.cursor)
|
|
253
|
+
url.searchParams.set("cursor", options.cursor);
|
|
254
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
255
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
256
|
+
}
|
|
221
257
|
async function stopRunViaServer(context, runId) {
|
|
222
258
|
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
223
259
|
method: "POST",
|
|
@@ -234,9 +270,75 @@ async function steerRunViaServer(context, runId, message) {
|
|
|
234
270
|
});
|
|
235
271
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
236
272
|
}
|
|
273
|
+
async function getRunPiSessionViaServer(context, runId) {
|
|
274
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
275
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
276
|
+
}
|
|
277
|
+
async function getRunPiMessagesViaServer(context, runId) {
|
|
278
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
279
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
280
|
+
}
|
|
281
|
+
async function getRunPiStatusViaServer(context, runId) {
|
|
282
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
283
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
284
|
+
}
|
|
285
|
+
async function getRunPiCommandsViaServer(context, runId) {
|
|
286
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
287
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
288
|
+
}
|
|
289
|
+
async function getRunPiCapabilitiesViaServer(context, runId) {
|
|
290
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
|
|
291
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
|
|
292
|
+
}
|
|
293
|
+
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
294
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
295
|
+
method: "POST",
|
|
296
|
+
headers: { "content-type": "application/json" },
|
|
297
|
+
body: JSON.stringify({ text, streamingBehavior })
|
|
298
|
+
});
|
|
299
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
300
|
+
}
|
|
301
|
+
async function sendRunPiShellViaServer(context, runId, text) {
|
|
302
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
303
|
+
method: "POST",
|
|
304
|
+
headers: { "content-type": "application/json" },
|
|
305
|
+
body: JSON.stringify({ text })
|
|
306
|
+
});
|
|
307
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
308
|
+
}
|
|
309
|
+
async function runRunPiCommandViaServer(context, runId, text) {
|
|
310
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
311
|
+
method: "POST",
|
|
312
|
+
headers: { "content-type": "application/json" },
|
|
313
|
+
body: JSON.stringify({ text })
|
|
314
|
+
});
|
|
315
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
316
|
+
}
|
|
317
|
+
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
318
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
319
|
+
method: "POST",
|
|
320
|
+
headers: { "content-type": "application/json" },
|
|
321
|
+
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
322
|
+
});
|
|
323
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
324
|
+
}
|
|
325
|
+
async function abortRunPiViaServer(context, runId) {
|
|
326
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
327
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
328
|
+
}
|
|
329
|
+
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
330
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
331
|
+
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
332
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
333
|
+
if (server.authToken)
|
|
334
|
+
url.searchParams.set("token", server.authToken);
|
|
335
|
+
if (server.serverProjectRoot)
|
|
336
|
+
url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
|
|
337
|
+
return url.toString();
|
|
338
|
+
}
|
|
237
339
|
|
|
238
|
-
// packages/cli/src/commands/_operator-
|
|
239
|
-
|
|
340
|
+
// packages/cli/src/commands/_operator-surface.ts
|
|
341
|
+
import { createInterface } from "readline";
|
|
240
342
|
var CANONICAL_STAGES = [
|
|
241
343
|
"Connect",
|
|
242
344
|
"GitHub/task sync",
|
|
@@ -251,18 +353,943 @@ var CANONICAL_STAGES = [
|
|
|
251
353
|
"Merge",
|
|
252
354
|
"Complete"
|
|
253
355
|
];
|
|
356
|
+
function logDetail(log) {
|
|
357
|
+
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
358
|
+
}
|
|
359
|
+
function parseProviderProtocolLog(title, detail) {
|
|
360
|
+
if (title.trim().toLowerCase() !== "agent output")
|
|
361
|
+
return null;
|
|
362
|
+
if (!detail.startsWith("{") || !detail.endsWith("}"))
|
|
363
|
+
return null;
|
|
364
|
+
try {
|
|
365
|
+
const record = JSON.parse(detail);
|
|
366
|
+
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
367
|
+
return null;
|
|
368
|
+
const type = record.type;
|
|
369
|
+
return typeof type === "string" && [
|
|
370
|
+
"assistant",
|
|
371
|
+
"message_start",
|
|
372
|
+
"message_update",
|
|
373
|
+
"message_end",
|
|
374
|
+
"stream_event",
|
|
375
|
+
"tool_result",
|
|
376
|
+
"tool_execution_start",
|
|
377
|
+
"tool_execution_update",
|
|
378
|
+
"tool_execution_end",
|
|
379
|
+
"turn_start",
|
|
380
|
+
"turn_end"
|
|
381
|
+
].includes(type) ? record : null;
|
|
382
|
+
} catch {
|
|
383
|
+
return null;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
function renderProviderProtocolLog(record) {
|
|
387
|
+
const type = typeof record.type === "string" ? record.type : "";
|
|
388
|
+
if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
|
|
389
|
+
const toolName = String(record.toolName ?? record.name ?? "tool");
|
|
390
|
+
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";
|
|
391
|
+
return `[Pi tool] ${toolName} ${status}`;
|
|
392
|
+
}
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
function entryId(entry, fallback) {
|
|
396
|
+
return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
|
|
397
|
+
}
|
|
254
398
|
function renderOperatorSnapshot(snapshot) {
|
|
255
399
|
const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
|
|
256
400
|
const runId = String(run.runId ?? run.id ?? "run");
|
|
257
401
|
const status = String(run.status ?? "unknown");
|
|
258
402
|
const logs = snapshot.logs ?? [];
|
|
403
|
+
const latestByStage = new Map;
|
|
404
|
+
for (const log of logs) {
|
|
405
|
+
const title = String(log.title ?? "").toLowerCase();
|
|
406
|
+
const stageName = String(log.stage ?? "").toLowerCase();
|
|
407
|
+
const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
408
|
+
if (stage)
|
|
409
|
+
latestByStage.set(stage, log);
|
|
410
|
+
}
|
|
259
411
|
const stageLines = CANONICAL_STAGES.flatMap((stage) => {
|
|
260
|
-
const match =
|
|
261
|
-
return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
|
|
412
|
+
const match = latestByStage.get(stage);
|
|
413
|
+
return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
|
|
262
414
|
});
|
|
263
415
|
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
264
416
|
`);
|
|
265
417
|
}
|
|
418
|
+
function createPiRunStreamRenderer(output = process.stdout) {
|
|
419
|
+
let lastSnapshot = "";
|
|
420
|
+
const assistantTextById = new Map;
|
|
421
|
+
const seenTimeline = new Set;
|
|
422
|
+
const seenLogs = new Set;
|
|
423
|
+
const writeLine = (line) => output.write(`${line}
|
|
424
|
+
`);
|
|
425
|
+
return {
|
|
426
|
+
renderSnapshot(snapshot) {
|
|
427
|
+
const rendered = renderOperatorSnapshot(snapshot);
|
|
428
|
+
if (rendered && rendered !== lastSnapshot) {
|
|
429
|
+
writeLine(rendered);
|
|
430
|
+
lastSnapshot = rendered;
|
|
431
|
+
}
|
|
432
|
+
},
|
|
433
|
+
renderTimeline(entries) {
|
|
434
|
+
for (const [index, entry] of entries.entries()) {
|
|
435
|
+
const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
|
|
436
|
+
if (entry.type === "assistant_message" && typeof entry.text === "string") {
|
|
437
|
+
const text = entry.text;
|
|
438
|
+
const previousText = assistantTextById.get(id) ?? "";
|
|
439
|
+
if (!previousText && text.trim()) {
|
|
440
|
+
writeLine("[Pi assistant]");
|
|
441
|
+
}
|
|
442
|
+
if (text.startsWith(previousText)) {
|
|
443
|
+
const delta = text.slice(previousText.length);
|
|
444
|
+
if (delta)
|
|
445
|
+
output.write(delta);
|
|
446
|
+
} else if (text.trim() && text !== previousText) {
|
|
447
|
+
if (previousText)
|
|
448
|
+
writeLine(`
|
|
449
|
+
[Pi assistant]`);
|
|
450
|
+
output.write(text);
|
|
451
|
+
}
|
|
452
|
+
assistantTextById.set(id, text);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (seenTimeline.has(id))
|
|
456
|
+
continue;
|
|
457
|
+
seenTimeline.add(id);
|
|
458
|
+
if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
|
|
459
|
+
writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
if (entry.type === "timeline_warning") {
|
|
463
|
+
writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
|
|
464
|
+
continue;
|
|
465
|
+
}
|
|
466
|
+
if (entry.type === "action") {
|
|
467
|
+
const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
|
|
468
|
+
if (text)
|
|
469
|
+
writeLine(`[Rig action] ${text}`);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (entry.type === "user_message") {
|
|
473
|
+
const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
|
|
474
|
+
if (text)
|
|
475
|
+
writeLine(`[Operator] ${text}`);
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
|
|
479
|
+
if (fallback)
|
|
480
|
+
writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
|
|
481
|
+
}
|
|
482
|
+
},
|
|
483
|
+
renderLogs(entries) {
|
|
484
|
+
for (const [index, entry] of entries.entries()) {
|
|
485
|
+
const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
|
|
486
|
+
if (seenLogs.has(id))
|
|
487
|
+
continue;
|
|
488
|
+
seenLogs.add(id);
|
|
489
|
+
const title = String(entry.title ?? "");
|
|
490
|
+
if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
|
|
491
|
+
continue;
|
|
492
|
+
const detail = logDetail(entry);
|
|
493
|
+
if (!detail)
|
|
494
|
+
continue;
|
|
495
|
+
const protocolRecord = parseProviderProtocolLog(title, detail);
|
|
496
|
+
if (protocolRecord) {
|
|
497
|
+
const protocolLine = renderProviderProtocolLog(protocolRecord);
|
|
498
|
+
if (protocolLine)
|
|
499
|
+
writeLine(protocolLine);
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
writeLine(`[${title || "Rig log"}] ${detail}`);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function createOperatorSurface(options = {}) {
|
|
508
|
+
const input = options.input ?? process.stdin;
|
|
509
|
+
const output = options.output ?? process.stdout;
|
|
510
|
+
const errorOutput = options.errorOutput ?? process.stderr;
|
|
511
|
+
const renderer = createPiRunStreamRenderer(output);
|
|
512
|
+
const writeLine = (line) => output.write(`${line}
|
|
513
|
+
`);
|
|
514
|
+
return {
|
|
515
|
+
mode: "pi-compatible-text",
|
|
516
|
+
...renderer,
|
|
517
|
+
info: writeLine,
|
|
518
|
+
error: (message) => errorOutput.write(`${message}
|
|
519
|
+
`),
|
|
520
|
+
attachCommandInput(handler) {
|
|
521
|
+
if (options.interactive === false || !input.isTTY)
|
|
522
|
+
return null;
|
|
523
|
+
const rl = createInterface({ input, output: process.stdout, terminal: false });
|
|
524
|
+
rl.on("line", (line) => {
|
|
525
|
+
Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
526
|
+
});
|
|
527
|
+
return { close: () => rl.close() };
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
533
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
534
|
+
import { tmpdir } from "os";
|
|
535
|
+
import { join } from "path";
|
|
536
|
+
import {
|
|
537
|
+
createAgentSessionFromServices,
|
|
538
|
+
createAgentSessionServices,
|
|
539
|
+
main as runPiMain
|
|
540
|
+
} from "@earendil-works/pi-coding-agent";
|
|
541
|
+
|
|
542
|
+
// packages/cli/src/commands/_pi-remote-session.ts
|
|
543
|
+
import { AgentSession as PiAgentSession, expandPromptTemplate } from "@earendil-works/pi-coding-agent";
|
|
544
|
+
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
545
|
+
function defaultTransport() {
|
|
546
|
+
return {
|
|
547
|
+
getSession: getRunPiSessionViaServer,
|
|
548
|
+
getMessages: getRunPiMessagesViaServer,
|
|
549
|
+
getStatus: getRunPiStatusViaServer,
|
|
550
|
+
getCommands: getRunPiCommandsViaServer,
|
|
551
|
+
getCapabilities: getRunPiCapabilitiesViaServer,
|
|
552
|
+
sendPrompt: sendRunPiPromptViaServer,
|
|
553
|
+
sendShell: sendRunPiShellViaServer,
|
|
554
|
+
runCommand: runRunPiCommandViaServer,
|
|
555
|
+
abort: abortRunPiViaServer,
|
|
556
|
+
buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
function recordOf(value) {
|
|
560
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
561
|
+
}
|
|
562
|
+
function emptyRemoteStatus() {
|
|
563
|
+
return {
|
|
564
|
+
isStreaming: false,
|
|
565
|
+
isCompacting: false,
|
|
566
|
+
isBashRunning: false,
|
|
567
|
+
pendingMessageCount: 0,
|
|
568
|
+
steeringMessages: [],
|
|
569
|
+
followUpMessages: [],
|
|
570
|
+
model: null,
|
|
571
|
+
thinkingLevel: null,
|
|
572
|
+
sessionName: null,
|
|
573
|
+
cwd: null,
|
|
574
|
+
stats: null,
|
|
575
|
+
contextUsage: null
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
function resolveAttachReadyTimeoutMs() {
|
|
579
|
+
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
580
|
+
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
class RigRemoteSessionController {
|
|
584
|
+
context;
|
|
585
|
+
runId;
|
|
586
|
+
status = emptyRemoteStatus();
|
|
587
|
+
transport;
|
|
588
|
+
hooks = {};
|
|
589
|
+
session = null;
|
|
590
|
+
socket = null;
|
|
591
|
+
closed = false;
|
|
592
|
+
pendingShells = [];
|
|
593
|
+
pendingCompactions = [];
|
|
594
|
+
constructor(input) {
|
|
595
|
+
this.context = input.context;
|
|
596
|
+
this.runId = input.runId;
|
|
597
|
+
this.transport = input.transport ?? defaultTransport();
|
|
598
|
+
}
|
|
599
|
+
ingestEnvelope(envelopeValue) {
|
|
600
|
+
this.applyEnvelope(envelopeValue);
|
|
601
|
+
}
|
|
602
|
+
bindSession(session) {
|
|
603
|
+
this.session = session;
|
|
604
|
+
}
|
|
605
|
+
setUiHooks(hooks) {
|
|
606
|
+
this.hooks = hooks;
|
|
607
|
+
}
|
|
608
|
+
async connect() {
|
|
609
|
+
const ready = await this.waitForReady();
|
|
610
|
+
if (!ready || this.closed)
|
|
611
|
+
return;
|
|
612
|
+
let catchupDone = false;
|
|
613
|
+
const buffered = [];
|
|
614
|
+
const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
|
|
615
|
+
const socket = new WebSocket(wsUrl);
|
|
616
|
+
this.socket = socket;
|
|
617
|
+
socket.onopen = () => {
|
|
618
|
+
this.hooks.onConnectionChange?.(true);
|
|
619
|
+
this.hooks.onStatusText?.("worker session live");
|
|
620
|
+
};
|
|
621
|
+
socket.onmessage = (message) => {
|
|
622
|
+
try {
|
|
623
|
+
const payload = typeof message.data === "string" ? JSON.parse(message.data) : JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
624
|
+
if (!catchupDone)
|
|
625
|
+
buffered.push(payload);
|
|
626
|
+
else
|
|
627
|
+
this.applyEnvelope(payload);
|
|
628
|
+
} catch (error) {
|
|
629
|
+
this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
socket.onerror = () => socket.close();
|
|
633
|
+
socket.onclose = () => {
|
|
634
|
+
this.hooks.onConnectionChange?.(false);
|
|
635
|
+
if (!this.closed)
|
|
636
|
+
this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
|
|
637
|
+
};
|
|
638
|
+
try {
|
|
639
|
+
const [messagesPayload, statusPayload, commandsPayload, capabilitiesPayload] = await Promise.all([
|
|
640
|
+
this.transport.getMessages(this.context, this.runId),
|
|
641
|
+
this.transport.getStatus(this.context, this.runId),
|
|
642
|
+
this.transport.getCommands(this.context, this.runId),
|
|
643
|
+
this.transport.getCapabilities(this.context, this.runId).catch(() => ({ capabilities: null }))
|
|
644
|
+
]);
|
|
645
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
646
|
+
this.applyStatusPayload(statusPayload);
|
|
647
|
+
this.session?.replaceRemoteMessages(messages);
|
|
648
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
649
|
+
const capabilities = capabilitiesPayload.capabilities && typeof capabilitiesPayload.capabilities === "object" && !Array.isArray(capabilitiesPayload.capabilities) ? capabilitiesPayload.capabilities : null;
|
|
650
|
+
this.hooks.onCatchUp?.(messages, commands, capabilities);
|
|
651
|
+
catchupDone = true;
|
|
652
|
+
for (const payload of buffered.splice(0))
|
|
653
|
+
this.applyEnvelope(payload);
|
|
654
|
+
} catch (error) {
|
|
655
|
+
catchupDone = true;
|
|
656
|
+
this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
close() {
|
|
660
|
+
this.closed = true;
|
|
661
|
+
this.socket?.close();
|
|
662
|
+
for (const shell of this.pendingShells.splice(0))
|
|
663
|
+
shell.reject(new Error("Remote session closed."));
|
|
664
|
+
for (const compaction of this.pendingCompactions.splice(0))
|
|
665
|
+
compaction.reject(new Error("Remote session closed."));
|
|
666
|
+
}
|
|
667
|
+
async sendPrompt(text, streamingBehavior) {
|
|
668
|
+
await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
|
|
669
|
+
}
|
|
670
|
+
async sendCommand(text) {
|
|
671
|
+
const result = await this.transport.runCommand(this.context, this.runId, text);
|
|
672
|
+
return typeof result.message === "string" ? result.message : "worker command accepted";
|
|
673
|
+
}
|
|
674
|
+
async sendShell(text) {
|
|
675
|
+
await this.transport.sendShell(this.context, this.runId, text);
|
|
676
|
+
}
|
|
677
|
+
async abort() {
|
|
678
|
+
await this.transport.abort(this.context, this.runId);
|
|
679
|
+
}
|
|
680
|
+
registerPendingShell(shell) {
|
|
681
|
+
this.pendingShells.push(shell);
|
|
682
|
+
}
|
|
683
|
+
failPendingShell(shell, error) {
|
|
684
|
+
const index = this.pendingShells.indexOf(shell);
|
|
685
|
+
if (index !== -1)
|
|
686
|
+
this.pendingShells.splice(index, 1);
|
|
687
|
+
shell.reject(error);
|
|
688
|
+
}
|
|
689
|
+
registerPendingCompaction(pending) {
|
|
690
|
+
this.pendingCompactions.push(pending);
|
|
691
|
+
}
|
|
692
|
+
async waitForReady() {
|
|
693
|
+
const startedAt = Date.now();
|
|
694
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
695
|
+
let consecutiveFailures = 0;
|
|
696
|
+
while (!this.closed) {
|
|
697
|
+
let requestFailed = false;
|
|
698
|
+
const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
|
|
699
|
+
requestFailed = true;
|
|
700
|
+
return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
|
|
701
|
+
});
|
|
702
|
+
if (session.ready !== false)
|
|
703
|
+
return true;
|
|
704
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
705
|
+
const status = String(session.status ?? "starting");
|
|
706
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
707
|
+
this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
|
|
708
|
+
return false;
|
|
709
|
+
}
|
|
710
|
+
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`);
|
|
711
|
+
if (Date.now() >= deadline) {
|
|
712
|
+
this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
|
|
713
|
+
return false;
|
|
714
|
+
}
|
|
715
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
716
|
+
}
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
applyEnvelope(envelopeValue) {
|
|
720
|
+
const envelope = recordOf(envelopeValue);
|
|
721
|
+
if (!envelope)
|
|
722
|
+
return;
|
|
723
|
+
const type = String(envelope.type ?? "");
|
|
724
|
+
if (type === "status.update") {
|
|
725
|
+
this.applyStatusPayload(envelope);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (type === "activity.update") {
|
|
729
|
+
const activity = recordOf(envelope.activity);
|
|
730
|
+
this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (type === "extension_ui_request") {
|
|
734
|
+
const request = recordOf(envelope.request);
|
|
735
|
+
if (request)
|
|
736
|
+
this.hooks.onExtensionUiRequest?.(request);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
if (type === "pi.ui_event") {
|
|
740
|
+
this.applyShellUiEvent(envelope.event);
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
if (type === "pi.event") {
|
|
744
|
+
this.session?.handleRemoteSessionEvent(envelope.event);
|
|
745
|
+
this.settlePendingCompaction(envelope.event);
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
if (type === "error") {
|
|
749
|
+
this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
applyStatusPayload(payload) {
|
|
753
|
+
const status = recordOf(payload.status) ?? payload;
|
|
754
|
+
const next = this.status;
|
|
755
|
+
next.isStreaming = status.isStreaming === true;
|
|
756
|
+
next.isCompacting = status.isCompacting === true;
|
|
757
|
+
next.isBashRunning = status.isBashRunning === true;
|
|
758
|
+
next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
759
|
+
next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
|
|
760
|
+
next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
|
|
761
|
+
next.model = recordOf(status.model) ?? next.model;
|
|
762
|
+
next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
|
|
763
|
+
next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
|
|
764
|
+
next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
|
|
765
|
+
next.stats = recordOf(status.stats) ?? next.stats;
|
|
766
|
+
next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
|
|
767
|
+
}
|
|
768
|
+
applyShellUiEvent(value) {
|
|
769
|
+
const event = recordOf(value);
|
|
770
|
+
if (!event)
|
|
771
|
+
return;
|
|
772
|
+
const type = String(event.type ?? "");
|
|
773
|
+
const pending = this.pendingShells[0];
|
|
774
|
+
if (type === "shell.chunk" && pending) {
|
|
775
|
+
pending.sawChunk = true;
|
|
776
|
+
pending.onData(Buffer.from(String(event.chunk ?? "")));
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
if (type === "shell.end" && pending) {
|
|
780
|
+
const output = String(event.output ?? "");
|
|
781
|
+
if (output && !pending.sawChunk)
|
|
782
|
+
pending.onData(Buffer.from(output));
|
|
783
|
+
const index = this.pendingShells.indexOf(pending);
|
|
784
|
+
if (index !== -1)
|
|
785
|
+
this.pendingShells.splice(index, 1);
|
|
786
|
+
pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
settlePendingCompaction(eventValue) {
|
|
790
|
+
const event = recordOf(eventValue);
|
|
791
|
+
if (!event)
|
|
792
|
+
return;
|
|
793
|
+
const type = String(event.type ?? "");
|
|
794
|
+
if (type !== "compaction_end" || this.pendingCompactions.length === 0)
|
|
795
|
+
return;
|
|
796
|
+
const pending = this.pendingCompactions.shift();
|
|
797
|
+
const result = recordOf(event.result);
|
|
798
|
+
if (result)
|
|
799
|
+
pending.resolve(result);
|
|
800
|
+
else if (event.aborted === true)
|
|
801
|
+
pending.reject(new Error("Compaction aborted on the worker."));
|
|
802
|
+
else
|
|
803
|
+
pending.resolve({});
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
class RigRemoteAgentSession extends PiAgentSession {
|
|
808
|
+
remote;
|
|
809
|
+
constructor(config, remote) {
|
|
810
|
+
super(config);
|
|
811
|
+
this.remote = remote;
|
|
812
|
+
remote.bindSession(this);
|
|
813
|
+
}
|
|
814
|
+
handleRemoteSessionEvent(eventValue) {
|
|
815
|
+
const event = recordOf(eventValue);
|
|
816
|
+
if (!event)
|
|
817
|
+
return;
|
|
818
|
+
const type = String(event.type ?? "");
|
|
819
|
+
if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
|
|
820
|
+
this.agent.state.messages = [...this.agent.state.messages, event.message];
|
|
821
|
+
}
|
|
822
|
+
this._emit(eventValue);
|
|
823
|
+
}
|
|
824
|
+
replaceRemoteMessages(messages) {
|
|
825
|
+
this.agent.state.messages = messages;
|
|
826
|
+
}
|
|
827
|
+
async expandLocalInput(text) {
|
|
828
|
+
let current = text;
|
|
829
|
+
const runner = this.extensionRunner;
|
|
830
|
+
if (runner.hasHandlers("input")) {
|
|
831
|
+
const result = await runner.emitInput(current, undefined, "interactive");
|
|
832
|
+
if (result.action === "handled")
|
|
833
|
+
return null;
|
|
834
|
+
if (result.action === "transform")
|
|
835
|
+
current = result.text;
|
|
836
|
+
}
|
|
837
|
+
current = this._expandSkillCommand(current);
|
|
838
|
+
current = expandPromptTemplate(current, [...this.promptTemplates]);
|
|
839
|
+
return current;
|
|
840
|
+
}
|
|
841
|
+
async prompt(text, options) {
|
|
842
|
+
const trimmed = text.trim();
|
|
843
|
+
if (!trimmed)
|
|
844
|
+
return;
|
|
845
|
+
if (trimmed.startsWith("/")) {
|
|
846
|
+
if (await this._tryExecuteExtensionCommand(trimmed))
|
|
847
|
+
return;
|
|
848
|
+
const expanded2 = await this.expandLocalInput(trimmed);
|
|
849
|
+
if (expanded2 === null)
|
|
850
|
+
return;
|
|
851
|
+
if (expanded2 !== trimmed) {
|
|
852
|
+
const behavior2 = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
853
|
+
options?.preflightResult?.(true);
|
|
854
|
+
await this.remote.sendPrompt(expanded2, behavior2);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
await this.remote.sendCommand(trimmed);
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
if (trimmed.startsWith("!")) {
|
|
861
|
+
await this.remote.sendShell(trimmed);
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
const expanded = await this.expandLocalInput(trimmed);
|
|
865
|
+
if (expanded === null)
|
|
866
|
+
return;
|
|
867
|
+
const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
868
|
+
options?.preflightResult?.(true);
|
|
869
|
+
await this.remote.sendPrompt(expanded, behavior);
|
|
870
|
+
}
|
|
871
|
+
async steer(text) {
|
|
872
|
+
const trimmed = text.trim();
|
|
873
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
874
|
+
return;
|
|
875
|
+
const expanded = await this.expandLocalInput(trimmed);
|
|
876
|
+
if (expanded === null)
|
|
877
|
+
return;
|
|
878
|
+
await this.remote.sendPrompt(expanded, "steer");
|
|
879
|
+
}
|
|
880
|
+
async followUp(text) {
|
|
881
|
+
const trimmed = text.trim();
|
|
882
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
883
|
+
return;
|
|
884
|
+
const expanded = await this.expandLocalInput(trimmed);
|
|
885
|
+
if (expanded === null)
|
|
886
|
+
return;
|
|
887
|
+
await this.remote.sendPrompt(expanded, "followUp");
|
|
888
|
+
}
|
|
889
|
+
async abort() {
|
|
890
|
+
await this.remote.abort();
|
|
891
|
+
}
|
|
892
|
+
async compact(customInstructions) {
|
|
893
|
+
const pending = new Promise((resolve3, reject) => {
|
|
894
|
+
this.remote.registerPendingCompaction({ resolve: resolve3, reject });
|
|
895
|
+
});
|
|
896
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
897
|
+
return pending;
|
|
898
|
+
}
|
|
899
|
+
clearQueue() {
|
|
900
|
+
const cleared = {
|
|
901
|
+
steering: [...this.remote.status.steeringMessages],
|
|
902
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
903
|
+
};
|
|
904
|
+
this.remote.status.steeringMessages = [];
|
|
905
|
+
this.remote.status.followUpMessages = [];
|
|
906
|
+
this.remote.status.pendingMessageCount = 0;
|
|
907
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
908
|
+
return cleared;
|
|
909
|
+
}
|
|
910
|
+
get isStreaming() {
|
|
911
|
+
return this.remote.status.isStreaming;
|
|
912
|
+
}
|
|
913
|
+
get isCompacting() {
|
|
914
|
+
return this.remote.status.isCompacting;
|
|
915
|
+
}
|
|
916
|
+
get isBashRunning() {
|
|
917
|
+
return this.remote.status.isBashRunning;
|
|
918
|
+
}
|
|
919
|
+
get pendingMessageCount() {
|
|
920
|
+
return this.remote.status.pendingMessageCount;
|
|
921
|
+
}
|
|
922
|
+
getSteeringMessages() {
|
|
923
|
+
return this.remote.status.steeringMessages;
|
|
924
|
+
}
|
|
925
|
+
getFollowUpMessages() {
|
|
926
|
+
return this.remote.status.followUpMessages;
|
|
927
|
+
}
|
|
928
|
+
get model() {
|
|
929
|
+
return this.remote.status.model ?? super.model;
|
|
930
|
+
}
|
|
931
|
+
async setModel(model) {
|
|
932
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
933
|
+
this.remote.status.model = model;
|
|
934
|
+
}
|
|
935
|
+
get thinkingLevel() {
|
|
936
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
937
|
+
}
|
|
938
|
+
setThinkingLevel(level) {
|
|
939
|
+
this.remote.status.thinkingLevel = level;
|
|
940
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
941
|
+
}
|
|
942
|
+
get sessionName() {
|
|
943
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
944
|
+
}
|
|
945
|
+
setSessionName(name) {
|
|
946
|
+
this.remote.status.sessionName = name;
|
|
947
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
948
|
+
}
|
|
949
|
+
getSessionStats() {
|
|
950
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
951
|
+
}
|
|
952
|
+
getContextUsage() {
|
|
953
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
954
|
+
}
|
|
955
|
+
dispose() {
|
|
956
|
+
this.remote.close();
|
|
957
|
+
super.dispose();
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
961
|
+
return {
|
|
962
|
+
exec(command, _cwd, execOptions) {
|
|
963
|
+
return new Promise((resolve3, reject) => {
|
|
964
|
+
const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
|
|
965
|
+
const cleanup = () => {
|
|
966
|
+
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
967
|
+
if (timer)
|
|
968
|
+
clearTimeout(timer);
|
|
969
|
+
};
|
|
970
|
+
const onAbort = () => {
|
|
971
|
+
cleanup();
|
|
972
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
973
|
+
};
|
|
974
|
+
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
975
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
976
|
+
cleanup();
|
|
977
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
978
|
+
}, timeoutMs) : null;
|
|
979
|
+
const wrappedResolve = pending.resolve;
|
|
980
|
+
const wrappedReject = pending.reject;
|
|
981
|
+
pending.resolve = (result) => {
|
|
982
|
+
cleanup();
|
|
983
|
+
wrappedResolve(result);
|
|
984
|
+
};
|
|
985
|
+
pending.reject = (error) => {
|
|
986
|
+
cleanup();
|
|
987
|
+
wrappedReject(error);
|
|
988
|
+
};
|
|
989
|
+
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
990
|
+
controller.registerPendingShell(pending);
|
|
991
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
992
|
+
cleanup();
|
|
993
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
994
|
+
});
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
// packages/cli/src/commands/_spinner.ts
|
|
1001
|
+
var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1002
|
+
|
|
1003
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
1004
|
+
function recordOf2(value) {
|
|
1005
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1006
|
+
}
|
|
1007
|
+
function asText(value) {
|
|
1008
|
+
if (typeof value === "string")
|
|
1009
|
+
return value;
|
|
1010
|
+
if (value === null || value === undefined)
|
|
1011
|
+
return "";
|
|
1012
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1013
|
+
return String(value);
|
|
1014
|
+
try {
|
|
1015
|
+
return JSON.stringify(value);
|
|
1016
|
+
} catch {
|
|
1017
|
+
return String(value);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
function names(value, key = "name") {
|
|
1021
|
+
if (!Array.isArray(value))
|
|
1022
|
+
return [];
|
|
1023
|
+
return value.flatMap((entry) => {
|
|
1024
|
+
if (typeof entry === "string")
|
|
1025
|
+
return [entry];
|
|
1026
|
+
const record = recordOf2(entry);
|
|
1027
|
+
const name = record?.[key];
|
|
1028
|
+
return typeof name === "string" ? [name] : [];
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
function renderWorkerCapabilities(capabilities) {
|
|
1032
|
+
const lines = ["Worker session capabilities (in effect for this run)"];
|
|
1033
|
+
const tools = Array.isArray(capabilities.tools) ? capabilities.tools : [];
|
|
1034
|
+
const activeTools = tools.flatMap((tool) => {
|
|
1035
|
+
const record = recordOf2(tool);
|
|
1036
|
+
return record && record.active === true && typeof record.name === "string" ? [record.name] : [];
|
|
1037
|
+
});
|
|
1038
|
+
const inactiveCount = tools.length - activeTools.length;
|
|
1039
|
+
lines.push(` tools ${activeTools.join(", ") || "(none)"}${inactiveCount > 0 ? ` (+${inactiveCount} inactive)` : ""}`);
|
|
1040
|
+
const extensions = Array.isArray(capabilities.extensions) ? capabilities.extensions : [];
|
|
1041
|
+
const extensionLabels = extensions.flatMap((entry) => {
|
|
1042
|
+
const record = recordOf2(entry);
|
|
1043
|
+
if (!record)
|
|
1044
|
+
return [];
|
|
1045
|
+
const path = typeof record.path === "string" ? record.path : "";
|
|
1046
|
+
const short = path.split("/").filter(Boolean).slice(-2).join("/") || path || "extension";
|
|
1047
|
+
return [short];
|
|
1048
|
+
});
|
|
1049
|
+
lines.push(` extensions ${extensionLabels.join(", ") || "(none)"}`);
|
|
1050
|
+
const hookEvents = names(capabilities.hookEvents);
|
|
1051
|
+
const hookList = Array.isArray(capabilities.hookEvents) ? capabilities.hookEvents.map(asText).filter(Boolean) : hookEvents;
|
|
1052
|
+
lines.push(` hooks ${hookList.join(", ") || "(none)"}`);
|
|
1053
|
+
lines.push(` skills ${names(capabilities.skills).join(", ") || "(none)"}`);
|
|
1054
|
+
lines.push(` prompts ${names(capabilities.prompts).join(", ") || "(none)"}`);
|
|
1055
|
+
const model = typeof capabilities.model === "string" ? capabilities.model : "(unknown)";
|
|
1056
|
+
const thinking = typeof capabilities.thinkingLevel === "string" ? capabilities.thinkingLevel : "";
|
|
1057
|
+
const cwd = typeof capabilities.cwd === "string" ? capabilities.cwd : "";
|
|
1058
|
+
lines.push(` model ${model}${thinking ? ` \xB7 ${thinking}` : ""}`);
|
|
1059
|
+
if (cwd)
|
|
1060
|
+
lines.push(` cwd ${cwd}`);
|
|
1061
|
+
lines.push(" (worker commands are in your palette as [worker \u2026] \xB7 /worker shows this again)");
|
|
1062
|
+
return lines;
|
|
1063
|
+
}
|
|
1064
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
1065
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
1066
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
1067
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
1068
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
1069
|
+
const choices = rawOptions.map((option) => {
|
|
1070
|
+
const record = recordOf2(option);
|
|
1071
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
1072
|
+
}).filter(Boolean);
|
|
1073
|
+
try {
|
|
1074
|
+
if (method === "confirm") {
|
|
1075
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
1076
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
if (choices.length > 0) {
|
|
1080
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
1081
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
1085
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "worker", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
1091
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
1092
|
+
for (const command of commands) {
|
|
1093
|
+
const record = recordOf2(command);
|
|
1094
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
1095
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
1096
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
1097
|
+
continue;
|
|
1098
|
+
registered.add(name);
|
|
1099
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
1100
|
+
try {
|
|
1101
|
+
pi.registerCommand(name, {
|
|
1102
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
1103
|
+
handler: async (args) => {
|
|
1104
|
+
try {
|
|
1105
|
+
const message = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
1106
|
+
ctx.ui.notify(message, "info");
|
|
1107
|
+
} catch (error) {
|
|
1108
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
});
|
|
1112
|
+
} catch {}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
function createRigWorkerPiBridgeExtension(options) {
|
|
1116
|
+
return (pi) => {
|
|
1117
|
+
const registeredDaemonCommands = new Set;
|
|
1118
|
+
let capabilityLines = null;
|
|
1119
|
+
let statusText = "connecting to worker session";
|
|
1120
|
+
let busy = true;
|
|
1121
|
+
let connected = false;
|
|
1122
|
+
let frame = 0;
|
|
1123
|
+
let spinnerTimer = null;
|
|
1124
|
+
const renderStatus = (ctx) => {
|
|
1125
|
+
const prefix = busy ? `${SPINNER_FRAMES[frame]} ` : connected ? "\u25CF " : "\u25CB ";
|
|
1126
|
+
ctx.ui.setStatus("rig-worker-pi", `${prefix}${statusText}`);
|
|
1127
|
+
};
|
|
1128
|
+
const setStatus = (ctx, text, isBusy) => {
|
|
1129
|
+
statusText = text;
|
|
1130
|
+
busy = isBusy;
|
|
1131
|
+
renderStatus(ctx);
|
|
1132
|
+
};
|
|
1133
|
+
pi.registerCommand("detach", {
|
|
1134
|
+
description: "Detach from this run; the worker keeps going",
|
|
1135
|
+
handler: async (_args, ctx) => {
|
|
1136
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
1137
|
+
ctx.shutdown();
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
pi.registerCommand("stop", {
|
|
1141
|
+
description: "Stop the worker Pi run and detach",
|
|
1142
|
+
handler: async (_args, ctx) => {
|
|
1143
|
+
await options.controller.abort();
|
|
1144
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
1145
|
+
ctx.shutdown();
|
|
1146
|
+
}
|
|
1147
|
+
});
|
|
1148
|
+
pi.registerCommand("worker", {
|
|
1149
|
+
description: "Show the worker session's real capabilities (tools, extensions, hooks, skills)",
|
|
1150
|
+
handler: async (_args, ctx) => {
|
|
1151
|
+
if (capabilityLines)
|
|
1152
|
+
ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
|
|
1153
|
+
else
|
|
1154
|
+
ctx.ui.notify("Worker capabilities are not available yet (still connecting).", "info");
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
pi.on("user_bash", (event) => ({
|
|
1158
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
1159
|
+
}));
|
|
1160
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1161
|
+
ctx.ui.setTitle("Rig \xB7 enriched bundled Pi");
|
|
1162
|
+
setStatus(ctx, "waiting for worker Pi daemon", true);
|
|
1163
|
+
spinnerTimer = setInterval(() => {
|
|
1164
|
+
frame = (frame + 1) % SPINNER_FRAMES.length;
|
|
1165
|
+
if (busy)
|
|
1166
|
+
renderStatus(ctx);
|
|
1167
|
+
}, 150);
|
|
1168
|
+
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");
|
|
1169
|
+
if (options.initialMessageSent)
|
|
1170
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
1171
|
+
const nativeUi = ctx.ui;
|
|
1172
|
+
options.controller.setUiHooks({
|
|
1173
|
+
onStatusText: (text) => setStatus(ctx, text, !connected),
|
|
1174
|
+
onActivity: (label, detail) => {
|
|
1175
|
+
const active = label !== "idle" && !/complete|ready/i.test(label);
|
|
1176
|
+
setStatus(ctx, [label, detail].filter(Boolean).join(" \u2014 "), active);
|
|
1177
|
+
if (/agent running|tool:/.test(label))
|
|
1178
|
+
ctx.ui.setWidget("rig-worker-capabilities", undefined);
|
|
1179
|
+
},
|
|
1180
|
+
onConnectionChange: (nextConnected) => {
|
|
1181
|
+
connected = nextConnected;
|
|
1182
|
+
setStatus(ctx, nextConnected ? "worker session live" : "worker session disconnected", false);
|
|
1183
|
+
},
|
|
1184
|
+
onError: (message) => ctx.ui.notify(message, "error"),
|
|
1185
|
+
onExtensionUiRequest: (request) => {
|
|
1186
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
1187
|
+
},
|
|
1188
|
+
onCatchUp: (messages, commands, capabilities) => {
|
|
1189
|
+
if (nativeUi.appendSessionMessages)
|
|
1190
|
+
nativeUi.appendSessionMessages(messages);
|
|
1191
|
+
const cwd = options.controller.status.cwd;
|
|
1192
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
1193
|
+
nativeUi.setDisplayCwd(cwd);
|
|
1194
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
1195
|
+
if (capabilities) {
|
|
1196
|
+
capabilityLines = renderWorkerCapabilities(capabilities);
|
|
1197
|
+
ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
});
|
|
1201
|
+
options.controller.connect().catch((error) => {
|
|
1202
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1203
|
+
});
|
|
1204
|
+
});
|
|
1205
|
+
pi.on("session_shutdown", () => {
|
|
1206
|
+
if (spinnerTimer)
|
|
1207
|
+
clearInterval(spinnerTimer);
|
|
1208
|
+
options.controller.close();
|
|
1209
|
+
});
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
1214
|
+
function setTemporaryEnv(updates) {
|
|
1215
|
+
const previous = new Map;
|
|
1216
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
1217
|
+
previous.set(key, process.env[key]);
|
|
1218
|
+
process.env[key] = value;
|
|
1219
|
+
}
|
|
1220
|
+
return () => {
|
|
1221
|
+
for (const [key, value] of previous) {
|
|
1222
|
+
if (value === undefined)
|
|
1223
|
+
delete process.env[key];
|
|
1224
|
+
else
|
|
1225
|
+
process.env[key] = value;
|
|
1226
|
+
}
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
async function attachRunBundledPiFrontend(context, input) {
|
|
1230
|
+
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
1231
|
+
const restoreEnv = setTemporaryEnv({
|
|
1232
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
1233
|
+
PI_SKIP_VERSION_CHECK: "1",
|
|
1234
|
+
PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust"
|
|
1235
|
+
});
|
|
1236
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
1237
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
1238
|
+
const services = await createAgentSessionServices({
|
|
1239
|
+
cwd,
|
|
1240
|
+
agentDir,
|
|
1241
|
+
resourceLoaderOptions: {
|
|
1242
|
+
extensionFactories: [
|
|
1243
|
+
createRigWorkerPiBridgeExtension({
|
|
1244
|
+
context,
|
|
1245
|
+
controller,
|
|
1246
|
+
runId: input.runId,
|
|
1247
|
+
initialMessageSent: input.steered === true
|
|
1248
|
+
})
|
|
1249
|
+
],
|
|
1250
|
+
noExtensions: true,
|
|
1251
|
+
noSkills: true,
|
|
1252
|
+
noPromptTemplates: true,
|
|
1253
|
+
noContextFiles: true
|
|
1254
|
+
}
|
|
1255
|
+
});
|
|
1256
|
+
const created = await createAgentSessionFromServices({
|
|
1257
|
+
services,
|
|
1258
|
+
sessionManager,
|
|
1259
|
+
sessionStartEvent,
|
|
1260
|
+
noTools: "all",
|
|
1261
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
1262
|
+
});
|
|
1263
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
1264
|
+
};
|
|
1265
|
+
let detached = false;
|
|
1266
|
+
try {
|
|
1267
|
+
await runPiMain([], {
|
|
1268
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
1269
|
+
});
|
|
1270
|
+
detached = true;
|
|
1271
|
+
} finally {
|
|
1272
|
+
restoreEnv();
|
|
1273
|
+
controller.close();
|
|
1274
|
+
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
1275
|
+
}
|
|
1276
|
+
let run = { runId: input.runId, status: "unknown" };
|
|
1277
|
+
try {
|
|
1278
|
+
run = await getRunDetailsViaServer(context, input.runId);
|
|
1279
|
+
} catch {}
|
|
1280
|
+
return {
|
|
1281
|
+
run,
|
|
1282
|
+
logs: [],
|
|
1283
|
+
timeline: [],
|
|
1284
|
+
timelineCursor: null,
|
|
1285
|
+
steered: input.steered === true,
|
|
1286
|
+
detached,
|
|
1287
|
+
rendered: "enriched bundled Pi frontend with remote worker session runtime"
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// packages/cli/src/commands/_operator-view.ts
|
|
1292
|
+
var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
266
1293
|
function runStatusFromPayload(payload) {
|
|
267
1294
|
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
268
1295
|
return String(run.status ?? "unknown").toLowerCase();
|
|
@@ -284,57 +1311,76 @@ async function applyOperatorCommand(context, input, deps = {}) {
|
|
|
284
1311
|
await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
|
|
285
1312
|
return { action: "continue", message: "Steering message queued." };
|
|
286
1313
|
}
|
|
287
|
-
async function readOperatorSnapshot(context, runId) {
|
|
1314
|
+
async function readOperatorSnapshot(context, runId, options = {}) {
|
|
288
1315
|
const run = await getRunDetailsViaServer(context, runId);
|
|
289
1316
|
const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
|
|
290
|
-
const
|
|
291
|
-
|
|
1317
|
+
const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
|
|
1318
|
+
entries: [{
|
|
1319
|
+
id: `timeline-unavailable:${runId}`,
|
|
1320
|
+
type: "timeline_warning",
|
|
1321
|
+
detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
|
|
1322
|
+
createdAt: new Date().toISOString()
|
|
1323
|
+
}],
|
|
1324
|
+
nextCursor: options.timelineCursor ?? null
|
|
1325
|
+
}));
|
|
1326
|
+
const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
|
|
1327
|
+
const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1328
|
+
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
1329
|
+
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
292
1330
|
}
|
|
293
1331
|
async function attachRunOperatorView(context, input) {
|
|
294
1332
|
let steered = false;
|
|
295
1333
|
if (input.message?.trim()) {
|
|
296
|
-
await steerRunViaServer(context, input.runId, input.message.trim());
|
|
1334
|
+
await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
|
|
297
1335
|
steered = true;
|
|
298
1336
|
}
|
|
1337
|
+
if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
1338
|
+
return attachRunBundledPiFrontend(context, {
|
|
1339
|
+
runId: input.runId,
|
|
1340
|
+
steered
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
299
1344
|
let snapshot = await readOperatorSnapshot(context, input.runId);
|
|
300
1345
|
if (context.outputMode === "text") {
|
|
301
|
-
|
|
1346
|
+
surface.renderSnapshot(snapshot);
|
|
1347
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1348
|
+
surface.renderLogs(snapshot.logs);
|
|
302
1349
|
if (steered)
|
|
303
|
-
|
|
1350
|
+
surface.info("Message submitted to worker Pi.");
|
|
304
1351
|
}
|
|
305
1352
|
let detached = false;
|
|
306
|
-
let
|
|
1353
|
+
let commandInput = null;
|
|
307
1354
|
if (input.follow && !input.once && context.outputMode === "text") {
|
|
308
1355
|
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)}`));
|
|
1356
|
+
surface.info("Controls: /user <message>, /stop, /detach");
|
|
1357
|
+
commandInput = surface.attachCommandInput(async (line) => {
|
|
1358
|
+
const result = await applyOperatorCommand(context, { runId: input.runId, line });
|
|
1359
|
+
if (result.message)
|
|
1360
|
+
surface.info(result.message);
|
|
1361
|
+
if (result.action === "detach" || result.action === "stopped") {
|
|
1362
|
+
detached = true;
|
|
1363
|
+
commandInput?.close();
|
|
1364
|
+
}
|
|
320
1365
|
});
|
|
321
1366
|
}
|
|
322
|
-
let lastRendered = snapshot.rendered;
|
|
323
1367
|
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
324
|
-
|
|
1368
|
+
let timelineCursor = snapshot.timelineCursor;
|
|
1369
|
+
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
325
1370
|
await Bun.sleep(pollMs);
|
|
326
|
-
snapshot = await readOperatorSnapshot(context, input.runId);
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
1371
|
+
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
1372
|
+
timelineCursor = snapshot.timelineCursor;
|
|
1373
|
+
surface.renderSnapshot(snapshot);
|
|
1374
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1375
|
+
surface.renderLogs(snapshot.logs);
|
|
331
1376
|
}
|
|
332
|
-
|
|
1377
|
+
commandInput?.close();
|
|
333
1378
|
}
|
|
334
1379
|
return { ...snapshot, steered, detached };
|
|
335
1380
|
}
|
|
336
1381
|
export {
|
|
337
1382
|
renderOperatorSnapshot,
|
|
1383
|
+
createPiRunStreamRenderer,
|
|
338
1384
|
attachRunOperatorView,
|
|
339
1385
|
applyOperatorCommand
|
|
340
1386
|
};
|