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