@h-rig/cli 0.0.6-alpha.28 → 0.0.6-alpha.281
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/README.md +6 -28
- package/package.json +11 -28
- package/dist/bin/build-rig-binaries.js +0 -107
- package/dist/bin/rig.js +0 -11739
- package/dist/src/commands/_authority-runs.js +0 -111
- package/dist/src/commands/_cli-format.js +0 -369
- package/dist/src/commands/_connection-state.js +0 -123
- package/dist/src/commands/_doctor-checks.js +0 -507
- package/dist/src/commands/_help-catalog.js +0 -364
- package/dist/src/commands/_operator-surface.js +0 -204
- package/dist/src/commands/_operator-view.js +0 -1147
- package/dist/src/commands/_parsers.js +0 -107
- package/dist/src/commands/_paths.js +0 -50
- package/dist/src/commands/_pi-frontend.js +0 -843
- package/dist/src/commands/_pi-install.js +0 -185
- package/dist/src/commands/_pi-worker-bridge-extension.js +0 -761
- package/dist/src/commands/_policy.js +0 -79
- package/dist/src/commands/_preflight.js +0 -403
- package/dist/src/commands/_probes.js +0 -13
- package/dist/src/commands/_run-driver-helpers.js +0 -289
- package/dist/src/commands/_server-client.js +0 -514
- package/dist/src/commands/_snapshot-upload.js +0 -318
- package/dist/src/commands/_task-picker.js +0 -76
- package/dist/src/commands/agent.js +0 -499
- package/dist/src/commands/browser.js +0 -890
- package/dist/src/commands/connect.js +0 -289
- package/dist/src/commands/dist.js +0 -402
- package/dist/src/commands/doctor.js +0 -517
- package/dist/src/commands/github.js +0 -281
- package/dist/src/commands/inbox.js +0 -482
- package/dist/src/commands/init.js +0 -1563
- package/dist/src/commands/inspect.js +0 -174
- package/dist/src/commands/inspector.js +0 -256
- package/dist/src/commands/plugin.js +0 -167
- package/dist/src/commands/profile-and-review.js +0 -178
- package/dist/src/commands/queue.js +0 -198
- package/dist/src/commands/remote.js +0 -507
- package/dist/src/commands/repo-git-harness.js +0 -221
- package/dist/src/commands/run.js +0 -1808
- package/dist/src/commands/server.js +0 -572
- package/dist/src/commands/setup.js +0 -687
- package/dist/src/commands/task-report-bug.js +0 -1083
- package/dist/src/commands/task-run-driver.js +0 -2600
- package/dist/src/commands/task.js +0 -2606
- package/dist/src/commands/test.js +0 -39
- package/dist/src/commands/workspace.js +0 -123
- package/dist/src/commands.js +0 -11418
- package/dist/src/index.js +0 -11757
- package/dist/src/launcher.js +0 -133
- package/dist/src/report-bug.js +0 -260
- package/dist/src/runner.js +0 -273
- package/dist/src/withMutedConsole.js +0 -42
package/dist/src/commands/run.js
DELETED
|
@@ -1,1808 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
// packages/cli/src/commands/run.ts
|
|
3
|
-
import { createInterface as createInterface2 } from "readline/promises";
|
|
4
|
-
|
|
5
|
-
// packages/cli/src/runner.ts
|
|
6
|
-
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
7
|
-
import { CliError } from "@rig/runtime/control-plane/errors";
|
|
8
|
-
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
9
|
-
import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
|
|
10
|
-
import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
|
|
11
|
-
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
12
|
-
import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
|
|
13
|
-
function takeFlag(args, flag) {
|
|
14
|
-
const rest = [];
|
|
15
|
-
let value = false;
|
|
16
|
-
for (const arg of args) {
|
|
17
|
-
if (arg === flag) {
|
|
18
|
-
value = true;
|
|
19
|
-
continue;
|
|
20
|
-
}
|
|
21
|
-
rest.push(arg);
|
|
22
|
-
}
|
|
23
|
-
return { value, rest };
|
|
24
|
-
}
|
|
25
|
-
function takeOption(args, option) {
|
|
26
|
-
const rest = [];
|
|
27
|
-
let value;
|
|
28
|
-
for (let index = 0;index < args.length; index += 1) {
|
|
29
|
-
const current = args[index];
|
|
30
|
-
if (current === option) {
|
|
31
|
-
const next = args[index + 1];
|
|
32
|
-
if (!next || next.startsWith("-")) {
|
|
33
|
-
throw new CliError(`Missing value for ${option}`);
|
|
34
|
-
}
|
|
35
|
-
value = next;
|
|
36
|
-
index += 1;
|
|
37
|
-
continue;
|
|
38
|
-
}
|
|
39
|
-
if (current !== undefined) {
|
|
40
|
-
rest.push(current);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return { value, rest };
|
|
44
|
-
}
|
|
45
|
-
function requireNoExtraArgs(args, usage) {
|
|
46
|
-
if (args.length > 0) {
|
|
47
|
-
throw new CliError(`Unexpected arguments: ${args.join(" ")}
|
|
48
|
-
Usage: ${usage}`);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// packages/cli/src/commands/run.ts
|
|
53
|
-
import {
|
|
54
|
-
listAuthorityRuns,
|
|
55
|
-
readAuthorityRun
|
|
56
|
-
} from "@rig/runtime/control-plane/authority-files";
|
|
57
|
-
import {
|
|
58
|
-
cleanupRunState,
|
|
59
|
-
deleteRunState,
|
|
60
|
-
listOpenEpics,
|
|
61
|
-
resolveDefaultEpic,
|
|
62
|
-
runResume,
|
|
63
|
-
runRestart,
|
|
64
|
-
runStatus,
|
|
65
|
-
runStop,
|
|
66
|
-
startRun,
|
|
67
|
-
defaultStartRunOptions
|
|
68
|
-
} from "@rig/runtime/control-plane/native/run-ops";
|
|
69
|
-
import { loadRuntimeContextFromEnv as loadRuntimeContextFromEnv2 } from "@rig/runtime/control-plane/runtime/context";
|
|
70
|
-
|
|
71
|
-
// packages/cli/src/commands/_parsers.ts
|
|
72
|
-
function parsePositiveInt(value, option, fallback) {
|
|
73
|
-
if (!value) {
|
|
74
|
-
return fallback;
|
|
75
|
-
}
|
|
76
|
-
const parsed = Number.parseInt(value, 10);
|
|
77
|
-
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
78
|
-
throw new CliError2(`Invalid ${option} value: ${value}`);
|
|
79
|
-
}
|
|
80
|
-
return parsed;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// packages/cli/src/commands/_server-client.ts
|
|
84
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
85
|
-
import { resolve as resolve2 } from "path";
|
|
86
|
-
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
87
|
-
|
|
88
|
-
// packages/cli/src/commands/_connection-state.ts
|
|
89
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
90
|
-
import { homedir } from "os";
|
|
91
|
-
import { dirname, resolve } from "path";
|
|
92
|
-
function resolveGlobalConnectionsPath(env = process.env) {
|
|
93
|
-
const explicit = env.RIG_CONNECTIONS_FILE?.trim();
|
|
94
|
-
if (explicit)
|
|
95
|
-
return resolve(explicit);
|
|
96
|
-
const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
|
|
97
|
-
if (stateDir)
|
|
98
|
-
return resolve(stateDir, "connections.json");
|
|
99
|
-
return resolve(homedir(), ".rig", "connections.json");
|
|
100
|
-
}
|
|
101
|
-
function resolveRepoConnectionPath(projectRoot) {
|
|
102
|
-
return resolve(projectRoot, ".rig", "state", "connection.json");
|
|
103
|
-
}
|
|
104
|
-
function readJsonFile(path) {
|
|
105
|
-
if (!existsSync(path))
|
|
106
|
-
return null;
|
|
107
|
-
try {
|
|
108
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
109
|
-
} catch (error) {
|
|
110
|
-
throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
function normalizeConnection(value) {
|
|
114
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
115
|
-
return null;
|
|
116
|
-
const record = value;
|
|
117
|
-
if (record.kind === "local")
|
|
118
|
-
return { kind: "local", mode: "auto" };
|
|
119
|
-
if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
|
|
120
|
-
const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
|
|
121
|
-
return { kind: "remote", baseUrl };
|
|
122
|
-
}
|
|
123
|
-
return null;
|
|
124
|
-
}
|
|
125
|
-
function readGlobalConnections(options = {}) {
|
|
126
|
-
const path = resolveGlobalConnectionsPath(options.env ?? process.env);
|
|
127
|
-
const payload = readJsonFile(path);
|
|
128
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
129
|
-
return { connections: {} };
|
|
130
|
-
}
|
|
131
|
-
const rawConnections = payload.connections;
|
|
132
|
-
const connections = {};
|
|
133
|
-
if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
|
|
134
|
-
for (const [alias, raw] of Object.entries(rawConnections)) {
|
|
135
|
-
const connection = normalizeConnection(raw);
|
|
136
|
-
if (connection)
|
|
137
|
-
connections[alias] = connection;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
return { connections };
|
|
141
|
-
}
|
|
142
|
-
function readRepoConnection(projectRoot) {
|
|
143
|
-
const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
|
|
144
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
145
|
-
return null;
|
|
146
|
-
const record = payload;
|
|
147
|
-
const selected = typeof record.selected === "string" ? record.selected.trim() : "";
|
|
148
|
-
if (!selected)
|
|
149
|
-
return null;
|
|
150
|
-
return {
|
|
151
|
-
selected,
|
|
152
|
-
project: typeof record.project === "string" ? record.project : undefined,
|
|
153
|
-
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
157
|
-
const repo = readRepoConnection(projectRoot);
|
|
158
|
-
if (!repo)
|
|
159
|
-
return null;
|
|
160
|
-
if (repo.selected === "local")
|
|
161
|
-
return { alias: "local", connection: { kind: "local", mode: "auto" } };
|
|
162
|
-
const global = readGlobalConnections(options);
|
|
163
|
-
const connection = global.connections[repo.selected];
|
|
164
|
-
if (!connection) {
|
|
165
|
-
throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
166
|
-
}
|
|
167
|
-
return { alias: repo.selected, connection };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// packages/cli/src/commands/_server-client.ts
|
|
171
|
-
var scopedGitHubBearerTokens = new Map;
|
|
172
|
-
function cleanToken(value) {
|
|
173
|
-
const trimmed = value?.trim();
|
|
174
|
-
return trimmed ? trimmed : null;
|
|
175
|
-
}
|
|
176
|
-
function readPrivateRemoteSessionToken(projectRoot) {
|
|
177
|
-
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
178
|
-
if (!existsSync2(path))
|
|
179
|
-
return null;
|
|
180
|
-
try {
|
|
181
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
182
|
-
return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
|
|
183
|
-
} catch {
|
|
184
|
-
return null;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
188
|
-
const scopedKey = resolve2(projectRoot);
|
|
189
|
-
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
190
|
-
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
191
|
-
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
192
|
-
if (privateSession)
|
|
193
|
-
return privateSession;
|
|
194
|
-
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
195
|
-
}
|
|
196
|
-
async function ensureServerForCli(projectRoot) {
|
|
197
|
-
try {
|
|
198
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
199
|
-
if (selected?.connection.kind === "remote") {
|
|
200
|
-
return {
|
|
201
|
-
baseUrl: selected.connection.baseUrl,
|
|
202
|
-
authToken: readGitHubBearerTokenForRemote(projectRoot),
|
|
203
|
-
connectionKind: "remote"
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
207
|
-
return {
|
|
208
|
-
baseUrl: connection.baseUrl,
|
|
209
|
-
authToken: connection.authToken,
|
|
210
|
-
connectionKind: "local"
|
|
211
|
-
};
|
|
212
|
-
} catch (error) {
|
|
213
|
-
if (error instanceof Error) {
|
|
214
|
-
throw new CliError2(error.message, 1);
|
|
215
|
-
}
|
|
216
|
-
throw error;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
function mergeHeaders(headers, authToken) {
|
|
220
|
-
const merged = new Headers(headers);
|
|
221
|
-
if (authToken) {
|
|
222
|
-
merged.set("authorization", `Bearer ${authToken}`);
|
|
223
|
-
}
|
|
224
|
-
return merged;
|
|
225
|
-
}
|
|
226
|
-
function diagnosticMessage(payload) {
|
|
227
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
228
|
-
return null;
|
|
229
|
-
const record = payload;
|
|
230
|
-
const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
|
|
231
|
-
const messages = diagnostics.flatMap((entry) => {
|
|
232
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
233
|
-
return [];
|
|
234
|
-
const diagnostic = entry;
|
|
235
|
-
const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
|
|
236
|
-
const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
|
|
237
|
-
return message ? [`${kind}: ${message}`] : [];
|
|
238
|
-
});
|
|
239
|
-
return messages.length > 0 ? messages.join("; ") : null;
|
|
240
|
-
}
|
|
241
|
-
async function requestServerJson(context, pathname, init = {}) {
|
|
242
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
243
|
-
const response = await fetch(`${server.baseUrl}${pathname}`, {
|
|
244
|
-
...init,
|
|
245
|
-
headers: mergeHeaders(init.headers, server.authToken)
|
|
246
|
-
});
|
|
247
|
-
const text = await response.text();
|
|
248
|
-
const payload = text.trim().length > 0 ? (() => {
|
|
249
|
-
try {
|
|
250
|
-
return JSON.parse(text);
|
|
251
|
-
} catch {
|
|
252
|
-
return null;
|
|
253
|
-
}
|
|
254
|
-
})() : null;
|
|
255
|
-
if (!response.ok) {
|
|
256
|
-
const diagnostics = diagnosticMessage(payload);
|
|
257
|
-
const detail = diagnostics ?? (text || response.statusText);
|
|
258
|
-
throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
|
|
259
|
-
}
|
|
260
|
-
return payload;
|
|
261
|
-
}
|
|
262
|
-
async function listRunsViaServer(context, options = {}) {
|
|
263
|
-
const url = new URL("http://rig.local/api/runs");
|
|
264
|
-
if (options.limit !== undefined)
|
|
265
|
-
url.searchParams.set("limit", String(options.limit));
|
|
266
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
267
|
-
const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
|
|
268
|
-
return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
|
|
269
|
-
}
|
|
270
|
-
async function getRunDetailsViaServer(context, runId) {
|
|
271
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
|
|
272
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
273
|
-
}
|
|
274
|
-
async function getRunLogsViaServer(context, runId, options = {}) {
|
|
275
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
|
|
276
|
-
if (options.limit !== undefined)
|
|
277
|
-
url.searchParams.set("limit", String(options.limit));
|
|
278
|
-
if (options.cursor)
|
|
279
|
-
url.searchParams.set("cursor", options.cursor);
|
|
280
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
281
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
282
|
-
}
|
|
283
|
-
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
284
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
285
|
-
if (options.limit !== undefined)
|
|
286
|
-
url.searchParams.set("limit", String(options.limit));
|
|
287
|
-
if (options.cursor)
|
|
288
|
-
url.searchParams.set("cursor", options.cursor);
|
|
289
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
290
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
291
|
-
}
|
|
292
|
-
async function stopRunViaServer(context, runId) {
|
|
293
|
-
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
294
|
-
method: "POST",
|
|
295
|
-
headers: { "content-type": "application/json" },
|
|
296
|
-
body: JSON.stringify({ runId })
|
|
297
|
-
});
|
|
298
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
|
|
299
|
-
}
|
|
300
|
-
async function steerRunViaServer(context, runId, message) {
|
|
301
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
|
|
302
|
-
method: "POST",
|
|
303
|
-
headers: { "content-type": "application/json" },
|
|
304
|
-
body: JSON.stringify({ message })
|
|
305
|
-
});
|
|
306
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
307
|
-
}
|
|
308
|
-
async function getRunPiSessionViaServer(context, runId) {
|
|
309
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
310
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
311
|
-
}
|
|
312
|
-
async function getRunPiMessagesViaServer(context, runId) {
|
|
313
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
314
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
315
|
-
}
|
|
316
|
-
async function getRunPiStatusViaServer(context, runId) {
|
|
317
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
318
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
319
|
-
}
|
|
320
|
-
async function getRunPiCommandsViaServer(context, runId) {
|
|
321
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
322
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
323
|
-
}
|
|
324
|
-
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
325
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
326
|
-
method: "POST",
|
|
327
|
-
headers: { "content-type": "application/json" },
|
|
328
|
-
body: JSON.stringify({ text, streamingBehavior })
|
|
329
|
-
});
|
|
330
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
331
|
-
}
|
|
332
|
-
async function sendRunPiShellViaServer(context, runId, text) {
|
|
333
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
334
|
-
method: "POST",
|
|
335
|
-
headers: { "content-type": "application/json" },
|
|
336
|
-
body: JSON.stringify({ text })
|
|
337
|
-
});
|
|
338
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
339
|
-
}
|
|
340
|
-
async function runRunPiCommandViaServer(context, runId, text) {
|
|
341
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
342
|
-
method: "POST",
|
|
343
|
-
headers: { "content-type": "application/json" },
|
|
344
|
-
body: JSON.stringify({ text })
|
|
345
|
-
});
|
|
346
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
347
|
-
}
|
|
348
|
-
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
349
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
350
|
-
method: "POST",
|
|
351
|
-
headers: { "content-type": "application/json" },
|
|
352
|
-
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
353
|
-
});
|
|
354
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
355
|
-
}
|
|
356
|
-
async function abortRunPiViaServer(context, runId) {
|
|
357
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
358
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
359
|
-
}
|
|
360
|
-
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
361
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
362
|
-
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
363
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
364
|
-
if (server.authToken)
|
|
365
|
-
url.searchParams.set("token", server.authToken);
|
|
366
|
-
return url.toString();
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
// packages/cli/src/commands/_operator-surface.ts
|
|
370
|
-
import { createInterface } from "readline";
|
|
371
|
-
var CANONICAL_STAGES = [
|
|
372
|
-
"Connect",
|
|
373
|
-
"GitHub/task sync",
|
|
374
|
-
"Prepare workspace",
|
|
375
|
-
"Launch Pi",
|
|
376
|
-
"Plan",
|
|
377
|
-
"Implement",
|
|
378
|
-
"Validate",
|
|
379
|
-
"Commit",
|
|
380
|
-
"Open PR",
|
|
381
|
-
"Review/CI",
|
|
382
|
-
"Merge",
|
|
383
|
-
"Complete"
|
|
384
|
-
];
|
|
385
|
-
function logDetail(log) {
|
|
386
|
-
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
387
|
-
}
|
|
388
|
-
function parseProviderProtocolLog(title, detail) {
|
|
389
|
-
if (title.trim().toLowerCase() !== "agent output")
|
|
390
|
-
return null;
|
|
391
|
-
if (!detail.startsWith("{") || !detail.endsWith("}"))
|
|
392
|
-
return null;
|
|
393
|
-
try {
|
|
394
|
-
const record = JSON.parse(detail);
|
|
395
|
-
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
396
|
-
return null;
|
|
397
|
-
const type = record.type;
|
|
398
|
-
return typeof type === "string" && [
|
|
399
|
-
"assistant",
|
|
400
|
-
"message_start",
|
|
401
|
-
"message_update",
|
|
402
|
-
"message_end",
|
|
403
|
-
"stream_event",
|
|
404
|
-
"tool_result",
|
|
405
|
-
"tool_execution_start",
|
|
406
|
-
"tool_execution_update",
|
|
407
|
-
"tool_execution_end",
|
|
408
|
-
"turn_start",
|
|
409
|
-
"turn_end"
|
|
410
|
-
].includes(type) ? record : null;
|
|
411
|
-
} catch {
|
|
412
|
-
return null;
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
function renderProviderProtocolLog(record) {
|
|
416
|
-
const type = typeof record.type === "string" ? record.type : "";
|
|
417
|
-
if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
|
|
418
|
-
const toolName = String(record.toolName ?? record.name ?? "tool");
|
|
419
|
-
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";
|
|
420
|
-
return `[Pi tool] ${toolName} ${status}`;
|
|
421
|
-
}
|
|
422
|
-
return null;
|
|
423
|
-
}
|
|
424
|
-
function entryId(entry, fallback) {
|
|
425
|
-
return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
|
|
426
|
-
}
|
|
427
|
-
function renderOperatorSnapshot(snapshot) {
|
|
428
|
-
const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
|
|
429
|
-
const runId = String(run.runId ?? run.id ?? "run");
|
|
430
|
-
const status = String(run.status ?? "unknown");
|
|
431
|
-
const logs = snapshot.logs ?? [];
|
|
432
|
-
const latestByStage = new Map;
|
|
433
|
-
for (const log of logs) {
|
|
434
|
-
const title = String(log.title ?? "").toLowerCase();
|
|
435
|
-
const stageName = String(log.stage ?? "").toLowerCase();
|
|
436
|
-
const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
437
|
-
if (stage)
|
|
438
|
-
latestByStage.set(stage, log);
|
|
439
|
-
}
|
|
440
|
-
const stageLines = CANONICAL_STAGES.flatMap((stage) => {
|
|
441
|
-
const match = latestByStage.get(stage);
|
|
442
|
-
return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
|
|
443
|
-
});
|
|
444
|
-
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
445
|
-
`);
|
|
446
|
-
}
|
|
447
|
-
function createPiRunStreamRenderer(output = process.stdout) {
|
|
448
|
-
let lastSnapshot = "";
|
|
449
|
-
const assistantTextById = new Map;
|
|
450
|
-
const seenTimeline = new Set;
|
|
451
|
-
const seenLogs = new Set;
|
|
452
|
-
const writeLine = (line) => output.write(`${line}
|
|
453
|
-
`);
|
|
454
|
-
return {
|
|
455
|
-
renderSnapshot(snapshot) {
|
|
456
|
-
const rendered = renderOperatorSnapshot(snapshot);
|
|
457
|
-
if (rendered && rendered !== lastSnapshot) {
|
|
458
|
-
writeLine(rendered);
|
|
459
|
-
lastSnapshot = rendered;
|
|
460
|
-
}
|
|
461
|
-
},
|
|
462
|
-
renderTimeline(entries) {
|
|
463
|
-
for (const [index, entry] of entries.entries()) {
|
|
464
|
-
const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
|
|
465
|
-
if (entry.type === "assistant_message" && typeof entry.text === "string") {
|
|
466
|
-
const text = entry.text;
|
|
467
|
-
const previousText = assistantTextById.get(id) ?? "";
|
|
468
|
-
if (!previousText && text.trim()) {
|
|
469
|
-
writeLine("[Pi assistant]");
|
|
470
|
-
}
|
|
471
|
-
if (text.startsWith(previousText)) {
|
|
472
|
-
const delta = text.slice(previousText.length);
|
|
473
|
-
if (delta)
|
|
474
|
-
output.write(delta);
|
|
475
|
-
} else if (text.trim() && text !== previousText) {
|
|
476
|
-
if (previousText)
|
|
477
|
-
writeLine(`
|
|
478
|
-
[Pi assistant]`);
|
|
479
|
-
output.write(text);
|
|
480
|
-
}
|
|
481
|
-
assistantTextById.set(id, text);
|
|
482
|
-
continue;
|
|
483
|
-
}
|
|
484
|
-
if (seenTimeline.has(id))
|
|
485
|
-
continue;
|
|
486
|
-
seenTimeline.add(id);
|
|
487
|
-
if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
|
|
488
|
-
writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
|
|
489
|
-
continue;
|
|
490
|
-
}
|
|
491
|
-
if (entry.type === "timeline_warning") {
|
|
492
|
-
writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
},
|
|
496
|
-
renderLogs(entries) {
|
|
497
|
-
for (const [index, entry] of entries.entries()) {
|
|
498
|
-
const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
|
|
499
|
-
if (seenLogs.has(id))
|
|
500
|
-
continue;
|
|
501
|
-
seenLogs.add(id);
|
|
502
|
-
const title = String(entry.title ?? "");
|
|
503
|
-
if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
|
|
504
|
-
continue;
|
|
505
|
-
const detail = logDetail(entry);
|
|
506
|
-
if (!detail)
|
|
507
|
-
continue;
|
|
508
|
-
const protocolRecord = parseProviderProtocolLog(title, detail);
|
|
509
|
-
if (protocolRecord) {
|
|
510
|
-
const protocolLine = renderProviderProtocolLog(protocolRecord);
|
|
511
|
-
if (protocolLine)
|
|
512
|
-
writeLine(protocolLine);
|
|
513
|
-
continue;
|
|
514
|
-
}
|
|
515
|
-
writeLine(`[${title || "Rig log"}] ${detail}`);
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
};
|
|
519
|
-
}
|
|
520
|
-
function createOperatorSurface(options = {}) {
|
|
521
|
-
const input = options.input ?? process.stdin;
|
|
522
|
-
const output = options.output ?? process.stdout;
|
|
523
|
-
const errorOutput = options.errorOutput ?? process.stderr;
|
|
524
|
-
const renderer = createPiRunStreamRenderer(output);
|
|
525
|
-
const writeLine = (line) => output.write(`${line}
|
|
526
|
-
`);
|
|
527
|
-
return {
|
|
528
|
-
mode: "pi-compatible-text",
|
|
529
|
-
...renderer,
|
|
530
|
-
info: writeLine,
|
|
531
|
-
error: (message) => errorOutput.write(`${message}
|
|
532
|
-
`),
|
|
533
|
-
attachCommandInput(handler) {
|
|
534
|
-
if (options.interactive === false || !input.isTTY)
|
|
535
|
-
return null;
|
|
536
|
-
const rl = createInterface({ input, output: process.stdout, terminal: false });
|
|
537
|
-
rl.on("line", (line) => {
|
|
538
|
-
Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
539
|
-
});
|
|
540
|
-
return { close: () => rl.close() };
|
|
541
|
-
}
|
|
542
|
-
};
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
// packages/cli/src/commands/_pi-frontend.ts
|
|
546
|
-
import { mkdtempSync, rmSync } from "fs";
|
|
547
|
-
import { tmpdir } from "os";
|
|
548
|
-
import { join } from "path";
|
|
549
|
-
import { main as runPiMain } from "@earendil-works/pi-coding-agent";
|
|
550
|
-
|
|
551
|
-
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
552
|
-
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
553
|
-
var MAX_TRANSCRIPT_LINES = 120;
|
|
554
|
-
function recordOf(value) {
|
|
555
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
556
|
-
}
|
|
557
|
-
function asText(value) {
|
|
558
|
-
if (typeof value === "string")
|
|
559
|
-
return value;
|
|
560
|
-
if (value === null || value === undefined)
|
|
561
|
-
return "";
|
|
562
|
-
if (typeof value === "number" || typeof value === "boolean")
|
|
563
|
-
return String(value);
|
|
564
|
-
try {
|
|
565
|
-
return JSON.stringify(value);
|
|
566
|
-
} catch {
|
|
567
|
-
return String(value);
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
function textFromContent(content) {
|
|
571
|
-
if (typeof content === "string")
|
|
572
|
-
return content;
|
|
573
|
-
if (!Array.isArray(content))
|
|
574
|
-
return asText(content);
|
|
575
|
-
return content.flatMap((part) => {
|
|
576
|
-
const item = recordOf(part);
|
|
577
|
-
if (!item)
|
|
578
|
-
return [];
|
|
579
|
-
if (typeof item.text === "string")
|
|
580
|
-
return [item.text];
|
|
581
|
-
if (typeof item.content === "string")
|
|
582
|
-
return [item.content];
|
|
583
|
-
if (item.type === "toolCall")
|
|
584
|
-
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
585
|
-
if (item.type === "toolResult")
|
|
586
|
-
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
587
|
-
return [];
|
|
588
|
-
}).join(`
|
|
589
|
-
`);
|
|
590
|
-
}
|
|
591
|
-
function appendTranscript(state, label, text) {
|
|
592
|
-
const trimmed = text.trimEnd();
|
|
593
|
-
if (!trimmed)
|
|
594
|
-
return;
|
|
595
|
-
const lines = trimmed.split(/\r?\n/);
|
|
596
|
-
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
597
|
-
for (const line of lines.slice(1))
|
|
598
|
-
state.transcript.push(` ${line}`);
|
|
599
|
-
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
600
|
-
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
function nativePiUi(ctx) {
|
|
604
|
-
const ui = ctx.ui;
|
|
605
|
-
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
606
|
-
}
|
|
607
|
-
function syncNativeDisplayCwd(ctx, state) {
|
|
608
|
-
const ui = nativePiUi(ctx);
|
|
609
|
-
if (ui?.setDisplayCwd && state.cwd)
|
|
610
|
-
ui.setDisplayCwd(state.cwd);
|
|
611
|
-
}
|
|
612
|
-
function parseExtensionUiRequest(value) {
|
|
613
|
-
const request = recordOf(value) ?? {};
|
|
614
|
-
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
615
|
-
const method = String(request.method ?? request.type ?? "input");
|
|
616
|
-
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
617
|
-
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
618
|
-
const options = rawOptions.map((option) => {
|
|
619
|
-
const record = recordOf(option);
|
|
620
|
-
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
621
|
-
}).filter(Boolean);
|
|
622
|
-
return { requestId, method, prompt, options };
|
|
623
|
-
}
|
|
624
|
-
function renderBridgeWidget(state) {
|
|
625
|
-
const statusParts = [
|
|
626
|
-
state.wsConnected ? "live WS" : "WS pending",
|
|
627
|
-
state.status,
|
|
628
|
-
state.model,
|
|
629
|
-
state.cwd
|
|
630
|
-
].filter(Boolean);
|
|
631
|
-
const lines = [`Worker Pi daemon bridge \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
632
|
-
if (state.activity)
|
|
633
|
-
lines.push(state.activity);
|
|
634
|
-
if (state.commands.length > 0) {
|
|
635
|
-
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
636
|
-
}
|
|
637
|
-
lines.push("");
|
|
638
|
-
if (state.transcript.length > 0) {
|
|
639
|
-
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
640
|
-
} else {
|
|
641
|
-
lines.push("Waiting for worker Pi daemon transcript\u2026");
|
|
642
|
-
}
|
|
643
|
-
if (state.pendingUi) {
|
|
644
|
-
lines.push("");
|
|
645
|
-
lines.push(`Extension UI request \xB7 ${state.pendingUi.method}`);
|
|
646
|
-
lines.push(state.pendingUi.prompt);
|
|
647
|
-
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
648
|
-
lines.push("Reply in the Pi editor. /cancel cancels this request.");
|
|
649
|
-
}
|
|
650
|
-
return lines;
|
|
651
|
-
}
|
|
652
|
-
function updatePiUi(ctx, state) {
|
|
653
|
-
ctx.ui.setTitle("Pi \xB7 Rig worker daemon");
|
|
654
|
-
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker Pi WS live" : state.status);
|
|
655
|
-
syncNativeDisplayCwd(ctx, state);
|
|
656
|
-
if (state.nativeStream && nativePiUi(ctx)) {
|
|
657
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
658
|
-
return;
|
|
659
|
-
}
|
|
660
|
-
ctx.ui.setWorkingVisible(false);
|
|
661
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", [`Worker Pi daemon bridge \xB7 degraded widget transcript`, ...renderBridgeWidget(state)], { placement: "aboveEditor" });
|
|
662
|
-
}
|
|
663
|
-
function applyStatus(state, payload) {
|
|
664
|
-
const status = recordOf(payload.status) ?? payload;
|
|
665
|
-
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
666
|
-
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
667
|
-
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
668
|
-
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
669
|
-
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
670
|
-
}
|
|
671
|
-
function applyMessage(state, message) {
|
|
672
|
-
const record = recordOf(message);
|
|
673
|
-
if (!record)
|
|
674
|
-
return;
|
|
675
|
-
const role = String(record.role ?? "system");
|
|
676
|
-
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
677
|
-
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
678
|
-
}
|
|
679
|
-
function applyPiEvent(ctx, state, eventValue) {
|
|
680
|
-
const event = recordOf(eventValue);
|
|
681
|
-
if (!event)
|
|
682
|
-
return;
|
|
683
|
-
const type = String(event.type ?? "event");
|
|
684
|
-
if (type === "agent_start") {
|
|
685
|
-
state.streaming = true;
|
|
686
|
-
state.status = "streaming";
|
|
687
|
-
} else if (type === "agent_end") {
|
|
688
|
-
state.streaming = false;
|
|
689
|
-
state.status = "idle";
|
|
690
|
-
} else if (type === "queue_update") {
|
|
691
|
-
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
692
|
-
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
693
|
-
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
694
|
-
}
|
|
695
|
-
const native = nativePiUi(ctx);
|
|
696
|
-
if (state.nativeStream && native?.emitSessionEvent) {
|
|
697
|
-
native.emitSessionEvent(eventValue);
|
|
698
|
-
return;
|
|
699
|
-
}
|
|
700
|
-
if (type === "agent_end") {
|
|
701
|
-
appendTranscript(state, "System", "Agent turn complete.");
|
|
702
|
-
return;
|
|
703
|
-
}
|
|
704
|
-
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
705
|
-
applyMessage(state, event.message);
|
|
706
|
-
return;
|
|
707
|
-
}
|
|
708
|
-
if (type === "message_update") {
|
|
709
|
-
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
710
|
-
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
711
|
-
if (delta)
|
|
712
|
-
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
713
|
-
return;
|
|
714
|
-
}
|
|
715
|
-
if (type === "tool_execution_start") {
|
|
716
|
-
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
717
|
-
return;
|
|
718
|
-
}
|
|
719
|
-
if (type === "tool_execution_update") {
|
|
720
|
-
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
721
|
-
return;
|
|
722
|
-
}
|
|
723
|
-
if (type === "tool_execution_end") {
|
|
724
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
function firstPendingShell(state) {
|
|
728
|
-
return state.pendingShells[0];
|
|
729
|
-
}
|
|
730
|
-
function finishPendingShell(state, shell, result) {
|
|
731
|
-
const index = state.pendingShells.indexOf(shell);
|
|
732
|
-
if (index !== -1)
|
|
733
|
-
state.pendingShells.splice(index, 1);
|
|
734
|
-
shell.resolve(result);
|
|
735
|
-
}
|
|
736
|
-
function failPendingShell(state, shell, error) {
|
|
737
|
-
const index = state.pendingShells.indexOf(shell);
|
|
738
|
-
if (index !== -1)
|
|
739
|
-
state.pendingShells.splice(index, 1);
|
|
740
|
-
shell.reject(error);
|
|
741
|
-
}
|
|
742
|
-
function applyUiEvent(state, value) {
|
|
743
|
-
const event = recordOf(value);
|
|
744
|
-
if (!event)
|
|
745
|
-
return;
|
|
746
|
-
const type = String(event.type ?? "ui");
|
|
747
|
-
if (type === "shell.chunk") {
|
|
748
|
-
const pending = firstPendingShell(state);
|
|
749
|
-
const chunk = asText(event.chunk);
|
|
750
|
-
if (pending) {
|
|
751
|
-
pending.sawChunk = true;
|
|
752
|
-
pending.onData(Buffer.from(chunk));
|
|
753
|
-
} else {
|
|
754
|
-
appendTranscript(state, "Tool", chunk);
|
|
755
|
-
}
|
|
756
|
-
return;
|
|
757
|
-
}
|
|
758
|
-
if (type === "shell.end") {
|
|
759
|
-
const pending = firstPendingShell(state);
|
|
760
|
-
const output = asText(event.output ?? "");
|
|
761
|
-
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
762
|
-
if (pending) {
|
|
763
|
-
if (output && !pending.sawChunk)
|
|
764
|
-
pending.onData(Buffer.from(output));
|
|
765
|
-
finishPendingShell(state, pending, { exitCode });
|
|
766
|
-
} else {
|
|
767
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
768
|
-
}
|
|
769
|
-
return;
|
|
770
|
-
}
|
|
771
|
-
if (type === "shell.start") {
|
|
772
|
-
if (!firstPendingShell(state))
|
|
773
|
-
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
774
|
-
return;
|
|
775
|
-
}
|
|
776
|
-
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
777
|
-
}
|
|
778
|
-
function applyEnvelope(ctx, state, envelopeValue) {
|
|
779
|
-
const envelope = recordOf(envelopeValue);
|
|
780
|
-
if (!envelope)
|
|
781
|
-
return;
|
|
782
|
-
const type = String(envelope.type ?? "");
|
|
783
|
-
if (type === "ready") {
|
|
784
|
-
const metadata = recordOf(envelope.metadata);
|
|
785
|
-
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
786
|
-
state.status = "worker Pi daemon ready";
|
|
787
|
-
if (!state.nativeStream)
|
|
788
|
-
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
789
|
-
} else if (type === "status.update") {
|
|
790
|
-
applyStatus(state, envelope);
|
|
791
|
-
} else if (type === "activity.update") {
|
|
792
|
-
const activity = recordOf(envelope.activity);
|
|
793
|
-
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
794
|
-
} else if (type === "extension_ui_request") {
|
|
795
|
-
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
796
|
-
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
797
|
-
} else if (type === "pi.ui_event") {
|
|
798
|
-
applyUiEvent(state, envelope.event);
|
|
799
|
-
} else if (type === "pi.event") {
|
|
800
|
-
applyPiEvent(ctx, state, envelope.event);
|
|
801
|
-
} else if (type === "error") {
|
|
802
|
-
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
803
|
-
}
|
|
804
|
-
syncNativeDisplayCwd(ctx, state);
|
|
805
|
-
}
|
|
806
|
-
async function waitForWorkerReady(options, ctx, state) {
|
|
807
|
-
while (true) {
|
|
808
|
-
const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => ({
|
|
809
|
-
ready: false,
|
|
810
|
-
status: error instanceof Error ? error.message : String(error),
|
|
811
|
-
retryAfterMs: 1000
|
|
812
|
-
}));
|
|
813
|
-
if (session.ready === false) {
|
|
814
|
-
const status = String(session.status ?? "starting");
|
|
815
|
-
state.status = `waiting for worker Pi daemon \xB7 ${status}`;
|
|
816
|
-
updatePiUi(ctx, state);
|
|
817
|
-
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
818
|
-
appendTranscript(state, "Error", `Run ended before worker Pi daemon became ready: ${status}`);
|
|
819
|
-
return false;
|
|
820
|
-
}
|
|
821
|
-
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
822
|
-
continue;
|
|
823
|
-
}
|
|
824
|
-
const sessionRecord = recordOf(session) ?? {};
|
|
825
|
-
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
826
|
-
updatePiUi(ctx, state);
|
|
827
|
-
return true;
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
function parseWsPayload(message) {
|
|
831
|
-
if (typeof message.data === "string")
|
|
832
|
-
return JSON.parse(message.data);
|
|
833
|
-
return JSON.parse(Buffer.from(message.data).toString("utf8"));
|
|
834
|
-
}
|
|
835
|
-
async function connectWorkerStream(options, ctx, state) {
|
|
836
|
-
const ready = await waitForWorkerReady(options, ctx, state);
|
|
837
|
-
if (!ready)
|
|
838
|
-
return;
|
|
839
|
-
let catchupDone = false;
|
|
840
|
-
const buffered = [];
|
|
841
|
-
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
842
|
-
const socket = new WebSocket(wsUrl);
|
|
843
|
-
const closePromise = new Promise((resolve3) => {
|
|
844
|
-
socket.onopen = () => {
|
|
845
|
-
state.wsConnected = true;
|
|
846
|
-
state.status = "live worker Pi WebSocket connected";
|
|
847
|
-
updatePiUi(ctx, state);
|
|
848
|
-
};
|
|
849
|
-
socket.onmessage = (message) => {
|
|
850
|
-
try {
|
|
851
|
-
const payload = parseWsPayload(message);
|
|
852
|
-
if (!catchupDone)
|
|
853
|
-
buffered.push(payload);
|
|
854
|
-
else {
|
|
855
|
-
applyEnvelope(ctx, state, payload);
|
|
856
|
-
updatePiUi(ctx, state);
|
|
857
|
-
}
|
|
858
|
-
} catch (error) {
|
|
859
|
-
appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
860
|
-
updatePiUi(ctx, state);
|
|
861
|
-
}
|
|
862
|
-
};
|
|
863
|
-
socket.onerror = () => socket.close();
|
|
864
|
-
socket.onclose = () => {
|
|
865
|
-
state.wsConnected = false;
|
|
866
|
-
state.status = "worker Pi WebSocket disconnected";
|
|
867
|
-
updatePiUi(ctx, state);
|
|
868
|
-
resolve3();
|
|
869
|
-
};
|
|
870
|
-
});
|
|
871
|
-
try {
|
|
872
|
-
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
873
|
-
getRunPiMessagesViaServer(options.context, options.runId),
|
|
874
|
-
getRunPiStatusViaServer(options.context, options.runId),
|
|
875
|
-
getRunPiCommandsViaServer(options.context, options.runId)
|
|
876
|
-
]);
|
|
877
|
-
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
878
|
-
const native = nativePiUi(ctx);
|
|
879
|
-
if (state.nativeStream && native?.appendSessionMessages)
|
|
880
|
-
native.appendSessionMessages(messages);
|
|
881
|
-
else
|
|
882
|
-
for (const message of messages)
|
|
883
|
-
applyMessage(state, message);
|
|
884
|
-
applyStatus(state, statusPayload);
|
|
885
|
-
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
886
|
-
state.commands = commands.flatMap((command) => {
|
|
887
|
-
const record = recordOf(command);
|
|
888
|
-
return typeof record?.name === "string" ? [`/${record.name}`] : [];
|
|
889
|
-
});
|
|
890
|
-
catchupDone = true;
|
|
891
|
-
for (const payload of buffered.splice(0))
|
|
892
|
-
applyEnvelope(ctx, state, payload);
|
|
893
|
-
updatePiUi(ctx, state);
|
|
894
|
-
} catch (error) {
|
|
895
|
-
appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
896
|
-
catchupDone = true;
|
|
897
|
-
updatePiUi(ctx, state);
|
|
898
|
-
}
|
|
899
|
-
await closePromise;
|
|
900
|
-
}
|
|
901
|
-
function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
902
|
-
return {
|
|
903
|
-
exec(command, _cwd, execOptions) {
|
|
904
|
-
return new Promise((resolve3, reject) => {
|
|
905
|
-
const pending = {
|
|
906
|
-
command,
|
|
907
|
-
onData: execOptions.onData,
|
|
908
|
-
resolve: resolve3,
|
|
909
|
-
reject,
|
|
910
|
-
sawChunk: false
|
|
911
|
-
};
|
|
912
|
-
const cleanup = () => {
|
|
913
|
-
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
914
|
-
if (timer)
|
|
915
|
-
clearTimeout(timer);
|
|
916
|
-
};
|
|
917
|
-
const onAbort = () => {
|
|
918
|
-
cleanup();
|
|
919
|
-
failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
|
|
920
|
-
};
|
|
921
|
-
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
922
|
-
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
923
|
-
cleanup();
|
|
924
|
-
failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
925
|
-
}, timeoutMs) : null;
|
|
926
|
-
const wrappedResolve = pending.resolve;
|
|
927
|
-
const wrappedReject = pending.reject;
|
|
928
|
-
pending.resolve = (result) => {
|
|
929
|
-
cleanup();
|
|
930
|
-
wrappedResolve(result);
|
|
931
|
-
};
|
|
932
|
-
pending.reject = (error) => {
|
|
933
|
-
cleanup();
|
|
934
|
-
wrappedReject(error);
|
|
935
|
-
};
|
|
936
|
-
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
937
|
-
state.pendingShells.push(pending);
|
|
938
|
-
sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
939
|
-
cleanup();
|
|
940
|
-
failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
|
|
941
|
-
});
|
|
942
|
-
});
|
|
943
|
-
}
|
|
944
|
-
};
|
|
945
|
-
}
|
|
946
|
-
async function answerPendingUi(options, state, line) {
|
|
947
|
-
const pending = state.pendingUi;
|
|
948
|
-
if (!pending)
|
|
949
|
-
return false;
|
|
950
|
-
if (line === "/cancel") {
|
|
951
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
952
|
-
} else if (pending.method === "confirm") {
|
|
953
|
-
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
954
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
955
|
-
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
956
|
-
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
957
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
958
|
-
} else {
|
|
959
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
960
|
-
}
|
|
961
|
-
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
962
|
-
state.pendingUi = null;
|
|
963
|
-
return true;
|
|
964
|
-
}
|
|
965
|
-
async function routeInput(options, ctx, state, line) {
|
|
966
|
-
const text = line.trim();
|
|
967
|
-
if (!text)
|
|
968
|
-
return;
|
|
969
|
-
if (await answerPendingUi(options, state, text)) {
|
|
970
|
-
updatePiUi(ctx, state);
|
|
971
|
-
return;
|
|
972
|
-
}
|
|
973
|
-
if (text === "/detach" || text === "/quit" || text === "/q") {
|
|
974
|
-
appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
|
|
975
|
-
updatePiUi(ctx, state);
|
|
976
|
-
ctx.shutdown();
|
|
977
|
-
return;
|
|
978
|
-
}
|
|
979
|
-
if (text === "/stop") {
|
|
980
|
-
await abortRunPiViaServer(options.context, options.runId);
|
|
981
|
-
appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
|
|
982
|
-
updatePiUi(ctx, state);
|
|
983
|
-
ctx.shutdown();
|
|
984
|
-
return;
|
|
985
|
-
}
|
|
986
|
-
if (text.startsWith("!")) {
|
|
987
|
-
appendTranscript(state, "You", text);
|
|
988
|
-
await sendRunPiShellViaServer(options.context, options.runId, text);
|
|
989
|
-
} else if (text.startsWith("/")) {
|
|
990
|
-
appendTranscript(state, "You", text);
|
|
991
|
-
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
992
|
-
const message = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
993
|
-
appendTranscript(state, "System", message);
|
|
994
|
-
} else {
|
|
995
|
-
appendTranscript(state, "You", text);
|
|
996
|
-
await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
|
|
997
|
-
}
|
|
998
|
-
updatePiUi(ctx, state);
|
|
999
|
-
}
|
|
1000
|
-
function createRigWorkerPiBridgeExtension(options) {
|
|
1001
|
-
return (pi) => {
|
|
1002
|
-
const state = {
|
|
1003
|
-
transcript: [],
|
|
1004
|
-
status: "starting worker Pi daemon bridge",
|
|
1005
|
-
activity: "",
|
|
1006
|
-
cwd: "",
|
|
1007
|
-
model: "",
|
|
1008
|
-
commands: [],
|
|
1009
|
-
streaming: false,
|
|
1010
|
-
pendingUi: null,
|
|
1011
|
-
pendingShells: [],
|
|
1012
|
-
wsConnected: false,
|
|
1013
|
-
nativeStream: false
|
|
1014
|
-
};
|
|
1015
|
-
if (options.initialMessageSent)
|
|
1016
|
-
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
1017
|
-
let nativePiUiContextAvailable = false;
|
|
1018
|
-
pi.on("user_bash", (event) => {
|
|
1019
|
-
state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
|
|
1020
|
-
return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
|
|
1021
|
-
});
|
|
1022
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
1023
|
-
nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
|
|
1024
|
-
state.nativeStream = nativePiUiContextAvailable;
|
|
1025
|
-
updatePiUi(ctx, state);
|
|
1026
|
-
ctx.ui.notify(nativePiUiContextAvailable ? "Rig worker Pi native stream bridge loaded" : "Rig worker Pi bridge extension loaded (degraded widget fallback)", "info");
|
|
1027
|
-
ctx.ui.onTerminalInput((data) => {
|
|
1028
|
-
if (data.includes("\x04")) {
|
|
1029
|
-
ctx.shutdown();
|
|
1030
|
-
return { consume: true };
|
|
1031
|
-
}
|
|
1032
|
-
if (!data.includes("\r") && !data.includes(`
|
|
1033
|
-
`))
|
|
1034
|
-
return;
|
|
1035
|
-
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
1036
|
-
const editorText = ctx.ui.getEditorText().trim();
|
|
1037
|
-
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
1038
|
-
if (!text)
|
|
1039
|
-
return;
|
|
1040
|
-
if (text.startsWith("!"))
|
|
1041
|
-
return;
|
|
1042
|
-
ctx.ui.setEditorText("");
|
|
1043
|
-
routeInput(options, ctx, state, text).catch((error) => {
|
|
1044
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1045
|
-
updatePiUi(ctx, state);
|
|
1046
|
-
});
|
|
1047
|
-
return { consume: true };
|
|
1048
|
-
});
|
|
1049
|
-
connectWorkerStream(options, ctx, state).catch((error) => {
|
|
1050
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1051
|
-
updatePiUi(ctx, state);
|
|
1052
|
-
});
|
|
1053
|
-
});
|
|
1054
|
-
pi.on("session_shutdown", () => {});
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
// packages/cli/src/commands/_pi-frontend.ts
|
|
1059
|
-
function setTemporaryEnv(updates) {
|
|
1060
|
-
const previous = new Map;
|
|
1061
|
-
for (const [key, value] of Object.entries(updates)) {
|
|
1062
|
-
previous.set(key, process.env[key]);
|
|
1063
|
-
process.env[key] = value;
|
|
1064
|
-
}
|
|
1065
|
-
return () => {
|
|
1066
|
-
for (const [key, value] of previous) {
|
|
1067
|
-
if (value === undefined)
|
|
1068
|
-
delete process.env[key];
|
|
1069
|
-
else
|
|
1070
|
-
process.env[key] = value;
|
|
1071
|
-
}
|
|
1072
|
-
};
|
|
1073
|
-
}
|
|
1074
|
-
async function attachRunBundledPiFrontend(context, input) {
|
|
1075
|
-
const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
|
|
1076
|
-
const cwd = join(tempRoot, "workspace");
|
|
1077
|
-
const agentDir = join(tempRoot, "agent");
|
|
1078
|
-
const sessionDir = join(tempRoot, "sessions");
|
|
1079
|
-
const previousCwd = process.cwd();
|
|
1080
|
-
const restoreEnv = setTemporaryEnv({
|
|
1081
|
-
PI_CODING_AGENT_DIR: agentDir,
|
|
1082
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
1083
|
-
PI_OFFLINE: "1",
|
|
1084
|
-
PI_SKIP_VERSION_CHECK: "1"
|
|
1085
|
-
});
|
|
1086
|
-
let detached = false;
|
|
1087
|
-
try {
|
|
1088
|
-
await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
|
|
1089
|
-
process.chdir(cwd);
|
|
1090
|
-
await runPiMain([
|
|
1091
|
-
"--offline",
|
|
1092
|
-
"--no-session",
|
|
1093
|
-
"--no-tools",
|
|
1094
|
-
"--no-builtin-tools",
|
|
1095
|
-
"--no-skills",
|
|
1096
|
-
"--no-prompt-templates",
|
|
1097
|
-
"--no-themes",
|
|
1098
|
-
"--no-context-files",
|
|
1099
|
-
"--no-approve"
|
|
1100
|
-
], {
|
|
1101
|
-
extensionFactories: [
|
|
1102
|
-
createRigWorkerPiBridgeExtension({
|
|
1103
|
-
context,
|
|
1104
|
-
runId: input.runId,
|
|
1105
|
-
initialMessageSent: input.steered === true
|
|
1106
|
-
})
|
|
1107
|
-
]
|
|
1108
|
-
});
|
|
1109
|
-
detached = true;
|
|
1110
|
-
} finally {
|
|
1111
|
-
process.chdir(previousCwd);
|
|
1112
|
-
restoreEnv();
|
|
1113
|
-
rmSync(tempRoot, { recursive: true, force: true });
|
|
1114
|
-
}
|
|
1115
|
-
let run = { runId: input.runId, status: "unknown" };
|
|
1116
|
-
try {
|
|
1117
|
-
run = await getRunDetailsViaServer(context, input.runId);
|
|
1118
|
-
} catch {}
|
|
1119
|
-
return {
|
|
1120
|
-
run,
|
|
1121
|
-
logs: [],
|
|
1122
|
-
timeline: [],
|
|
1123
|
-
timelineCursor: null,
|
|
1124
|
-
steered: input.steered === true,
|
|
1125
|
-
detached,
|
|
1126
|
-
rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
|
|
1127
|
-
};
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
// packages/cli/src/commands/_operator-view.ts
|
|
1131
|
-
var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
1132
|
-
function runStatusFromPayload(payload) {
|
|
1133
|
-
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
1134
|
-
return String(run.status ?? "unknown").toLowerCase();
|
|
1135
|
-
}
|
|
1136
|
-
async function applyOperatorCommand(context, input, deps = {}) {
|
|
1137
|
-
const line = input.line.trim();
|
|
1138
|
-
if (!line)
|
|
1139
|
-
return { action: "ignored" };
|
|
1140
|
-
if (line === "/detach" || line === "/quit" || line === "/q") {
|
|
1141
|
-
return { action: "detach", message: "Detached from run." };
|
|
1142
|
-
}
|
|
1143
|
-
if (line === "/stop") {
|
|
1144
|
-
await (deps.stop ?? stopRunViaServer)(context, input.runId);
|
|
1145
|
-
return { action: "stopped", message: "Stop requested." };
|
|
1146
|
-
}
|
|
1147
|
-
const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
|
|
1148
|
-
if (!userMessage)
|
|
1149
|
-
return { action: "ignored" };
|
|
1150
|
-
await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
|
|
1151
|
-
return { action: "continue", message: "Steering message queued." };
|
|
1152
|
-
}
|
|
1153
|
-
async function readOperatorSnapshot(context, runId, options = {}) {
|
|
1154
|
-
const run = await getRunDetailsViaServer(context, runId);
|
|
1155
|
-
const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
|
|
1156
|
-
const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
|
|
1157
|
-
entries: [{
|
|
1158
|
-
id: `timeline-unavailable:${runId}`,
|
|
1159
|
-
type: "timeline_warning",
|
|
1160
|
-
detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
|
|
1161
|
-
createdAt: new Date().toISOString()
|
|
1162
|
-
}],
|
|
1163
|
-
nextCursor: options.timelineCursor ?? null
|
|
1164
|
-
}));
|
|
1165
|
-
const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
|
|
1166
|
-
const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1167
|
-
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
1168
|
-
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
1169
|
-
}
|
|
1170
|
-
async function attachRunOperatorView(context, input) {
|
|
1171
|
-
let steered = false;
|
|
1172
|
-
if (input.message?.trim()) {
|
|
1173
|
-
await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
|
|
1174
|
-
steered = true;
|
|
1175
|
-
}
|
|
1176
|
-
if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
1177
|
-
return attachRunBundledPiFrontend(context, {
|
|
1178
|
-
runId: input.runId,
|
|
1179
|
-
steered
|
|
1180
|
-
});
|
|
1181
|
-
}
|
|
1182
|
-
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
1183
|
-
let snapshot = await readOperatorSnapshot(context, input.runId);
|
|
1184
|
-
if (context.outputMode === "text") {
|
|
1185
|
-
surface.renderSnapshot(snapshot);
|
|
1186
|
-
surface.renderTimeline(snapshot.timeline);
|
|
1187
|
-
surface.renderLogs(snapshot.logs);
|
|
1188
|
-
if (steered)
|
|
1189
|
-
surface.info("Message submitted to worker Pi.");
|
|
1190
|
-
}
|
|
1191
|
-
let detached = false;
|
|
1192
|
-
let commandInput = null;
|
|
1193
|
-
if (input.follow && !input.once && context.outputMode === "text") {
|
|
1194
|
-
if (input.interactive !== false && process.stdin.isTTY) {
|
|
1195
|
-
surface.info("Controls: /user <message>, /stop, /detach");
|
|
1196
|
-
commandInput = surface.attachCommandInput(async (line) => {
|
|
1197
|
-
const result = await applyOperatorCommand(context, { runId: input.runId, line });
|
|
1198
|
-
if (result.message)
|
|
1199
|
-
surface.info(result.message);
|
|
1200
|
-
if (result.action === "detach" || result.action === "stopped") {
|
|
1201
|
-
detached = true;
|
|
1202
|
-
commandInput?.close();
|
|
1203
|
-
}
|
|
1204
|
-
});
|
|
1205
|
-
}
|
|
1206
|
-
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
1207
|
-
let timelineCursor = snapshot.timelineCursor;
|
|
1208
|
-
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
1209
|
-
await Bun.sleep(pollMs);
|
|
1210
|
-
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
1211
|
-
timelineCursor = snapshot.timelineCursor;
|
|
1212
|
-
surface.renderSnapshot(snapshot);
|
|
1213
|
-
surface.renderTimeline(snapshot.timeline);
|
|
1214
|
-
surface.renderLogs(snapshot.logs);
|
|
1215
|
-
}
|
|
1216
|
-
commandInput?.close();
|
|
1217
|
-
}
|
|
1218
|
-
return { ...snapshot, steered, detached };
|
|
1219
|
-
}
|
|
1220
|
-
|
|
1221
|
-
// packages/cli/src/commands/_cli-format.ts
|
|
1222
|
-
import { log, note } from "@clack/prompts";
|
|
1223
|
-
import pc from "picocolors";
|
|
1224
|
-
function stringField(record, key, fallback = "") {
|
|
1225
|
-
const value = record[key];
|
|
1226
|
-
return typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
1227
|
-
}
|
|
1228
|
-
function rawObject(record) {
|
|
1229
|
-
const raw = record.raw;
|
|
1230
|
-
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
1231
|
-
}
|
|
1232
|
-
function truncate(value, width) {
|
|
1233
|
-
if (value.length <= width)
|
|
1234
|
-
return value;
|
|
1235
|
-
if (width <= 1)
|
|
1236
|
-
return "\u2026";
|
|
1237
|
-
return `${value.slice(0, width - 1)}\u2026`;
|
|
1238
|
-
}
|
|
1239
|
-
function pad(value, width) {
|
|
1240
|
-
return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
|
|
1241
|
-
}
|
|
1242
|
-
function statusColor(status) {
|
|
1243
|
-
const normalized = status.toLowerCase();
|
|
1244
|
-
if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved"].includes(normalized))
|
|
1245
|
-
return pc.green;
|
|
1246
|
-
if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
|
|
1247
|
-
return pc.red;
|
|
1248
|
-
if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
|
|
1249
|
-
return pc.cyan;
|
|
1250
|
-
if (["ready", "open", "queued", "created", "preparing", "local", "pending"].includes(normalized))
|
|
1251
|
-
return pc.yellow;
|
|
1252
|
-
return pc.dim;
|
|
1253
|
-
}
|
|
1254
|
-
function compactDate(value) {
|
|
1255
|
-
if (!value.trim())
|
|
1256
|
-
return "";
|
|
1257
|
-
const parsed = Date.parse(value);
|
|
1258
|
-
if (!Number.isFinite(parsed))
|
|
1259
|
-
return value;
|
|
1260
|
-
return new Date(parsed).toISOString().replace("T", " ").replace(/\.\d{3}Z$/, "Z");
|
|
1261
|
-
}
|
|
1262
|
-
function firstString(record, keys, fallback = "") {
|
|
1263
|
-
for (const key of keys) {
|
|
1264
|
-
const value = stringField(record, key);
|
|
1265
|
-
if (value)
|
|
1266
|
-
return value;
|
|
1267
|
-
}
|
|
1268
|
-
return fallback;
|
|
1269
|
-
}
|
|
1270
|
-
function runIdOf(run) {
|
|
1271
|
-
return firstString(run, ["runId", "id"], "(unknown-run)");
|
|
1272
|
-
}
|
|
1273
|
-
function taskIdOf(run) {
|
|
1274
|
-
return firstString(run, ["taskId", "task", "task_id"]);
|
|
1275
|
-
}
|
|
1276
|
-
function runTitleOf(run) {
|
|
1277
|
-
return firstString(run, ["title", "summary", "name"], taskIdOf(run) || "(untitled)");
|
|
1278
|
-
}
|
|
1279
|
-
function shouldUseClackOutput() {
|
|
1280
|
-
return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
|
|
1281
|
-
}
|
|
1282
|
-
function printFormattedOutput(message, options = {}) {
|
|
1283
|
-
if (!shouldUseClackOutput()) {
|
|
1284
|
-
console.log(message);
|
|
1285
|
-
return;
|
|
1286
|
-
}
|
|
1287
|
-
if (options.title)
|
|
1288
|
-
note(message, options.title);
|
|
1289
|
-
else
|
|
1290
|
-
log.message(message);
|
|
1291
|
-
}
|
|
1292
|
-
function formatStatusPill(status) {
|
|
1293
|
-
const label = status || "unknown";
|
|
1294
|
-
return statusColor(label)(`\u25CF ${label}`);
|
|
1295
|
-
}
|
|
1296
|
-
function formatSection(title, subtitle) {
|
|
1297
|
-
return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
|
|
1298
|
-
}
|
|
1299
|
-
function formatSuccessCard(title, rows = []) {
|
|
1300
|
-
const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${pc.dim("\u2502")} ${pc.dim(key.padEnd(12))} ${value}`);
|
|
1301
|
-
return [formatSection(title), ...body].join(`
|
|
1302
|
-
`);
|
|
1303
|
-
}
|
|
1304
|
-
function formatNextSteps(steps) {
|
|
1305
|
-
if (steps.length === 0)
|
|
1306
|
-
return [];
|
|
1307
|
-
return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
|
|
1308
|
-
}
|
|
1309
|
-
function formatRunList(runs, options = {}) {
|
|
1310
|
-
if (runs.length === 0) {
|
|
1311
|
-
return [
|
|
1312
|
-
formatSection("Runs", "none recorded"),
|
|
1313
|
-
options.source === "server" ? pc.dim("No runs recorded on the selected Rig server.") : pc.dim("No runs recorded in .rig/runs."),
|
|
1314
|
-
"",
|
|
1315
|
-
...formatNextSteps(["Start one: `rig task run --next`", "Check server: `rig server status`"])
|
|
1316
|
-
].join(`
|
|
1317
|
-
`);
|
|
1318
|
-
}
|
|
1319
|
-
const rows = runs.map((run) => {
|
|
1320
|
-
const runId = stringField(run, "runId", stringField(run, "id", "(unknown-run)"));
|
|
1321
|
-
const status = stringField(run, "status", "unknown");
|
|
1322
|
-
const taskId = stringField(run, "taskId", "");
|
|
1323
|
-
const title = stringField(run, "title", taskId || "(untitled)");
|
|
1324
|
-
const runtime = stringField(run, "runtimeAdapter", "");
|
|
1325
|
-
return { runId, status, title, runtime };
|
|
1326
|
-
});
|
|
1327
|
-
const idWidth = Math.min(36, Math.max(6, ...rows.map((row) => row.runId.length)));
|
|
1328
|
-
const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
|
|
1329
|
-
const header = `${pc.bold(pad("RUN", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
|
|
1330
|
-
const body = rows.map((row) => [
|
|
1331
|
-
pc.bold(pad(truncate(row.runId, idWidth), idWidth)),
|
|
1332
|
-
statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
|
|
1333
|
-
`${row.title}${row.runtime ? pc.dim(` ${row.runtime}`) : ""}`
|
|
1334
|
-
].join(" "));
|
|
1335
|
-
return [formatSection("Runs", options.source === "server" ? "selected server" : "local state"), header, ...body, "", ...formatNextSteps(["Follow live: `rig run attach <run-id> --follow`", "Details: `rig run show <run-id>`"])].join(`
|
|
1336
|
-
`);
|
|
1337
|
-
}
|
|
1338
|
-
function formatRunCard(run, options = {}) {
|
|
1339
|
-
const raw = rawObject(run);
|
|
1340
|
-
const merged = { ...raw, ...run };
|
|
1341
|
-
const runId = runIdOf(merged);
|
|
1342
|
-
const status = firstString(merged, ["status"], "unknown");
|
|
1343
|
-
const taskId = taskIdOf(merged);
|
|
1344
|
-
const title = runTitleOf(merged);
|
|
1345
|
-
const runtime = firstString(merged, ["runtimeAdapter", "runtime", "adapter"]);
|
|
1346
|
-
const mode = firstString(merged, ["runtimeMode", "mode"]);
|
|
1347
|
-
const interaction = firstString(merged, ["interactionMode"]);
|
|
1348
|
-
const created = compactDate(firstString(merged, ["createdAt"]));
|
|
1349
|
-
const started = compactDate(firstString(merged, ["startedAt"]));
|
|
1350
|
-
const updated = compactDate(firstString(merged, ["updatedAt"]));
|
|
1351
|
-
const completed = compactDate(firstString(merged, ["completedAt", "finishedAt"]));
|
|
1352
|
-
const worktree = firstString(merged, ["worktreePath", "cwd", "projectRoot"]);
|
|
1353
|
-
const piSession = merged.piSession && typeof merged.piSession === "object" && !Array.isArray(merged.piSession) ? firstString(merged.piSession, ["sessionId", "id"]) : "";
|
|
1354
|
-
const timeline = Array.isArray(merged.timeline) ? merged.timeline.length : null;
|
|
1355
|
-
const approvals = Array.isArray(merged.approvals) ? merged.approvals.length : null;
|
|
1356
|
-
const inputs = Array.isArray(merged.userInputs) ? merged.userInputs.length : null;
|
|
1357
|
-
const rows = [
|
|
1358
|
-
["run", pc.bold(runId)],
|
|
1359
|
-
["status", formatStatusPill(status)],
|
|
1360
|
-
["task", taskId],
|
|
1361
|
-
["title", title],
|
|
1362
|
-
["runtime", [runtime, mode, interaction].filter(Boolean).join(" \xB7 ")],
|
|
1363
|
-
["created", created],
|
|
1364
|
-
["started", started],
|
|
1365
|
-
["updated", updated],
|
|
1366
|
-
["completed", completed],
|
|
1367
|
-
["worktree", worktree],
|
|
1368
|
-
["pi", piSession],
|
|
1369
|
-
["timeline", timeline],
|
|
1370
|
-
["approvals", approvals],
|
|
1371
|
-
["inputs", inputs]
|
|
1372
|
-
];
|
|
1373
|
-
return [
|
|
1374
|
-
formatSuccessCard(options.title ?? "Run details", rows),
|
|
1375
|
-
"",
|
|
1376
|
-
...formatNextSteps([`Follow live: \`rig run attach ${runId} --follow\``, `Raw payload: \`rig run show ${runId} --raw\``])
|
|
1377
|
-
].join(`
|
|
1378
|
-
`);
|
|
1379
|
-
}
|
|
1380
|
-
function formatRunStatus(summary, options = {}) {
|
|
1381
|
-
const activeRuns = summary.activeRuns ?? [];
|
|
1382
|
-
const recentRuns = summary.recentRuns ?? [];
|
|
1383
|
-
const lines = [formatSection("Run status", options.source === "server" ? "selected server" : "local state")];
|
|
1384
|
-
lines.push("", pc.bold(`Active runs (${activeRuns.length})`));
|
|
1385
|
-
if (activeRuns.length === 0) {
|
|
1386
|
-
lines.push(pc.dim("No active runs."));
|
|
1387
|
-
} else {
|
|
1388
|
-
for (const run of activeRuns) {
|
|
1389
|
-
lines.push(formatRunSummaryLine(run));
|
|
1390
|
-
}
|
|
1391
|
-
}
|
|
1392
|
-
lines.push("", pc.bold(`Recent runs (${recentRuns.length})`));
|
|
1393
|
-
if (recentRuns.length === 0) {
|
|
1394
|
-
lines.push(pc.dim("No recent terminal runs."));
|
|
1395
|
-
} else {
|
|
1396
|
-
for (const run of recentRuns.slice(0, 10)) {
|
|
1397
|
-
lines.push(formatRunSummaryLine(run));
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
lines.push("", ...formatNextSteps(["Start work: `rig task run --next`", "Attach: `rig run attach <run-id> --follow`", "Details: `rig run show <run-id>`"]));
|
|
1401
|
-
return lines.join(`
|
|
1402
|
-
`);
|
|
1403
|
-
}
|
|
1404
|
-
function formatRunSummaryLine(run) {
|
|
1405
|
-
const record = run;
|
|
1406
|
-
const runId = runIdOf(record);
|
|
1407
|
-
const status = firstString(record, ["status"], "unknown");
|
|
1408
|
-
const taskId = taskIdOf(record);
|
|
1409
|
-
const title = runTitleOf(record);
|
|
1410
|
-
const runtime = firstString(record, ["runtimeAdapter", "runtime", "adapter"]);
|
|
1411
|
-
const descriptor = [taskId, title].filter(Boolean).join(" \xB7 ");
|
|
1412
|
-
return `${pc.dim("\u2502")} ${pc.bold(runId)} ${formatStatusPill(status)} ${descriptor}${runtime ? pc.dim(` ${runtime}`) : ""}`;
|
|
1413
|
-
}
|
|
1414
|
-
|
|
1415
|
-
// packages/cli/src/commands/run.ts
|
|
1416
|
-
function normalizeRemoteRunDetails(payload) {
|
|
1417
|
-
const run = payload.run;
|
|
1418
|
-
if (!run || typeof run !== "object" || Array.isArray(run))
|
|
1419
|
-
return null;
|
|
1420
|
-
return {
|
|
1421
|
-
...run,
|
|
1422
|
-
...Array.isArray(payload.timeline) ? { timeline: payload.timeline } : {},
|
|
1423
|
-
...Array.isArray(payload.approvals) ? { approvals: payload.approvals } : {},
|
|
1424
|
-
...Array.isArray(payload.userInputs) ? { userInputs: payload.userInputs } : {}
|
|
1425
|
-
};
|
|
1426
|
-
}
|
|
1427
|
-
var REMOTE_TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged"]);
|
|
1428
|
-
function isRemoteConnectionSelected(projectRoot) {
|
|
1429
|
-
return resolveSelectedConnection(projectRoot)?.connection.kind === "remote";
|
|
1430
|
-
}
|
|
1431
|
-
async function listRunsForSelectedConnection(context, options = {}) {
|
|
1432
|
-
if (isRemoteConnectionSelected(context.projectRoot)) {
|
|
1433
|
-
return { runs: await listRunsViaServer(context, options), source: "server" };
|
|
1434
|
-
}
|
|
1435
|
-
return { runs: listAuthorityRuns(context.projectRoot), source: "local" };
|
|
1436
|
-
}
|
|
1437
|
-
function runStringField(run, key, fallback = "") {
|
|
1438
|
-
const value = run[key];
|
|
1439
|
-
return typeof value === "string" && value.trim() ? value : fallback;
|
|
1440
|
-
}
|
|
1441
|
-
function buildServerRunStatus(runs) {
|
|
1442
|
-
const activeRuns = runs.filter((run) => !REMOTE_TERMINAL_RUN_STATUSES.has(runStringField(run, "status").toLowerCase()));
|
|
1443
|
-
const recentRuns = runs.filter((run) => REMOTE_TERMINAL_RUN_STATUSES.has(runStringField(run, "status").toLowerCase()));
|
|
1444
|
-
return { activeRuns, recentRuns, runs };
|
|
1445
|
-
}
|
|
1446
|
-
function shouldPromptForEpicSelection(context, command, promptEpic, noEpicPrompt) {
|
|
1447
|
-
if (noEpicPrompt) {
|
|
1448
|
-
return false;
|
|
1449
|
-
}
|
|
1450
|
-
if (promptEpic) {
|
|
1451
|
-
return true;
|
|
1452
|
-
}
|
|
1453
|
-
if (command !== "start-serial") {
|
|
1454
|
-
return false;
|
|
1455
|
-
}
|
|
1456
|
-
return context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY;
|
|
1457
|
-
}
|
|
1458
|
-
async function promptForEpicSelection(projectRoot, command) {
|
|
1459
|
-
const epics = listOpenEpics(projectRoot);
|
|
1460
|
-
const defaultEpic = await resolveDefaultEpic(projectRoot);
|
|
1461
|
-
const options = epics.map((epic) => epic.id);
|
|
1462
|
-
if (defaultEpic && !options.includes(defaultEpic)) {
|
|
1463
|
-
options.unshift(defaultEpic);
|
|
1464
|
-
}
|
|
1465
|
-
if (options.length === 0) {
|
|
1466
|
-
throw new CliError2("No open epic found. Pass --epic <id>.");
|
|
1467
|
-
}
|
|
1468
|
-
console.log(`Select epic for run ${command}:`);
|
|
1469
|
-
options.forEach((id, index) => {
|
|
1470
|
-
const metadata = epics.find((epic) => epic.id === id);
|
|
1471
|
-
const details = [
|
|
1472
|
-
metadata?.priority !== undefined ? `priority:${metadata.priority}` : "",
|
|
1473
|
-
metadata?.createdAt ? `created:${metadata.createdAt.slice(0, 10)}` : "",
|
|
1474
|
-
id === defaultEpic ? "default" : ""
|
|
1475
|
-
].filter(Boolean).join(" ");
|
|
1476
|
-
const suffix = details ? ` (${details})` : "";
|
|
1477
|
-
console.log(` ${index + 1}. ${id}${suffix}`);
|
|
1478
|
-
});
|
|
1479
|
-
const fallback = defaultEpic || options[0];
|
|
1480
|
-
const rl = createInterface2({ input: process.stdin, output: process.stdout });
|
|
1481
|
-
try {
|
|
1482
|
-
while (true) {
|
|
1483
|
-
const answer = (await rl.question(`Epic [1-${options.length}] or id (Enter for ${fallback}, q to cancel): `)).trim();
|
|
1484
|
-
if (!answer) {
|
|
1485
|
-
return fallback ?? options[0];
|
|
1486
|
-
}
|
|
1487
|
-
if (answer === "q" || answer === "quit") {
|
|
1488
|
-
throw new CliError2("Run cancelled by user.");
|
|
1489
|
-
}
|
|
1490
|
-
if (/^\d+$/.test(answer)) {
|
|
1491
|
-
const index = Number.parseInt(answer, 10) - 1;
|
|
1492
|
-
if (index >= 0 && index < options.length) {
|
|
1493
|
-
return options[index];
|
|
1494
|
-
}
|
|
1495
|
-
}
|
|
1496
|
-
if (options.includes(answer)) {
|
|
1497
|
-
return answer;
|
|
1498
|
-
}
|
|
1499
|
-
console.log("Invalid selection. Choose a listed number, exact epic id, or q to cancel.");
|
|
1500
|
-
}
|
|
1501
|
-
} finally {
|
|
1502
|
-
rl.close();
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
async function executeRun(context, args) {
|
|
1506
|
-
const [command = "status", ...rest] = args;
|
|
1507
|
-
const runtimeContext = loadRuntimeContextFromEnv2() ?? undefined;
|
|
1508
|
-
switch (command) {
|
|
1509
|
-
case "list": {
|
|
1510
|
-
requireNoExtraArgs(rest, "rig run list");
|
|
1511
|
-
const { runs, source } = await listRunsForSelectedConnection(context, { limit: 100 });
|
|
1512
|
-
if (context.outputMode === "text") {
|
|
1513
|
-
printFormattedOutput(formatRunList(runs, { source }));
|
|
1514
|
-
}
|
|
1515
|
-
return { ok: true, group: "run", command, details: { runs, source } };
|
|
1516
|
-
}
|
|
1517
|
-
case "delete": {
|
|
1518
|
-
let pending = rest;
|
|
1519
|
-
const run = takeOption(pending, "--run");
|
|
1520
|
-
pending = run.rest;
|
|
1521
|
-
const purgeArtifacts = takeFlag(pending, "--purge-artifacts");
|
|
1522
|
-
pending = purgeArtifacts.rest;
|
|
1523
|
-
requireNoExtraArgs(pending, "rig run delete --run <id> [--purge-artifacts]");
|
|
1524
|
-
if (!run.value) {
|
|
1525
|
-
throw new CliError2("run delete requires --run <id>.");
|
|
1526
|
-
}
|
|
1527
|
-
const result = await deleteRunState(context.projectRoot, {
|
|
1528
|
-
runId: run.value,
|
|
1529
|
-
purgeRuntime: true,
|
|
1530
|
-
purgeTaskArtifacts: purgeArtifacts.value
|
|
1531
|
-
});
|
|
1532
|
-
if (context.outputMode === "text") {
|
|
1533
|
-
console.log(`Deleted run ${result.runId}`);
|
|
1534
|
-
if (result.runtimeIds.length > 0) {
|
|
1535
|
-
console.log(`Cleaned runtimes: ${result.runtimeIds.join(", ")}`);
|
|
1536
|
-
}
|
|
1537
|
-
if (result.taskArtifactsDeleted) {
|
|
1538
|
-
console.log(`Cleared task artifacts for ${result.taskId}`);
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
return { ok: true, group: "run", command, details: result };
|
|
1542
|
-
}
|
|
1543
|
-
case "cleanup": {
|
|
1544
|
-
let pending = rest;
|
|
1545
|
-
const all = takeFlag(pending, "--all");
|
|
1546
|
-
pending = all.rest;
|
|
1547
|
-
const keepArtifacts = takeFlag(pending, "--keep-artifacts");
|
|
1548
|
-
pending = keepArtifacts.rest;
|
|
1549
|
-
const keepRuntimes = takeFlag(pending, "--keep-runtimes");
|
|
1550
|
-
pending = keepRuntimes.rest;
|
|
1551
|
-
const keepQueue = takeFlag(pending, "--keep-queue");
|
|
1552
|
-
pending = keepQueue.rest;
|
|
1553
|
-
requireNoExtraArgs(pending, "rig run cleanup --all [--keep-artifacts] [--keep-runtimes] [--keep-queue]");
|
|
1554
|
-
if (!all.value) {
|
|
1555
|
-
throw new CliError2("run cleanup currently requires --all.");
|
|
1556
|
-
}
|
|
1557
|
-
const result = await cleanupRunState(context.projectRoot, {
|
|
1558
|
-
includeArtifacts: !keepArtifacts.value,
|
|
1559
|
-
includeRuntimes: !keepRuntimes.value,
|
|
1560
|
-
includeQueue: !keepQueue.value
|
|
1561
|
-
});
|
|
1562
|
-
if (context.outputMode === "text") {
|
|
1563
|
-
console.log(`Deleted runs: ${result.runIds.length}`);
|
|
1564
|
-
console.log(`Cleaned runtimes: ${result.runtimeIds.length}`);
|
|
1565
|
-
console.log(`Artifacts cleared: ${result.artifactsCleared ? "yes" : "no"}`);
|
|
1566
|
-
console.log(`Queue cleared: ${result.queueCleared ? "yes" : "no"}`);
|
|
1567
|
-
}
|
|
1568
|
-
return { ok: true, group: "run", command, details: result };
|
|
1569
|
-
}
|
|
1570
|
-
case "show": {
|
|
1571
|
-
let pending = rest;
|
|
1572
|
-
const rawResult = takeFlag(pending, "--raw");
|
|
1573
|
-
pending = rawResult.rest;
|
|
1574
|
-
const run = takeOption(pending, "--run");
|
|
1575
|
-
pending = run.rest;
|
|
1576
|
-
const positionalRunId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? pending[0] : undefined;
|
|
1577
|
-
const extra = positionalRunId ? pending.slice(1) : pending;
|
|
1578
|
-
requireNoExtraArgs(extra, "rig run show <id>|--run <id> [--raw]");
|
|
1579
|
-
const runId = run.value ?? positionalRunId;
|
|
1580
|
-
if (!runId) {
|
|
1581
|
-
throw new CliError2("run show requires a run id.");
|
|
1582
|
-
}
|
|
1583
|
-
const record = readAuthorityRun(context.projectRoot, runId) ?? normalizeRemoteRunDetails(await getRunDetailsViaServer(context, runId).catch(() => ({})));
|
|
1584
|
-
if (!record) {
|
|
1585
|
-
throw new CliError2(`Run not found: ${runId}`, 2);
|
|
1586
|
-
}
|
|
1587
|
-
if (context.outputMode === "text") {
|
|
1588
|
-
printFormattedOutput(rawResult.value ? JSON.stringify(record, null, 2) : formatRunCard(record));
|
|
1589
|
-
}
|
|
1590
|
-
return { ok: true, group: "run", command, details: { ...record, rawOutput: rawResult.value } };
|
|
1591
|
-
}
|
|
1592
|
-
case "timeline": {
|
|
1593
|
-
let pending = rest;
|
|
1594
|
-
const run = takeOption(pending, "--run");
|
|
1595
|
-
pending = run.rest;
|
|
1596
|
-
const follow = takeFlag(pending, "--follow");
|
|
1597
|
-
pending = follow.rest;
|
|
1598
|
-
requireNoExtraArgs(pending, "rig run timeline --run <id> [--follow]");
|
|
1599
|
-
if (!run.value) {
|
|
1600
|
-
throw new CliError2("run timeline requires --run <id>.");
|
|
1601
|
-
}
|
|
1602
|
-
const renderer = createPiRunStreamRenderer();
|
|
1603
|
-
let cursor = null;
|
|
1604
|
-
const page = await getRunTimelineViaServer(context, run.value, { limit: 500 });
|
|
1605
|
-
const events = Array.isArray(page.entries) ? page.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1606
|
-
cursor = typeof page.nextCursor === "string" ? page.nextCursor : null;
|
|
1607
|
-
if (context.outputMode === "text") {
|
|
1608
|
-
renderer.renderTimeline(events);
|
|
1609
|
-
}
|
|
1610
|
-
if (follow.value && context.outputMode === "text") {
|
|
1611
|
-
while (true) {
|
|
1612
|
-
await Bun.sleep(1000);
|
|
1613
|
-
const nextPage = await getRunTimelineViaServer(context, run.value, { limit: 500, ...cursor ? { cursor } : {} });
|
|
1614
|
-
const nextEvents = Array.isArray(nextPage.entries) ? nextPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1615
|
-
cursor = typeof nextPage.nextCursor === "string" ? nextPage.nextCursor : cursor;
|
|
1616
|
-
renderer.renderTimeline(nextEvents);
|
|
1617
|
-
}
|
|
1618
|
-
}
|
|
1619
|
-
return { ok: true, group: "run", command, details: { runId: run.value, events, cursor } };
|
|
1620
|
-
}
|
|
1621
|
-
case "attach": {
|
|
1622
|
-
let pending = rest;
|
|
1623
|
-
const runOption = takeOption(pending, "--run");
|
|
1624
|
-
pending = runOption.rest;
|
|
1625
|
-
const messageOption = takeOption(pending, "--message");
|
|
1626
|
-
pending = messageOption.rest;
|
|
1627
|
-
const once = takeFlag(pending, "--once");
|
|
1628
|
-
pending = once.rest;
|
|
1629
|
-
const follow = takeFlag(pending, "--follow");
|
|
1630
|
-
pending = follow.rest;
|
|
1631
|
-
const pollMs = takeOption(pending, "--poll-ms");
|
|
1632
|
-
pending = pollMs.rest;
|
|
1633
|
-
const positionalRunId = pending.length > 0 ? pending[0] : undefined;
|
|
1634
|
-
const extra = positionalRunId ? pending.slice(1) : pending;
|
|
1635
|
-
requireNoExtraArgs(extra, "rig run attach <run-id>|--run <run-id> [--message <text>] [--once|--follow] [--poll-ms <ms>]");
|
|
1636
|
-
const runId = runOption.value ?? positionalRunId;
|
|
1637
|
-
if (!runId) {
|
|
1638
|
-
throw new CliError2("run attach requires a run id.", 2);
|
|
1639
|
-
}
|
|
1640
|
-
let steered = false;
|
|
1641
|
-
if (messageOption.value?.trim()) {
|
|
1642
|
-
await steerRunViaServer(context, runId, messageOption.value.trim());
|
|
1643
|
-
steered = true;
|
|
1644
|
-
}
|
|
1645
|
-
const attached = await attachRunOperatorView(context, {
|
|
1646
|
-
runId,
|
|
1647
|
-
message: null,
|
|
1648
|
-
once: once.value,
|
|
1649
|
-
follow: follow.value,
|
|
1650
|
-
pollMs: parsePositiveInt(pollMs.value, "--poll-ms", 2000)
|
|
1651
|
-
});
|
|
1652
|
-
return { ok: true, group: "run", command, details: { ...attached, steered: attached.steered || steered } };
|
|
1653
|
-
}
|
|
1654
|
-
case "status": {
|
|
1655
|
-
requireNoExtraArgs(rest, "rig run status");
|
|
1656
|
-
if (context.dryRun) {
|
|
1657
|
-
if (context.outputMode === "text") {
|
|
1658
|
-
console.log("[dry-run] rig run status");
|
|
1659
|
-
}
|
|
1660
|
-
return { ok: true, group: "run", command };
|
|
1661
|
-
}
|
|
1662
|
-
const summary = isRemoteConnectionSelected(context.projectRoot) ? buildServerRunStatus(await listRunsViaServer(context, { limit: 100 })) : runStatus(context.projectRoot, runtimeContext);
|
|
1663
|
-
const activeRuns = Array.isArray(summary.activeRuns) ? summary.activeRuns.filter((run) => Boolean(run && typeof run === "object" && !Array.isArray(run))) : [];
|
|
1664
|
-
const recentRuns = Array.isArray(summary.recentRuns) ? summary.recentRuns.filter((run) => Boolean(run && typeof run === "object" && !Array.isArray(run))) : [];
|
|
1665
|
-
if (context.outputMode === "text") {
|
|
1666
|
-
printFormattedOutput(formatRunStatus({ activeRuns, recentRuns, runs: Array.isArray(summary.runs) ? summary.runs : [...activeRuns, ...recentRuns] }, { source: isRemoteConnectionSelected(context.projectRoot) ? "server" : "local" }));
|
|
1667
|
-
}
|
|
1668
|
-
return { ok: true, group: "run", command, details: summary };
|
|
1669
|
-
}
|
|
1670
|
-
case "start":
|
|
1671
|
-
case "start-serial":
|
|
1672
|
-
case "start-parallel": {
|
|
1673
|
-
let pending = rest;
|
|
1674
|
-
const epicResult = takeOption(pending, "--epic");
|
|
1675
|
-
pending = epicResult.rest;
|
|
1676
|
-
const promptEpicResult = takeFlag(pending, "--prompt-epic");
|
|
1677
|
-
pending = promptEpicResult.rest;
|
|
1678
|
-
const noEpicPromptResult = takeFlag(pending, "--no-epic-prompt");
|
|
1679
|
-
pending = noEpicPromptResult.rest;
|
|
1680
|
-
const wsPortResult = takeOption(pending, "--ws-port");
|
|
1681
|
-
pending = wsPortResult.rest;
|
|
1682
|
-
const serverHostResult = takeOption(pending, "--server-host");
|
|
1683
|
-
pending = serverHostResult.rest;
|
|
1684
|
-
const serverPortResult = takeOption(pending, "--server-port");
|
|
1685
|
-
pending = serverPortResult.rest;
|
|
1686
|
-
const pollResult = takeOption(pending, "--poll-ms");
|
|
1687
|
-
pending = pollResult.rest;
|
|
1688
|
-
const noServerResult = takeFlag(pending, "--no-server");
|
|
1689
|
-
pending = noServerResult.rest;
|
|
1690
|
-
requireNoExtraArgs(pending, "rig run start [--epic <id>] [--prompt-epic|--no-epic-prompt] [--ws-port <n>] [--server-host <host>] [--server-port <n>] [--poll-ms <n>] [--no-server]");
|
|
1691
|
-
if (promptEpicResult.value && noEpicPromptResult.value) {
|
|
1692
|
-
throw new CliError2("Cannot use --prompt-epic and --no-epic-prompt together.");
|
|
1693
|
-
}
|
|
1694
|
-
if (promptEpicResult.value && (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY)) {
|
|
1695
|
-
throw new CliError2("--prompt-epic requires an interactive terminal (TTY) in text mode.");
|
|
1696
|
-
}
|
|
1697
|
-
let resolvedEpicId = epicResult.value || undefined;
|
|
1698
|
-
if (!resolvedEpicId && shouldPromptForEpicSelection(context, command, promptEpicResult.value, noEpicPromptResult.value)) {
|
|
1699
|
-
resolvedEpicId = await promptForEpicSelection(context.projectRoot, command);
|
|
1700
|
-
}
|
|
1701
|
-
const defaults = defaultStartRunOptions(command === "start-parallel" ? "parallel" : "serial");
|
|
1702
|
-
const result = await startRun(context.projectRoot, {
|
|
1703
|
-
mode: command === "start-parallel" ? "parallel" : "serial",
|
|
1704
|
-
workers: defaults.workers,
|
|
1705
|
-
epicId: resolvedEpicId,
|
|
1706
|
-
wsPort: parsePositiveInt(wsPortResult.value, "--ws-port", defaults.wsPort),
|
|
1707
|
-
startEventServer: noServerResult.value ? false : defaults.startEventServer,
|
|
1708
|
-
serverHost: serverHostResult.value || defaults.serverHost,
|
|
1709
|
-
serverPort: parsePositiveInt(serverPortResult.value, "--server-port", defaults.serverPort),
|
|
1710
|
-
serverPollMs: parsePositiveInt(pollResult.value, "--poll-ms", defaults.serverPollMs),
|
|
1711
|
-
dryRun: context.dryRun,
|
|
1712
|
-
runtimeContext
|
|
1713
|
-
});
|
|
1714
|
-
if (context.outputMode === "text") {
|
|
1715
|
-
console.log(`Epic: ${result.epicId}`);
|
|
1716
|
-
console.log(`Server: ${result.baseUrl}`);
|
|
1717
|
-
if (result.eventServerUrl) {
|
|
1718
|
-
console.log(`Events: ${result.eventServerUrl}`);
|
|
1719
|
-
}
|
|
1720
|
-
console.log(`Runs: ${result.runIds.join(", ")}`);
|
|
1721
|
-
}
|
|
1722
|
-
if (result.exitCode !== 0) {
|
|
1723
|
-
throw new CliError2(`run ${command} failed with exit code ${result.exitCode}.`, result.exitCode);
|
|
1724
|
-
}
|
|
1725
|
-
return {
|
|
1726
|
-
ok: true,
|
|
1727
|
-
group: "run",
|
|
1728
|
-
command,
|
|
1729
|
-
details: {
|
|
1730
|
-
epicId: result.epicId,
|
|
1731
|
-
baseUrl: result.baseUrl,
|
|
1732
|
-
runIds: result.runIds,
|
|
1733
|
-
eventServerUrl: result.eventServerUrl || null
|
|
1734
|
-
}
|
|
1735
|
-
};
|
|
1736
|
-
}
|
|
1737
|
-
case "resume": {
|
|
1738
|
-
requireNoExtraArgs(rest, "rig run resume");
|
|
1739
|
-
if (context.dryRun) {
|
|
1740
|
-
if (context.outputMode === "text") {
|
|
1741
|
-
console.log("[dry-run] rig run resume");
|
|
1742
|
-
}
|
|
1743
|
-
return { ok: true, group: "run", command };
|
|
1744
|
-
}
|
|
1745
|
-
const resumed = await runResume(context.projectRoot, runtimeContext);
|
|
1746
|
-
if (context.outputMode === "text") {
|
|
1747
|
-
console.log(`Resumed run: ${resumed.runId}`);
|
|
1748
|
-
}
|
|
1749
|
-
return { ok: true, group: "run", command, details: resumed };
|
|
1750
|
-
}
|
|
1751
|
-
case "restart": {
|
|
1752
|
-
requireNoExtraArgs(rest, "rig run restart");
|
|
1753
|
-
if (context.dryRun) {
|
|
1754
|
-
if (context.outputMode === "text") {
|
|
1755
|
-
console.log("[dry-run] rig run restart");
|
|
1756
|
-
}
|
|
1757
|
-
return { ok: true, group: "run", command };
|
|
1758
|
-
}
|
|
1759
|
-
const restarted = await runRestart(context.projectRoot, runtimeContext);
|
|
1760
|
-
if (context.outputMode === "text") {
|
|
1761
|
-
console.log(`Restarted run: ${restarted.runId}`);
|
|
1762
|
-
}
|
|
1763
|
-
return { ok: true, group: "run", command, details: restarted };
|
|
1764
|
-
}
|
|
1765
|
-
case "stop": {
|
|
1766
|
-
const runOption = takeOption(rest, "--run");
|
|
1767
|
-
const positionalRunId = runOption.rest.length > 0 ? runOption.rest[0] : undefined;
|
|
1768
|
-
const extra = positionalRunId ? runOption.rest.slice(1) : runOption.rest;
|
|
1769
|
-
requireNoExtraArgs(extra, "rig run stop [<run-id>|--run <id>]");
|
|
1770
|
-
const runId = runOption.value ?? positionalRunId;
|
|
1771
|
-
if (context.dryRun) {
|
|
1772
|
-
return {
|
|
1773
|
-
ok: true,
|
|
1774
|
-
group: "run",
|
|
1775
|
-
command,
|
|
1776
|
-
details: runId ? { runId, accepted: true } : { stopped: 0, remaining: [] }
|
|
1777
|
-
};
|
|
1778
|
-
}
|
|
1779
|
-
if (runId) {
|
|
1780
|
-
const stopped = await stopRunViaServer(context, runId);
|
|
1781
|
-
if (context.outputMode === "text")
|
|
1782
|
-
console.log(`Stop requested: ${runId}`);
|
|
1783
|
-
return { ok: true, group: "run", command, details: stopped };
|
|
1784
|
-
}
|
|
1785
|
-
const result = await runStop(context.projectRoot);
|
|
1786
|
-
if (result.remaining.length > 0) {
|
|
1787
|
-
throw new CliError2(`Failed to stop run(s): ${result.remaining.join(", ")}`, 1);
|
|
1788
|
-
}
|
|
1789
|
-
if (context.outputMode === "text") {
|
|
1790
|
-
console.log(`Stopped process count: ${result.stopped}`);
|
|
1791
|
-
}
|
|
1792
|
-
return {
|
|
1793
|
-
ok: true,
|
|
1794
|
-
group: "run",
|
|
1795
|
-
command,
|
|
1796
|
-
details: {
|
|
1797
|
-
stopped: result.stopped,
|
|
1798
|
-
remaining: result.remaining
|
|
1799
|
-
}
|
|
1800
|
-
};
|
|
1801
|
-
}
|
|
1802
|
-
default:
|
|
1803
|
-
throw new CliError2(`Unknown run command: ${command}`);
|
|
1804
|
-
}
|
|
1805
|
-
}
|
|
1806
|
-
export {
|
|
1807
|
-
executeRun
|
|
1808
|
-
};
|