@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
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// packages/cli/src/commands/_server-client.ts
|
|
3
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
4
|
+
import { resolve as resolve2 } from "path";
|
|
5
|
+
|
|
6
|
+
// packages/cli/src/runner.ts
|
|
7
|
+
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
8
|
+
import { CliError } from "@rig/runtime/control-plane/errors";
|
|
9
|
+
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
10
|
+
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
11
|
+
import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
|
|
12
|
+
|
|
13
|
+
// packages/cli/src/commands/_server-client.ts
|
|
14
|
+
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
15
|
+
|
|
16
|
+
// packages/cli/src/commands/_connection-state.ts
|
|
17
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
18
|
+
import { homedir } from "os";
|
|
19
|
+
import { dirname, resolve } from "path";
|
|
20
|
+
function resolveGlobalConnectionsPath(env = process.env) {
|
|
21
|
+
const explicit = env.RIG_CONNECTIONS_FILE?.trim();
|
|
22
|
+
if (explicit)
|
|
23
|
+
return resolve(explicit);
|
|
24
|
+
const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
|
|
25
|
+
if (stateDir)
|
|
26
|
+
return resolve(stateDir, "connections.json");
|
|
27
|
+
return resolve(homedir(), ".rig", "connections.json");
|
|
28
|
+
}
|
|
29
|
+
function resolveRepoConnectionPath(projectRoot) {
|
|
30
|
+
return resolve(projectRoot, ".rig", "state", "connection.json");
|
|
31
|
+
}
|
|
32
|
+
function readJsonFile(path) {
|
|
33
|
+
if (!existsSync(path))
|
|
34
|
+
return null;
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
37
|
+
} catch (error) {
|
|
38
|
+
throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function normalizeConnection(value) {
|
|
42
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
43
|
+
return null;
|
|
44
|
+
const record = value;
|
|
45
|
+
if (record.kind === "local")
|
|
46
|
+
return { kind: "local", mode: "auto" };
|
|
47
|
+
if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
|
|
48
|
+
const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
|
|
49
|
+
return { kind: "remote", baseUrl };
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
function readGlobalConnections(options = {}) {
|
|
54
|
+
const path = resolveGlobalConnectionsPath(options.env ?? process.env);
|
|
55
|
+
const payload = readJsonFile(path);
|
|
56
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
57
|
+
return { connections: {} };
|
|
58
|
+
}
|
|
59
|
+
const rawConnections = payload.connections;
|
|
60
|
+
const connections = {};
|
|
61
|
+
if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
|
|
62
|
+
for (const [alias, raw] of Object.entries(rawConnections)) {
|
|
63
|
+
const connection = normalizeConnection(raw);
|
|
64
|
+
if (connection)
|
|
65
|
+
connections[alias] = connection;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { connections };
|
|
69
|
+
}
|
|
70
|
+
function readRepoConnection(projectRoot) {
|
|
71
|
+
const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
|
|
72
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
73
|
+
return null;
|
|
74
|
+
const record = payload;
|
|
75
|
+
const selected = typeof record.selected === "string" ? record.selected.trim() : "";
|
|
76
|
+
if (!selected)
|
|
77
|
+
return null;
|
|
78
|
+
return {
|
|
79
|
+
selected,
|
|
80
|
+
project: typeof record.project === "string" ? record.project : undefined,
|
|
81
|
+
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
85
|
+
const repo = readRepoConnection(projectRoot);
|
|
86
|
+
if (!repo)
|
|
87
|
+
return null;
|
|
88
|
+
if (repo.selected === "local")
|
|
89
|
+
return { alias: "local", connection: { kind: "local", mode: "auto" } };
|
|
90
|
+
const global = readGlobalConnections(options);
|
|
91
|
+
const connection = global.connections[repo.selected];
|
|
92
|
+
if (!connection) {
|
|
93
|
+
throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
94
|
+
}
|
|
95
|
+
return { alias: repo.selected, connection };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// packages/cli/src/commands/_server-client.ts
|
|
99
|
+
var scopedGitHubBearerTokens = new Map;
|
|
100
|
+
function cleanToken(value) {
|
|
101
|
+
const trimmed = value?.trim();
|
|
102
|
+
return trimmed ? trimmed : null;
|
|
103
|
+
}
|
|
104
|
+
function readPrivateRemoteSessionToken(projectRoot) {
|
|
105
|
+
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
106
|
+
if (!existsSync2(path))
|
|
107
|
+
return null;
|
|
108
|
+
try {
|
|
109
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
110
|
+
return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
116
|
+
const scopedKey = resolve2(projectRoot);
|
|
117
|
+
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
118
|
+
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
119
|
+
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
120
|
+
if (privateSession)
|
|
121
|
+
return privateSession;
|
|
122
|
+
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
123
|
+
}
|
|
124
|
+
async function ensureServerForCli(projectRoot) {
|
|
125
|
+
try {
|
|
126
|
+
const selected = resolveSelectedConnection(projectRoot);
|
|
127
|
+
if (selected?.connection.kind === "remote") {
|
|
128
|
+
return {
|
|
129
|
+
baseUrl: selected.connection.baseUrl,
|
|
130
|
+
authToken: readGitHubBearerTokenForRemote(projectRoot),
|
|
131
|
+
connectionKind: "remote"
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
135
|
+
return {
|
|
136
|
+
baseUrl: connection.baseUrl,
|
|
137
|
+
authToken: connection.authToken,
|
|
138
|
+
connectionKind: "local"
|
|
139
|
+
};
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (error instanceof Error) {
|
|
142
|
+
throw new CliError2(error.message, 1);
|
|
143
|
+
}
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function mergeHeaders(headers, authToken) {
|
|
148
|
+
const merged = new Headers(headers);
|
|
149
|
+
if (authToken) {
|
|
150
|
+
merged.set("authorization", `Bearer ${authToken}`);
|
|
151
|
+
}
|
|
152
|
+
return merged;
|
|
153
|
+
}
|
|
154
|
+
function diagnosticMessage(payload) {
|
|
155
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
156
|
+
return null;
|
|
157
|
+
const record = payload;
|
|
158
|
+
const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
|
|
159
|
+
const messages = diagnostics.flatMap((entry) => {
|
|
160
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
161
|
+
return [];
|
|
162
|
+
const diagnostic = entry;
|
|
163
|
+
const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
|
|
164
|
+
const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
|
|
165
|
+
return message ? [`${kind}: ${message}`] : [];
|
|
166
|
+
});
|
|
167
|
+
return messages.length > 0 ? messages.join("; ") : null;
|
|
168
|
+
}
|
|
169
|
+
async function requestServerJson(context, pathname, init = {}) {
|
|
170
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
171
|
+
const response = await fetch(`${server.baseUrl}${pathname}`, {
|
|
172
|
+
...init,
|
|
173
|
+
headers: mergeHeaders(init.headers, server.authToken)
|
|
174
|
+
});
|
|
175
|
+
const text = await response.text();
|
|
176
|
+
const payload = text.trim().length > 0 ? (() => {
|
|
177
|
+
try {
|
|
178
|
+
return JSON.parse(text);
|
|
179
|
+
} catch {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
})() : null;
|
|
183
|
+
if (!response.ok) {
|
|
184
|
+
const diagnostics = diagnosticMessage(payload);
|
|
185
|
+
const detail = diagnostics ?? (text || response.statusText);
|
|
186
|
+
throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
|
|
187
|
+
}
|
|
188
|
+
return payload;
|
|
189
|
+
}
|
|
190
|
+
async function getRunPiSessionViaServer(context, runId) {
|
|
191
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
192
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
193
|
+
}
|
|
194
|
+
async function getRunPiMessagesViaServer(context, runId) {
|
|
195
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
196
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
197
|
+
}
|
|
198
|
+
async function getRunPiStatusViaServer(context, runId) {
|
|
199
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
200
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
201
|
+
}
|
|
202
|
+
async function getRunPiCommandsViaServer(context, runId) {
|
|
203
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
204
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
205
|
+
}
|
|
206
|
+
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
207
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: { "content-type": "application/json" },
|
|
210
|
+
body: JSON.stringify({ text, streamingBehavior })
|
|
211
|
+
});
|
|
212
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
213
|
+
}
|
|
214
|
+
async function sendRunPiShellViaServer(context, runId, text) {
|
|
215
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
216
|
+
method: "POST",
|
|
217
|
+
headers: { "content-type": "application/json" },
|
|
218
|
+
body: JSON.stringify({ text })
|
|
219
|
+
});
|
|
220
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
221
|
+
}
|
|
222
|
+
async function runRunPiCommandViaServer(context, runId, text) {
|
|
223
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
224
|
+
method: "POST",
|
|
225
|
+
headers: { "content-type": "application/json" },
|
|
226
|
+
body: JSON.stringify({ text })
|
|
227
|
+
});
|
|
228
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
229
|
+
}
|
|
230
|
+
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
231
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
232
|
+
method: "POST",
|
|
233
|
+
headers: { "content-type": "application/json" },
|
|
234
|
+
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
235
|
+
});
|
|
236
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
237
|
+
}
|
|
238
|
+
async function abortRunPiViaServer(context, runId) {
|
|
239
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
240
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
241
|
+
}
|
|
242
|
+
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
243
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
244
|
+
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
245
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
246
|
+
if (server.authToken)
|
|
247
|
+
url.searchParams.set("token", server.authToken);
|
|
248
|
+
return url.toString();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
252
|
+
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
253
|
+
var MAX_TRANSCRIPT_LINES = 120;
|
|
254
|
+
function recordOf(value) {
|
|
255
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
256
|
+
}
|
|
257
|
+
function asText(value) {
|
|
258
|
+
if (typeof value === "string")
|
|
259
|
+
return value;
|
|
260
|
+
if (value === null || value === undefined)
|
|
261
|
+
return "";
|
|
262
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
263
|
+
return String(value);
|
|
264
|
+
try {
|
|
265
|
+
return JSON.stringify(value);
|
|
266
|
+
} catch {
|
|
267
|
+
return String(value);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
function textFromContent(content) {
|
|
271
|
+
if (typeof content === "string")
|
|
272
|
+
return content;
|
|
273
|
+
if (!Array.isArray(content))
|
|
274
|
+
return asText(content);
|
|
275
|
+
return content.flatMap((part) => {
|
|
276
|
+
const item = recordOf(part);
|
|
277
|
+
if (!item)
|
|
278
|
+
return [];
|
|
279
|
+
if (typeof item.text === "string")
|
|
280
|
+
return [item.text];
|
|
281
|
+
if (typeof item.content === "string")
|
|
282
|
+
return [item.content];
|
|
283
|
+
if (item.type === "toolCall")
|
|
284
|
+
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
285
|
+
if (item.type === "toolResult")
|
|
286
|
+
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
287
|
+
return [];
|
|
288
|
+
}).join(`
|
|
289
|
+
`);
|
|
290
|
+
}
|
|
291
|
+
function appendTranscript(state, label, text) {
|
|
292
|
+
const trimmed = text.trimEnd();
|
|
293
|
+
if (!trimmed)
|
|
294
|
+
return;
|
|
295
|
+
const lines = trimmed.split(/\r?\n/);
|
|
296
|
+
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
297
|
+
for (const line of lines.slice(1))
|
|
298
|
+
state.transcript.push(` ${line}`);
|
|
299
|
+
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
300
|
+
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function nativePiUi(ctx) {
|
|
304
|
+
const ui = ctx.ui;
|
|
305
|
+
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
306
|
+
}
|
|
307
|
+
function syncNativeDisplayCwd(ctx, state) {
|
|
308
|
+
const ui = nativePiUi(ctx);
|
|
309
|
+
if (ui?.setDisplayCwd && state.cwd)
|
|
310
|
+
ui.setDisplayCwd(state.cwd);
|
|
311
|
+
}
|
|
312
|
+
function parseExtensionUiRequest(value) {
|
|
313
|
+
const request = recordOf(value) ?? {};
|
|
314
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
315
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
316
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
317
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
318
|
+
const options = rawOptions.map((option) => {
|
|
319
|
+
const record = recordOf(option);
|
|
320
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
321
|
+
}).filter(Boolean);
|
|
322
|
+
return { requestId, method, prompt, options };
|
|
323
|
+
}
|
|
324
|
+
function renderBridgeWidget(state) {
|
|
325
|
+
const statusParts = [
|
|
326
|
+
state.wsConnected ? "live" : "connecting",
|
|
327
|
+
state.status,
|
|
328
|
+
state.model,
|
|
329
|
+
state.cwd
|
|
330
|
+
].filter(Boolean);
|
|
331
|
+
const lines = [`Rig worker session \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
332
|
+
if (state.activity)
|
|
333
|
+
lines.push(state.activity);
|
|
334
|
+
if (state.commands.length > 0) {
|
|
335
|
+
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
336
|
+
}
|
|
337
|
+
lines.push("");
|
|
338
|
+
if (state.transcript.length > 0) {
|
|
339
|
+
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
340
|
+
} else {
|
|
341
|
+
lines.push("Waiting for the worker session transcript\u2026 (/detach exits and leaves the worker running)");
|
|
342
|
+
}
|
|
343
|
+
if (state.pendingUi) {
|
|
344
|
+
lines.push("");
|
|
345
|
+
lines.push(`Worker needs input \xB7 ${state.pendingUi.method}`);
|
|
346
|
+
lines.push(state.pendingUi.prompt);
|
|
347
|
+
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
348
|
+
lines.push("Reply in the editor below. /cancel dismisses this request.");
|
|
349
|
+
}
|
|
350
|
+
return lines;
|
|
351
|
+
}
|
|
352
|
+
function reportBridgeError(ctx, state, message) {
|
|
353
|
+
appendTranscript(state, "Error", message);
|
|
354
|
+
state.status = message;
|
|
355
|
+
try {
|
|
356
|
+
ctx.ui.notify(message, "error");
|
|
357
|
+
} catch {}
|
|
358
|
+
updatePiUi(ctx, state);
|
|
359
|
+
}
|
|
360
|
+
function updatePiUi(ctx, state) {
|
|
361
|
+
ctx.ui.setTitle("Rig \xB7 worker session");
|
|
362
|
+
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker session live" : state.status);
|
|
363
|
+
syncNativeDisplayCwd(ctx, state);
|
|
364
|
+
if (state.nativeStream && nativePiUi(ctx)) {
|
|
365
|
+
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
ctx.ui.setWorkingVisible(false);
|
|
369
|
+
ctx.ui.setWidget("rig-worker-pi-transcript", renderBridgeWidget(state), { placement: "aboveEditor" });
|
|
370
|
+
}
|
|
371
|
+
function applyStatus(state, payload) {
|
|
372
|
+
const status = recordOf(payload.status) ?? payload;
|
|
373
|
+
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
374
|
+
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
375
|
+
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
376
|
+
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
377
|
+
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
378
|
+
}
|
|
379
|
+
function applyMessage(state, message) {
|
|
380
|
+
const record = recordOf(message);
|
|
381
|
+
if (!record)
|
|
382
|
+
return;
|
|
383
|
+
const role = String(record.role ?? "system");
|
|
384
|
+
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
385
|
+
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
386
|
+
}
|
|
387
|
+
function applyPiEvent(ctx, state, eventValue) {
|
|
388
|
+
const event = recordOf(eventValue);
|
|
389
|
+
if (!event)
|
|
390
|
+
return;
|
|
391
|
+
const type = String(event.type ?? "event");
|
|
392
|
+
if (type === "agent_start") {
|
|
393
|
+
state.streaming = true;
|
|
394
|
+
state.status = "streaming";
|
|
395
|
+
} else if (type === "agent_end") {
|
|
396
|
+
state.streaming = false;
|
|
397
|
+
state.status = "idle";
|
|
398
|
+
} else if (type === "queue_update") {
|
|
399
|
+
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
400
|
+
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
401
|
+
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
402
|
+
}
|
|
403
|
+
const native = nativePiUi(ctx);
|
|
404
|
+
if (state.nativeStream && native?.emitSessionEvent) {
|
|
405
|
+
native.emitSessionEvent(eventValue);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (type === "agent_end") {
|
|
409
|
+
appendTranscript(state, "System", "Agent turn complete.");
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
413
|
+
applyMessage(state, event.message);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (type === "message_update") {
|
|
417
|
+
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
418
|
+
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
419
|
+
if (delta)
|
|
420
|
+
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
if (type === "tool_execution_start") {
|
|
424
|
+
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
if (type === "tool_execution_update") {
|
|
428
|
+
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
if (type === "tool_execution_end") {
|
|
432
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function firstPendingShell(state) {
|
|
436
|
+
return state.pendingShells[0];
|
|
437
|
+
}
|
|
438
|
+
function finishPendingShell(state, shell, result) {
|
|
439
|
+
const index = state.pendingShells.indexOf(shell);
|
|
440
|
+
if (index !== -1)
|
|
441
|
+
state.pendingShells.splice(index, 1);
|
|
442
|
+
shell.resolve(result);
|
|
443
|
+
}
|
|
444
|
+
function failPendingShell(state, shell, error) {
|
|
445
|
+
const index = state.pendingShells.indexOf(shell);
|
|
446
|
+
if (index !== -1)
|
|
447
|
+
state.pendingShells.splice(index, 1);
|
|
448
|
+
shell.reject(error);
|
|
449
|
+
}
|
|
450
|
+
function applyUiEvent(state, value) {
|
|
451
|
+
const event = recordOf(value);
|
|
452
|
+
if (!event)
|
|
453
|
+
return;
|
|
454
|
+
const type = String(event.type ?? "ui");
|
|
455
|
+
if (type === "shell.chunk") {
|
|
456
|
+
const pending = firstPendingShell(state);
|
|
457
|
+
const chunk = asText(event.chunk);
|
|
458
|
+
if (pending) {
|
|
459
|
+
pending.sawChunk = true;
|
|
460
|
+
pending.onData(Buffer.from(chunk));
|
|
461
|
+
} else {
|
|
462
|
+
appendTranscript(state, "Tool", chunk);
|
|
463
|
+
}
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (type === "shell.end") {
|
|
467
|
+
const pending = firstPendingShell(state);
|
|
468
|
+
const output = asText(event.output ?? "");
|
|
469
|
+
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
470
|
+
if (pending) {
|
|
471
|
+
if (output && !pending.sawChunk)
|
|
472
|
+
pending.onData(Buffer.from(output));
|
|
473
|
+
finishPendingShell(state, pending, { exitCode });
|
|
474
|
+
} else {
|
|
475
|
+
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
476
|
+
}
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (type === "shell.start") {
|
|
480
|
+
if (!firstPendingShell(state))
|
|
481
|
+
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
485
|
+
}
|
|
486
|
+
function applyEnvelope(ctx, state, envelopeValue) {
|
|
487
|
+
const envelope = recordOf(envelopeValue);
|
|
488
|
+
if (!envelope)
|
|
489
|
+
return;
|
|
490
|
+
const type = String(envelope.type ?? "");
|
|
491
|
+
if (type === "ready") {
|
|
492
|
+
const metadata = recordOf(envelope.metadata);
|
|
493
|
+
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
494
|
+
state.status = "worker Pi daemon ready";
|
|
495
|
+
if (!state.nativeStream)
|
|
496
|
+
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
497
|
+
} else if (type === "status.update") {
|
|
498
|
+
applyStatus(state, envelope);
|
|
499
|
+
} else if (type === "activity.update") {
|
|
500
|
+
const activity = recordOf(envelope.activity);
|
|
501
|
+
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
502
|
+
} else if (type === "extension_ui_request") {
|
|
503
|
+
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
504
|
+
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
505
|
+
} else if (type === "pi.ui_event") {
|
|
506
|
+
applyUiEvent(state, envelope.event);
|
|
507
|
+
} else if (type === "pi.event") {
|
|
508
|
+
applyPiEvent(ctx, state, envelope.event);
|
|
509
|
+
} else if (type === "error") {
|
|
510
|
+
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
511
|
+
}
|
|
512
|
+
syncNativeDisplayCwd(ctx, state);
|
|
513
|
+
}
|
|
514
|
+
function resolveAttachReadyTimeoutMs() {
|
|
515
|
+
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
516
|
+
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
517
|
+
}
|
|
518
|
+
function formatElapsed(sinceMs) {
|
|
519
|
+
const totalSeconds = Math.floor((Date.now() - sinceMs) / 1000);
|
|
520
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
521
|
+
const seconds = totalSeconds % 60;
|
|
522
|
+
return minutes > 0 ? `${minutes}m${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
|
|
523
|
+
}
|
|
524
|
+
async function waitForWorkerReady(options, ctx, state) {
|
|
525
|
+
const startedAt = Date.now();
|
|
526
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
527
|
+
let consecutiveFailures = 0;
|
|
528
|
+
while (true) {
|
|
529
|
+
let requestFailed = false;
|
|
530
|
+
const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => {
|
|
531
|
+
requestFailed = true;
|
|
532
|
+
return {
|
|
533
|
+
ready: false,
|
|
534
|
+
status: error instanceof Error ? error.message : String(error),
|
|
535
|
+
retryAfterMs: 1000
|
|
536
|
+
};
|
|
537
|
+
});
|
|
538
|
+
if (session.ready === false) {
|
|
539
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
540
|
+
const status = String(session.status ?? "starting");
|
|
541
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
542
|
+
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>\`.`);
|
|
543
|
+
return false;
|
|
544
|
+
}
|
|
545
|
+
if (consecutiveFailures >= 5) {
|
|
546
|
+
state.status = `Rig server unreachable \xB7 retrying (${formatElapsed(startedAt)}) \xB7 /detach to exit`;
|
|
547
|
+
} else {
|
|
548
|
+
state.status = `waiting for worker Pi daemon \xB7 ${status} \xB7 ${formatElapsed(startedAt)} \xB7 /detach to exit`;
|
|
549
|
+
}
|
|
550
|
+
updatePiUi(ctx, state);
|
|
551
|
+
if (Date.now() >= deadline) {
|
|
552
|
+
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.");
|
|
553
|
+
return false;
|
|
554
|
+
}
|
|
555
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
const sessionRecord = recordOf(session) ?? {};
|
|
559
|
+
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
560
|
+
updatePiUi(ctx, state);
|
|
561
|
+
return true;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
function parseWsPayload(message) {
|
|
565
|
+
if (typeof message.data === "string")
|
|
566
|
+
return JSON.parse(message.data);
|
|
567
|
+
return JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
568
|
+
}
|
|
569
|
+
var BRIDGE_LOCAL_COMMANDS = new Set(["detach", "quit", "q", "stop"]);
|
|
570
|
+
function registerDaemonCommandsNatively(pi, options, ctx, state, commands, registered) {
|
|
571
|
+
for (const command of commands) {
|
|
572
|
+
const record = recordOf(command);
|
|
573
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
574
|
+
if (!name || registered.has(name) || BRIDGE_LOCAL_COMMANDS.has(name))
|
|
575
|
+
continue;
|
|
576
|
+
registered.add(name);
|
|
577
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
578
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
579
|
+
try {
|
|
580
|
+
pi.registerCommand(name, {
|
|
581
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
582
|
+
handler: async (args) => {
|
|
583
|
+
const text = `/${name}${args ? ` ${args}` : ""}`;
|
|
584
|
+
appendTranscript(state, "You", text);
|
|
585
|
+
try {
|
|
586
|
+
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
587
|
+
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
588
|
+
appendTranscript(state, "System", message);
|
|
589
|
+
if (state.nativeStream)
|
|
590
|
+
ctx.ui.notify(message, "info");
|
|
591
|
+
} catch (error) {
|
|
592
|
+
reportBridgeError(ctx, state, error instanceof Error ? error.message : String(error));
|
|
593
|
+
}
|
|
594
|
+
updatePiUi(ctx, state);
|
|
595
|
+
}
|
|
596
|
+
});
|
|
597
|
+
} catch {}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
async function connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands) {
|
|
601
|
+
const ready = await waitForWorkerReady(options, ctx, state);
|
|
602
|
+
if (!ready)
|
|
603
|
+
return;
|
|
604
|
+
let catchupDone = false;
|
|
605
|
+
const buffered = [];
|
|
606
|
+
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
607
|
+
const socket = new WebSocket(wsUrl);
|
|
608
|
+
const closePromise = new Promise((resolve3) => {
|
|
609
|
+
socket.onopen = () => {
|
|
610
|
+
state.wsConnected = true;
|
|
611
|
+
state.status = "live worker Pi WebSocket connected";
|
|
612
|
+
updatePiUi(ctx, state);
|
|
613
|
+
};
|
|
614
|
+
socket.onmessage = (message) => {
|
|
615
|
+
try {
|
|
616
|
+
const payload = parseWsPayload(message);
|
|
617
|
+
if (!catchupDone)
|
|
618
|
+
buffered.push(payload);
|
|
619
|
+
else {
|
|
620
|
+
applyEnvelope(ctx, state, payload);
|
|
621
|
+
updatePiUi(ctx, state);
|
|
622
|
+
}
|
|
623
|
+
} catch (error) {
|
|
624
|
+
appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
625
|
+
updatePiUi(ctx, state);
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
socket.onerror = () => socket.close();
|
|
629
|
+
socket.onclose = () => {
|
|
630
|
+
state.wsConnected = false;
|
|
631
|
+
state.status = "worker Pi WebSocket disconnected";
|
|
632
|
+
updatePiUi(ctx, state);
|
|
633
|
+
resolve3();
|
|
634
|
+
};
|
|
635
|
+
});
|
|
636
|
+
try {
|
|
637
|
+
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
638
|
+
getRunPiMessagesViaServer(options.context, options.runId),
|
|
639
|
+
getRunPiStatusViaServer(options.context, options.runId),
|
|
640
|
+
getRunPiCommandsViaServer(options.context, options.runId)
|
|
641
|
+
]);
|
|
642
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
643
|
+
const native = nativePiUi(ctx);
|
|
644
|
+
if (state.nativeStream && native?.appendSessionMessages)
|
|
645
|
+
native.appendSessionMessages(messages);
|
|
646
|
+
else
|
|
647
|
+
for (const message of messages)
|
|
648
|
+
applyMessage(state, message);
|
|
649
|
+
applyStatus(state, statusPayload);
|
|
650
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
651
|
+
state.commands = commands.flatMap((command) => {
|
|
652
|
+
const record = recordOf(command);
|
|
653
|
+
return typeof record?.name === "string" ? [`/${record.name}`] : [];
|
|
654
|
+
});
|
|
655
|
+
registerDaemonCommandsNatively(pi, options, ctx, state, commands, registeredDaemonCommands);
|
|
656
|
+
catchupDone = true;
|
|
657
|
+
for (const payload of buffered.splice(0))
|
|
658
|
+
applyEnvelope(ctx, state, payload);
|
|
659
|
+
updatePiUi(ctx, state);
|
|
660
|
+
} catch (error) {
|
|
661
|
+
appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
662
|
+
catchupDone = true;
|
|
663
|
+
updatePiUi(ctx, state);
|
|
664
|
+
}
|
|
665
|
+
await closePromise;
|
|
666
|
+
}
|
|
667
|
+
function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
668
|
+
return {
|
|
669
|
+
exec(command, _cwd, execOptions) {
|
|
670
|
+
return new Promise((resolve3, reject) => {
|
|
671
|
+
const pending = {
|
|
672
|
+
command,
|
|
673
|
+
onData: execOptions.onData,
|
|
674
|
+
resolve: resolve3,
|
|
675
|
+
reject,
|
|
676
|
+
sawChunk: false
|
|
677
|
+
};
|
|
678
|
+
const cleanup = () => {
|
|
679
|
+
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
680
|
+
if (timer)
|
|
681
|
+
clearTimeout(timer);
|
|
682
|
+
};
|
|
683
|
+
const onAbort = () => {
|
|
684
|
+
cleanup();
|
|
685
|
+
failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
|
|
686
|
+
};
|
|
687
|
+
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
688
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
689
|
+
cleanup();
|
|
690
|
+
failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
691
|
+
}, timeoutMs) : null;
|
|
692
|
+
const wrappedResolve = pending.resolve;
|
|
693
|
+
const wrappedReject = pending.reject;
|
|
694
|
+
pending.resolve = (result) => {
|
|
695
|
+
cleanup();
|
|
696
|
+
wrappedResolve(result);
|
|
697
|
+
};
|
|
698
|
+
pending.reject = (error) => {
|
|
699
|
+
cleanup();
|
|
700
|
+
wrappedReject(error);
|
|
701
|
+
};
|
|
702
|
+
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
703
|
+
state.pendingShells.push(pending);
|
|
704
|
+
sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
705
|
+
cleanup();
|
|
706
|
+
failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
async function answerPendingUi(options, state, line) {
|
|
713
|
+
const pending = state.pendingUi;
|
|
714
|
+
if (!pending)
|
|
715
|
+
return false;
|
|
716
|
+
if (line === "/cancel") {
|
|
717
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
718
|
+
} else if (pending.method === "confirm") {
|
|
719
|
+
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
720
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
721
|
+
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
722
|
+
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
723
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
724
|
+
} else {
|
|
725
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
726
|
+
}
|
|
727
|
+
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
728
|
+
state.pendingUi = null;
|
|
729
|
+
return true;
|
|
730
|
+
}
|
|
731
|
+
async function routeInput(options, ctx, state, line) {
|
|
732
|
+
const text = line.trim();
|
|
733
|
+
if (!text)
|
|
734
|
+
return;
|
|
735
|
+
if (await answerPendingUi(options, state, text)) {
|
|
736
|
+
updatePiUi(ctx, state);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
if (text === "/detach" || text === "/quit" || text === "/q") {
|
|
740
|
+
appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
|
|
741
|
+
updatePiUi(ctx, state);
|
|
742
|
+
ctx.shutdown();
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (text === "/stop") {
|
|
746
|
+
await abortRunPiViaServer(options.context, options.runId);
|
|
747
|
+
appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
|
|
748
|
+
updatePiUi(ctx, state);
|
|
749
|
+
ctx.shutdown();
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (text.startsWith("!")) {
|
|
753
|
+
appendTranscript(state, "You", text);
|
|
754
|
+
await sendRunPiShellViaServer(options.context, options.runId, text);
|
|
755
|
+
} else if (text.startsWith("/")) {
|
|
756
|
+
appendTranscript(state, "You", text);
|
|
757
|
+
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
758
|
+
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
759
|
+
appendTranscript(state, "System", message);
|
|
760
|
+
} else {
|
|
761
|
+
appendTranscript(state, "You", text);
|
|
762
|
+
await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
|
|
763
|
+
}
|
|
764
|
+
updatePiUi(ctx, state);
|
|
765
|
+
}
|
|
766
|
+
function createRigWorkerPiBridgeExtension(options) {
|
|
767
|
+
return (pi) => {
|
|
768
|
+
const state = {
|
|
769
|
+
transcript: [],
|
|
770
|
+
status: "starting worker Pi daemon bridge",
|
|
771
|
+
activity: "",
|
|
772
|
+
cwd: "",
|
|
773
|
+
model: "",
|
|
774
|
+
commands: [],
|
|
775
|
+
streaming: false,
|
|
776
|
+
pendingUi: null,
|
|
777
|
+
pendingShells: [],
|
|
778
|
+
wsConnected: false,
|
|
779
|
+
nativeStream: false
|
|
780
|
+
};
|
|
781
|
+
if (options.initialMessageSent)
|
|
782
|
+
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
783
|
+
const registeredDaemonCommands = new Set;
|
|
784
|
+
let nativePiUiContextAvailable = false;
|
|
785
|
+
pi.on("user_bash", (event) => {
|
|
786
|
+
state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
|
|
787
|
+
return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
|
|
788
|
+
});
|
|
789
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
790
|
+
nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
|
|
791
|
+
state.nativeStream = nativePiUiContextAvailable;
|
|
792
|
+
updatePiUi(ctx, state);
|
|
793
|
+
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");
|
|
794
|
+
ctx.ui.onTerminalInput((data) => {
|
|
795
|
+
if (data.includes("\x04")) {
|
|
796
|
+
ctx.shutdown();
|
|
797
|
+
return { consume: true };
|
|
798
|
+
}
|
|
799
|
+
if (!data.includes("\r") && !data.includes(`
|
|
800
|
+
`))
|
|
801
|
+
return;
|
|
802
|
+
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
803
|
+
const editorText = ctx.ui.getEditorText().trim();
|
|
804
|
+
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
805
|
+
if (!text)
|
|
806
|
+
return;
|
|
807
|
+
if (text.startsWith("!"))
|
|
808
|
+
return;
|
|
809
|
+
ctx.ui.setEditorText("");
|
|
810
|
+
routeInput(options, ctx, state, text).catch((error) => {
|
|
811
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
812
|
+
updatePiUi(ctx, state);
|
|
813
|
+
});
|
|
814
|
+
return { consume: true };
|
|
815
|
+
});
|
|
816
|
+
connectWorkerStream(options, pi, ctx, state, registeredDaemonCommands).catch((error) => {
|
|
817
|
+
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
818
|
+
updatePiUi(ctx, state);
|
|
819
|
+
});
|
|
820
|
+
});
|
|
821
|
+
pi.on("session_shutdown", () => {});
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
export {
|
|
825
|
+
createRigWorkerPiBridgeExtension
|
|
826
|
+
};
|