@h-rig/cli 0.0.6-alpha.5 → 0.0.6-alpha.51
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 +1 -1
- package/dist/bin/rig.js +4129 -1207
- package/dist/src/commands/_cli-format.js +369 -0
- package/dist/src/commands/_connection-state.js +12 -6
- package/dist/src/commands/_doctor-checks.js +79 -34
- package/dist/src/commands/_help-catalog.js +445 -0
- package/dist/src/commands/_operator-surface.js +220 -0
- package/dist/src/commands/_operator-view.js +1124 -64
- package/dist/src/commands/_parsers.js +0 -2
- package/dist/src/commands/_pi-frontend.js +1080 -0
- package/dist/src/commands/_pi-install.js +4 -3
- package/dist/src/commands/_pi-remote-session.js +771 -0
- package/dist/src/commands/_pi-worker-bridge-extension.js +834 -0
- package/dist/src/commands/_policy.js +0 -2
- package/dist/src/commands/_preflight.js +98 -116
- package/dist/src/commands/_run-driver-helpers.js +2 -2
- package/dist/src/commands/_server-client.js +225 -48
- package/dist/src/commands/_snapshot-upload.js +74 -30
- package/dist/src/commands/_spinner.js +63 -0
- package/dist/src/commands/_task-picker.js +44 -16
- package/dist/src/commands/agent.js +8 -9
- package/dist/src/commands/browser.js +4 -6
- package/dist/src/commands/connect.js +134 -26
- package/dist/src/commands/dist.js +4 -6
- package/dist/src/commands/doctor.js +79 -34
- package/dist/src/commands/github.js +76 -32
- package/dist/src/commands/inbox.js +410 -31
- package/dist/src/commands/init.js +398 -90
- package/dist/src/commands/inspect.js +296 -23
- package/dist/src/commands/inspector.js +2 -4
- package/dist/src/commands/pi.js +168 -0
- package/dist/src/commands/plugin.js +81 -22
- package/dist/src/commands/profile-and-review.js +8 -10
- package/dist/src/commands/queue.js +2 -3
- package/dist/src/commands/remote.js +18 -20
- package/dist/src/commands/repo-git-harness.js +6 -8
- package/dist/src/commands/run.js +1422 -131
- package/dist/src/commands/server.js +280 -40
- package/dist/src/commands/setup.js +84 -45
- package/dist/src/commands/task-report-bug.js +5 -7
- package/dist/src/commands/task-run-driver.js +676 -70
- package/dist/src/commands/task.js +1861 -260
- package/dist/src/commands/test.js +3 -5
- package/dist/src/commands/workspace.js +4 -6
- package/dist/src/commands.js +4111 -1183
- package/dist/src/index.js +4122 -1203
- package/dist/src/launcher.js +5 -3
- package/dist/src/report-bug.js +3 -3
- package/dist/src/runner.js +5 -19
- package/package.json +7 -4
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// packages/cli/src/commands/task.ts
|
|
3
|
-
import { readFileSync as
|
|
4
|
-
import { spawnSync
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
3
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
4
|
+
import { spawnSync } from "child_process";
|
|
5
|
+
import { resolve as resolve3 } from "path";
|
|
6
|
+
import { cancel as cancel2, confirm, isCancel as isCancel2 } from "@clack/prompts";
|
|
7
7
|
|
|
8
8
|
// packages/cli/src/runner.ts
|
|
9
9
|
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
10
10
|
import { CliError } from "@rig/runtime/control-plane/errors";
|
|
11
11
|
import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
|
|
12
|
-
import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
|
|
13
|
-
import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
|
|
14
12
|
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
15
13
|
import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
|
|
16
14
|
function takeFlag(args, flag) {
|
|
@@ -130,6 +128,11 @@ function readJsonFile(path) {
|
|
|
130
128
|
throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
131
129
|
}
|
|
132
130
|
}
|
|
131
|
+
function writeJsonFile2(path, value) {
|
|
132
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
133
|
+
writeFileSync(path, `${JSON.stringify(value, null, 2)}
|
|
134
|
+
`, "utf8");
|
|
135
|
+
}
|
|
133
136
|
function normalizeConnection(value) {
|
|
134
137
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
135
138
|
return null;
|
|
@@ -170,29 +173,38 @@ function readRepoConnection(projectRoot) {
|
|
|
170
173
|
return {
|
|
171
174
|
selected,
|
|
172
175
|
project: typeof record.project === "string" ? record.project : undefined,
|
|
173
|
-
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
|
|
176
|
+
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
|
|
177
|
+
serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
|
|
174
178
|
};
|
|
175
179
|
}
|
|
180
|
+
function writeRepoConnection(projectRoot, state) {
|
|
181
|
+
writeJsonFile2(resolveRepoConnectionPath(projectRoot), state);
|
|
182
|
+
}
|
|
176
183
|
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
177
184
|
const repo = readRepoConnection(projectRoot);
|
|
178
185
|
if (!repo)
|
|
179
186
|
return null;
|
|
180
187
|
if (repo.selected === "local")
|
|
181
|
-
return { alias: "local", connection: { kind: "local", mode: "auto" } };
|
|
188
|
+
return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
|
|
182
189
|
const global = readGlobalConnections(options);
|
|
183
190
|
const connection = global.connections[repo.selected];
|
|
184
191
|
if (!connection) {
|
|
185
|
-
throw new CliError2(`Selected Rig
|
|
192
|
+
throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
186
193
|
}
|
|
187
|
-
return { alias: repo.selected, connection };
|
|
194
|
+
return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
|
|
195
|
+
}
|
|
196
|
+
function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
|
|
197
|
+
const repo = readRepoConnection(projectRoot);
|
|
198
|
+
if (!repo)
|
|
199
|
+
return;
|
|
200
|
+
writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
|
|
188
201
|
}
|
|
189
202
|
|
|
190
203
|
// packages/cli/src/commands/_server-client.ts
|
|
191
|
-
import { spawnSync } from "child_process";
|
|
192
204
|
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
193
205
|
import { resolve as resolve2 } from "path";
|
|
194
206
|
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
195
|
-
var
|
|
207
|
+
var scopedGitHubBearerTokens = new Map;
|
|
196
208
|
function cleanToken(value) {
|
|
197
209
|
const trimmed = value?.trim();
|
|
198
210
|
return trimmed ? trimmed : null;
|
|
@@ -209,41 +221,47 @@ function readPrivateRemoteSessionToken(projectRoot) {
|
|
|
209
221
|
}
|
|
210
222
|
}
|
|
211
223
|
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
212
|
-
|
|
213
|
-
|
|
224
|
+
const scopedKey = resolve2(projectRoot);
|
|
225
|
+
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
226
|
+
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
214
227
|
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
215
|
-
if (privateSession)
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
return
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
|
|
228
|
+
if (privateSession)
|
|
229
|
+
return privateSession;
|
|
230
|
+
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
231
|
+
}
|
|
232
|
+
function readStoredGitHubAuthToken(projectRoot) {
|
|
233
|
+
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
234
|
+
if (!existsSync2(path))
|
|
235
|
+
return null;
|
|
236
|
+
try {
|
|
237
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
238
|
+
return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
|
|
239
|
+
} catch {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function readLocalConnectionFallbackToken(projectRoot) {
|
|
244
|
+
return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
|
|
231
245
|
}
|
|
232
246
|
async function ensureServerForCli(projectRoot) {
|
|
233
247
|
try {
|
|
234
248
|
const selected = resolveSelectedConnection(projectRoot);
|
|
235
249
|
if (selected?.connection.kind === "remote") {
|
|
250
|
+
const authToken = readGitHubBearerTokenForRemote(projectRoot);
|
|
251
|
+
const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
|
|
236
252
|
return {
|
|
237
253
|
baseUrl: selected.connection.baseUrl,
|
|
238
|
-
authToken
|
|
239
|
-
connectionKind: "remote"
|
|
254
|
+
authToken,
|
|
255
|
+
connectionKind: "remote",
|
|
256
|
+
serverProjectRoot
|
|
240
257
|
};
|
|
241
258
|
}
|
|
242
259
|
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
243
260
|
return {
|
|
244
261
|
baseUrl: connection.baseUrl,
|
|
245
|
-
authToken: connection.authToken,
|
|
246
|
-
connectionKind: "local"
|
|
262
|
+
authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
|
|
263
|
+
connectionKind: "local",
|
|
264
|
+
serverProjectRoot: resolve2(projectRoot)
|
|
247
265
|
};
|
|
248
266
|
} catch (error) {
|
|
249
267
|
if (error instanceof Error) {
|
|
@@ -252,6 +270,29 @@ async function ensureServerForCli(projectRoot) {
|
|
|
252
270
|
throw error;
|
|
253
271
|
}
|
|
254
272
|
}
|
|
273
|
+
async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
|
|
274
|
+
const repo = readRepoConnection(projectRoot);
|
|
275
|
+
const slug = repo?.project?.trim();
|
|
276
|
+
if (!slug)
|
|
277
|
+
return null;
|
|
278
|
+
try {
|
|
279
|
+
const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
|
|
280
|
+
headers: mergeHeaders(undefined, authToken)
|
|
281
|
+
});
|
|
282
|
+
if (!response.ok)
|
|
283
|
+
return null;
|
|
284
|
+
const payload = await response.json();
|
|
285
|
+
const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
|
|
286
|
+
const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
|
|
287
|
+
const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
|
|
288
|
+
const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
|
|
289
|
+
if (path)
|
|
290
|
+
writeRepoServerProjectRoot(projectRoot, path);
|
|
291
|
+
return path;
|
|
292
|
+
} catch {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
255
296
|
function appendTaskFilterParams(url, filters) {
|
|
256
297
|
if (filters.assignee)
|
|
257
298
|
url.searchParams.set("assignee", filters.assignee);
|
|
@@ -286,9 +327,12 @@ function diagnosticMessage(payload) {
|
|
|
286
327
|
}
|
|
287
328
|
async function requestServerJson(context, pathname, init = {}) {
|
|
288
329
|
const server = await ensureServerForCli(context.projectRoot);
|
|
330
|
+
const headers = mergeHeaders(init.headers, server.authToken);
|
|
331
|
+
if (server.serverProjectRoot)
|
|
332
|
+
headers.set("x-rig-project-root", server.serverProjectRoot);
|
|
289
333
|
const response = await fetch(`${server.baseUrl}${pathname}`, {
|
|
290
334
|
...init,
|
|
291
|
-
headers
|
|
335
|
+
headers
|
|
292
336
|
});
|
|
293
337
|
const text = await response.text();
|
|
294
338
|
const payload = text.trim().length > 0 ? (() => {
|
|
@@ -347,6 +391,15 @@ async function getRunLogsViaServer(context, runId, options = {}) {
|
|
|
347
391
|
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
348
392
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
349
393
|
}
|
|
394
|
+
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
395
|
+
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
396
|
+
if (options.limit !== undefined)
|
|
397
|
+
url.searchParams.set("limit", String(options.limit));
|
|
398
|
+
if (options.cursor)
|
|
399
|
+
url.searchParams.set("cursor", options.cursor);
|
|
400
|
+
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
401
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
402
|
+
}
|
|
350
403
|
async function stopRunViaServer(context, runId) {
|
|
351
404
|
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
352
405
|
method: "POST",
|
|
@@ -363,6 +416,72 @@ async function steerRunViaServer(context, runId, message) {
|
|
|
363
416
|
});
|
|
364
417
|
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
365
418
|
}
|
|
419
|
+
async function getRunPiSessionViaServer(context, runId) {
|
|
420
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
421
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
422
|
+
}
|
|
423
|
+
async function getRunPiMessagesViaServer(context, runId) {
|
|
424
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
425
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
426
|
+
}
|
|
427
|
+
async function getRunPiStatusViaServer(context, runId) {
|
|
428
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
429
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
430
|
+
}
|
|
431
|
+
async function getRunPiCommandsViaServer(context, runId) {
|
|
432
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
433
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
434
|
+
}
|
|
435
|
+
async function getRunPiCapabilitiesViaServer(context, runId) {
|
|
436
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/capabilities`);
|
|
437
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { capabilities: null };
|
|
438
|
+
}
|
|
439
|
+
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
440
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
441
|
+
method: "POST",
|
|
442
|
+
headers: { "content-type": "application/json" },
|
|
443
|
+
body: JSON.stringify({ text, streamingBehavior })
|
|
444
|
+
});
|
|
445
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
446
|
+
}
|
|
447
|
+
async function sendRunPiShellViaServer(context, runId, text) {
|
|
448
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
449
|
+
method: "POST",
|
|
450
|
+
headers: { "content-type": "application/json" },
|
|
451
|
+
body: JSON.stringify({ text })
|
|
452
|
+
});
|
|
453
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
454
|
+
}
|
|
455
|
+
async function runRunPiCommandViaServer(context, runId, text) {
|
|
456
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
457
|
+
method: "POST",
|
|
458
|
+
headers: { "content-type": "application/json" },
|
|
459
|
+
body: JSON.stringify({ text })
|
|
460
|
+
});
|
|
461
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
462
|
+
}
|
|
463
|
+
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
464
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
465
|
+
method: "POST",
|
|
466
|
+
headers: { "content-type": "application/json" },
|
|
467
|
+
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
468
|
+
});
|
|
469
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
470
|
+
}
|
|
471
|
+
async function abortRunPiViaServer(context, runId) {
|
|
472
|
+
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
473
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
474
|
+
}
|
|
475
|
+
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
476
|
+
const server = await ensureServerForCli(context.projectRoot);
|
|
477
|
+
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
478
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
479
|
+
if (server.authToken)
|
|
480
|
+
url.searchParams.set("token", server.authToken);
|
|
481
|
+
if (server.serverProjectRoot)
|
|
482
|
+
url.searchParams.set("rigProjectRoot", server.serverProjectRoot);
|
|
483
|
+
return url.toString();
|
|
484
|
+
}
|
|
366
485
|
async function submitTaskRunViaServer(context, input) {
|
|
367
486
|
const isTaskRun = Boolean(input.taskId);
|
|
368
487
|
const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
|
|
@@ -395,78 +514,6 @@ async function submitTaskRunViaServer(context, input) {
|
|
|
395
514
|
return { runId };
|
|
396
515
|
}
|
|
397
516
|
|
|
398
|
-
// packages/cli/src/commands/_pi-install.ts
|
|
399
|
-
import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
|
|
400
|
-
import { homedir as homedir2 } from "os";
|
|
401
|
-
import { resolve as resolve3 } from "path";
|
|
402
|
-
var PI_RIG_PACKAGE_NAME = "@rig/pi-rig";
|
|
403
|
-
async function defaultCommandRunner(command, options = {}) {
|
|
404
|
-
const proc = Bun.spawn(command, { cwd: options.cwd, stdout: "pipe", stderr: "pipe" });
|
|
405
|
-
const [stdout, stderr, exitCode] = await Promise.all([
|
|
406
|
-
new Response(proc.stdout).text(),
|
|
407
|
-
new Response(proc.stderr).text(),
|
|
408
|
-
proc.exited
|
|
409
|
-
]);
|
|
410
|
-
return { exitCode, stdout, stderr };
|
|
411
|
-
}
|
|
412
|
-
function resolvePiRigExtensionPath(homeDir) {
|
|
413
|
-
return resolve3(homeDir, ".pi", "agent", "extensions", "pi-rig");
|
|
414
|
-
}
|
|
415
|
-
function resolvePiHomeDir(inputHomeDir) {
|
|
416
|
-
return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
|
|
417
|
-
}
|
|
418
|
-
function piListContainsPiRig(output) {
|
|
419
|
-
return output.split(/\r?\n/).some((line) => {
|
|
420
|
-
const normalized = line.trim();
|
|
421
|
-
return normalized.includes(PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
async function safeRun(runner, command, options) {
|
|
425
|
-
try {
|
|
426
|
-
return await runner(command, options);
|
|
427
|
-
} catch (error) {
|
|
428
|
-
return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
async function checkPiRigInstall(input = {}) {
|
|
432
|
-
const home = resolvePiHomeDir(input.homeDir);
|
|
433
|
-
const extensionPath = resolvePiRigExtensionPath(home);
|
|
434
|
-
if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
|
|
435
|
-
return {
|
|
436
|
-
extensionPath,
|
|
437
|
-
pi: { ok: true, label: "pi", detail: "fake-pi" },
|
|
438
|
-
piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
const exists = input.exists ?? existsSync3;
|
|
442
|
-
const runner = input.commandRunner ?? defaultCommandRunner;
|
|
443
|
-
const piResult = await safeRun(runner, ["pi", "--version"]);
|
|
444
|
-
const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
|
|
445
|
-
const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
|
|
446
|
-
${piListResult.stderr}`);
|
|
447
|
-
const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
|
|
448
|
-
const hasPiRig = listedPiRig;
|
|
449
|
-
return {
|
|
450
|
-
extensionPath,
|
|
451
|
-
pi: {
|
|
452
|
-
ok: piResult.exitCode === 0,
|
|
453
|
-
label: "pi",
|
|
454
|
-
detail: (piResult.stdout || piResult.stderr).trim() || undefined,
|
|
455
|
-
hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
|
|
456
|
-
},
|
|
457
|
-
piRig: {
|
|
458
|
-
ok: hasPiRig,
|
|
459
|
-
label: "pi-rig global extension",
|
|
460
|
-
detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
|
|
461
|
-
hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
|
|
462
|
-
}
|
|
463
|
-
};
|
|
464
|
-
}
|
|
465
|
-
async function buildPiSetupChecks(input = {}) {
|
|
466
|
-
const status = await checkPiRigInstall(input);
|
|
467
|
-
return [status.pi, status.piRig];
|
|
468
|
-
}
|
|
469
|
-
|
|
470
517
|
// packages/cli/src/commands/_preflight.ts
|
|
471
518
|
function preflightCheck(id, label, status, detail, remediation) {
|
|
472
519
|
return {
|
|
@@ -522,6 +569,9 @@ function permissionAllowsPr(payload) {
|
|
|
522
569
|
}
|
|
523
570
|
return null;
|
|
524
571
|
}
|
|
572
|
+
function isNotFoundError(error) {
|
|
573
|
+
return /\b(404|not found)\b/i.test(message(error));
|
|
574
|
+
}
|
|
525
575
|
function projectCheckoutReady(payload) {
|
|
526
576
|
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
527
577
|
return null;
|
|
@@ -554,19 +604,33 @@ async function runFastTaskRunPreflight(context, options = {}) {
|
|
|
554
604
|
const checks = [];
|
|
555
605
|
const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
|
|
556
606
|
const taskId = options.taskId?.trim() || null;
|
|
607
|
+
const requiresCurrentRunApi = Boolean(taskId);
|
|
608
|
+
const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
|
|
609
|
+
const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
|
|
610
|
+
let legacyServerCompatibility = false;
|
|
557
611
|
try {
|
|
558
612
|
await request("/api/server/status");
|
|
559
613
|
checks.push(preflightCheck("server", "Rig server reachable", "pass"));
|
|
560
614
|
} catch (error) {
|
|
561
|
-
|
|
615
|
+
if (isNotFoundError(error)) {
|
|
616
|
+
try {
|
|
617
|
+
await request("/health");
|
|
618
|
+
legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
|
|
619
|
+
checks.push(requiresCurrentRunApi && !allowLocalLegacyTaskRunCompatibility ? preflightCheck("server", "Rig server reachable", "fail", "legacy /health endpoint only; current task-run APIs are required", "Upgrade/select the Rig server before launching a task run.") : preflightCheck("server", "Rig server reachable", "pass", allowLocalLegacyTaskRunCompatibility ? "local legacy /health endpoint; submit endpoint will be authoritative" : "legacy /health endpoint"));
|
|
620
|
+
} catch (healthError) {
|
|
621
|
+
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
|
|
622
|
+
}
|
|
623
|
+
} else {
|
|
624
|
+
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
|
|
625
|
+
}
|
|
562
626
|
}
|
|
563
627
|
const repo = readRepoConnection(context.projectRoot);
|
|
564
|
-
checks.push(repo ? preflightCheck("project-link", "project linked to Rig
|
|
628
|
+
checks.push(repo ? preflightCheck("project-link", "project linked to Rig server", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to Rig server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
|
|
565
629
|
try {
|
|
566
630
|
const auth = await request("/api/github/auth/status");
|
|
567
|
-
checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
|
|
631
|
+
checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
|
|
568
632
|
} catch (error) {
|
|
569
|
-
checks.push(preflightCheck("github-auth", "GitHub auth valid", "fail", message(error), "Fix GitHub auth on the selected Rig server."));
|
|
633
|
+
checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
|
|
570
634
|
}
|
|
571
635
|
try {
|
|
572
636
|
const projection = await request("/api/workspace/task-projection");
|
|
@@ -594,9 +658,9 @@ async function runFastTaskRunPreflight(context, options = {}) {
|
|
|
594
658
|
try {
|
|
595
659
|
const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
|
|
596
660
|
const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
|
|
597
|
-
checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
|
|
661
|
+
checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
|
|
598
662
|
} catch (error) {
|
|
599
|
-
checks.push(preflightCheck("issue", "task/issue accessible", "fail", message(error), "Fix the task source before launching a run."));
|
|
663
|
+
checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
|
|
600
664
|
}
|
|
601
665
|
try {
|
|
602
666
|
const runs = await request("/api/runs?limit=200");
|
|
@@ -607,14 +671,7 @@ async function runFastTaskRunPreflight(context, options = {}) {
|
|
|
607
671
|
}
|
|
608
672
|
}
|
|
609
673
|
if ((options.runtimeAdapter ?? "pi") === "pi") {
|
|
610
|
-
|
|
611
|
-
ok: false,
|
|
612
|
-
label: "pi/pi-rig checks",
|
|
613
|
-
hint: message(error)
|
|
614
|
-
}]);
|
|
615
|
-
for (const pi of piChecks) {
|
|
616
|
-
checks.push(preflightCheck(pi.label === "pi" ? "pi" : "pi-rig", pi.label, pi.ok ? "pass" : "fail", pi.detail, pi.hint ?? (pi.ok ? undefined : "Run `rig init --yes` to install/update Pi and enable pi-rig.")));
|
|
617
|
-
}
|
|
674
|
+
checks.push(preflightCheck("runtime", "worker Pi SDK session daemon", "pass", selectedServer?.connectionKind === "remote" ? "remote worker-owned runtime" : "bundled server-owned runtime"));
|
|
618
675
|
} else {
|
|
619
676
|
checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
|
|
620
677
|
}
|
|
@@ -706,7 +763,200 @@ function withMutedConsole(mute, fn) {
|
|
|
706
763
|
}
|
|
707
764
|
|
|
708
765
|
// packages/cli/src/commands/_task-picker.ts
|
|
709
|
-
import {
|
|
766
|
+
import { cancel, isCancel, select } from "@clack/prompts";
|
|
767
|
+
|
|
768
|
+
// packages/cli/src/commands/_operator-surface.ts
|
|
769
|
+
import { createInterface } from "readline";
|
|
770
|
+
import { createInterface as createPromptInterface } from "readline/promises";
|
|
771
|
+
var CANONICAL_STAGES = [
|
|
772
|
+
"Connect",
|
|
773
|
+
"GitHub/task sync",
|
|
774
|
+
"Prepare workspace",
|
|
775
|
+
"Launch Pi",
|
|
776
|
+
"Plan",
|
|
777
|
+
"Implement",
|
|
778
|
+
"Validate",
|
|
779
|
+
"Commit",
|
|
780
|
+
"Open PR",
|
|
781
|
+
"Review/CI",
|
|
782
|
+
"Merge",
|
|
783
|
+
"Complete"
|
|
784
|
+
];
|
|
785
|
+
function logDetail(log) {
|
|
786
|
+
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
787
|
+
}
|
|
788
|
+
function parseProviderProtocolLog(title, detail) {
|
|
789
|
+
if (title.trim().toLowerCase() !== "agent output")
|
|
790
|
+
return null;
|
|
791
|
+
if (!detail.startsWith("{") || !detail.endsWith("}"))
|
|
792
|
+
return null;
|
|
793
|
+
try {
|
|
794
|
+
const record = JSON.parse(detail);
|
|
795
|
+
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
796
|
+
return null;
|
|
797
|
+
const type = record.type;
|
|
798
|
+
return typeof type === "string" && [
|
|
799
|
+
"assistant",
|
|
800
|
+
"message_start",
|
|
801
|
+
"message_update",
|
|
802
|
+
"message_end",
|
|
803
|
+
"stream_event",
|
|
804
|
+
"tool_result",
|
|
805
|
+
"tool_execution_start",
|
|
806
|
+
"tool_execution_update",
|
|
807
|
+
"tool_execution_end",
|
|
808
|
+
"turn_start",
|
|
809
|
+
"turn_end"
|
|
810
|
+
].includes(type) ? record : null;
|
|
811
|
+
} catch {
|
|
812
|
+
return null;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
function renderProviderProtocolLog(record) {
|
|
816
|
+
const type = typeof record.type === "string" ? record.type : "";
|
|
817
|
+
if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
|
|
818
|
+
const toolName = String(record.toolName ?? record.name ?? "tool");
|
|
819
|
+
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";
|
|
820
|
+
return `[Pi tool] ${toolName} ${status}`;
|
|
821
|
+
}
|
|
822
|
+
return null;
|
|
823
|
+
}
|
|
824
|
+
function entryId(entry, fallback) {
|
|
825
|
+
return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
|
|
826
|
+
}
|
|
827
|
+
function renderOperatorSnapshot(snapshot) {
|
|
828
|
+
const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
|
|
829
|
+
const runId = String(run.runId ?? run.id ?? "run");
|
|
830
|
+
const status = String(run.status ?? "unknown");
|
|
831
|
+
const logs = snapshot.logs ?? [];
|
|
832
|
+
const latestByStage = new Map;
|
|
833
|
+
for (const log of logs) {
|
|
834
|
+
const title = String(log.title ?? "").toLowerCase();
|
|
835
|
+
const stageName = String(log.stage ?? "").toLowerCase();
|
|
836
|
+
const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
837
|
+
if (stage)
|
|
838
|
+
latestByStage.set(stage, log);
|
|
839
|
+
}
|
|
840
|
+
const stageLines = CANONICAL_STAGES.flatMap((stage) => {
|
|
841
|
+
const match = latestByStage.get(stage);
|
|
842
|
+
return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
|
|
843
|
+
});
|
|
844
|
+
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
845
|
+
`);
|
|
846
|
+
}
|
|
847
|
+
function createPiRunStreamRenderer(output = process.stdout) {
|
|
848
|
+
let lastSnapshot = "";
|
|
849
|
+
const assistantTextById = new Map;
|
|
850
|
+
const seenTimeline = new Set;
|
|
851
|
+
const seenLogs = new Set;
|
|
852
|
+
const writeLine = (line) => output.write(`${line}
|
|
853
|
+
`);
|
|
854
|
+
return {
|
|
855
|
+
renderSnapshot(snapshot) {
|
|
856
|
+
const rendered = renderOperatorSnapshot(snapshot);
|
|
857
|
+
if (rendered && rendered !== lastSnapshot) {
|
|
858
|
+
writeLine(rendered);
|
|
859
|
+
lastSnapshot = rendered;
|
|
860
|
+
}
|
|
861
|
+
},
|
|
862
|
+
renderTimeline(entries) {
|
|
863
|
+
for (const [index, entry] of entries.entries()) {
|
|
864
|
+
const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
|
|
865
|
+
if (entry.type === "assistant_message" && typeof entry.text === "string") {
|
|
866
|
+
const text = entry.text;
|
|
867
|
+
const previousText = assistantTextById.get(id) ?? "";
|
|
868
|
+
if (!previousText && text.trim()) {
|
|
869
|
+
writeLine("[Pi assistant]");
|
|
870
|
+
}
|
|
871
|
+
if (text.startsWith(previousText)) {
|
|
872
|
+
const delta = text.slice(previousText.length);
|
|
873
|
+
if (delta)
|
|
874
|
+
output.write(delta);
|
|
875
|
+
} else if (text.trim() && text !== previousText) {
|
|
876
|
+
if (previousText)
|
|
877
|
+
writeLine(`
|
|
878
|
+
[Pi assistant]`);
|
|
879
|
+
output.write(text);
|
|
880
|
+
}
|
|
881
|
+
assistantTextById.set(id, text);
|
|
882
|
+
continue;
|
|
883
|
+
}
|
|
884
|
+
if (seenTimeline.has(id))
|
|
885
|
+
continue;
|
|
886
|
+
seenTimeline.add(id);
|
|
887
|
+
if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
|
|
888
|
+
writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
|
|
889
|
+
continue;
|
|
890
|
+
}
|
|
891
|
+
if (entry.type === "timeline_warning") {
|
|
892
|
+
writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
|
|
893
|
+
continue;
|
|
894
|
+
}
|
|
895
|
+
if (entry.type === "action") {
|
|
896
|
+
const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
|
|
897
|
+
if (text)
|
|
898
|
+
writeLine(`[Rig action] ${text}`);
|
|
899
|
+
continue;
|
|
900
|
+
}
|
|
901
|
+
if (entry.type === "user_message") {
|
|
902
|
+
const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
|
|
903
|
+
if (text)
|
|
904
|
+
writeLine(`[Operator] ${text}`);
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
|
|
908
|
+
if (fallback)
|
|
909
|
+
writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
|
|
910
|
+
}
|
|
911
|
+
},
|
|
912
|
+
renderLogs(entries) {
|
|
913
|
+
for (const [index, entry] of entries.entries()) {
|
|
914
|
+
const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
|
|
915
|
+
if (seenLogs.has(id))
|
|
916
|
+
continue;
|
|
917
|
+
seenLogs.add(id);
|
|
918
|
+
const title = String(entry.title ?? "");
|
|
919
|
+
if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
|
|
920
|
+
continue;
|
|
921
|
+
const detail = logDetail(entry);
|
|
922
|
+
if (!detail)
|
|
923
|
+
continue;
|
|
924
|
+
const protocolRecord = parseProviderProtocolLog(title, detail);
|
|
925
|
+
if (protocolRecord) {
|
|
926
|
+
const protocolLine = renderProviderProtocolLog(protocolRecord);
|
|
927
|
+
if (protocolLine)
|
|
928
|
+
writeLine(protocolLine);
|
|
929
|
+
continue;
|
|
930
|
+
}
|
|
931
|
+
writeLine(`[${title || "Rig log"}] ${detail}`);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
function createOperatorSurface(options = {}) {
|
|
937
|
+
const input = options.input ?? process.stdin;
|
|
938
|
+
const output = options.output ?? process.stdout;
|
|
939
|
+
const errorOutput = options.errorOutput ?? process.stderr;
|
|
940
|
+
const renderer = createPiRunStreamRenderer(output);
|
|
941
|
+
const writeLine = (line) => output.write(`${line}
|
|
942
|
+
`);
|
|
943
|
+
return {
|
|
944
|
+
mode: "pi-compatible-text",
|
|
945
|
+
...renderer,
|
|
946
|
+
info: writeLine,
|
|
947
|
+
error: (message2) => errorOutput.write(`${message2}
|
|
948
|
+
`),
|
|
949
|
+
attachCommandInput(handler) {
|
|
950
|
+
if (options.interactive === false || !input.isTTY)
|
|
951
|
+
return null;
|
|
952
|
+
const rl = createInterface({ input, output: process.stdout, terminal: false });
|
|
953
|
+
rl.on("line", (line) => {
|
|
954
|
+
Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
955
|
+
});
|
|
956
|
+
return { close: () => rl.close() };
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
}
|
|
710
960
|
function taskId(task) {
|
|
711
961
|
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
712
962
|
}
|
|
@@ -719,6 +969,19 @@ function taskStatus(task) {
|
|
|
719
969
|
function renderTaskPickerRows(tasks) {
|
|
720
970
|
return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
|
|
721
971
|
}
|
|
972
|
+
async function promptForTaskSelection(question) {
|
|
973
|
+
const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
|
|
974
|
+
try {
|
|
975
|
+
return await rl.question(question);
|
|
976
|
+
} finally {
|
|
977
|
+
rl.close();
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// packages/cli/src/commands/_task-picker.ts
|
|
982
|
+
function taskId2(task) {
|
|
983
|
+
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
984
|
+
}
|
|
722
985
|
async function selectTaskWithTextPicker(tasks, io = {}) {
|
|
723
986
|
if (tasks.length === 0)
|
|
724
987
|
return null;
|
|
@@ -728,56 +991,800 @@ async function selectTaskWithTextPicker(tasks, io = {}) {
|
|
|
728
991
|
if (!isTty) {
|
|
729
992
|
throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
|
|
730
993
|
}
|
|
731
|
-
|
|
732
|
-
const
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
994
|
+
if (io.prompt || io.renderer) {
|
|
995
|
+
const prompt = io.prompt ?? promptForTaskSelection;
|
|
996
|
+
const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
|
|
997
|
+
`) };
|
|
998
|
+
renderer.writeLine("Select Rig task:");
|
|
999
|
+
for (const row of renderTaskPickerRows(tasks))
|
|
1000
|
+
renderer.writeLine(` ${row}`);
|
|
1001
|
+
const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
|
|
1002
|
+
if (!answer2)
|
|
1003
|
+
return null;
|
|
1004
|
+
if (/^\d+$/.test(answer2)) {
|
|
1005
|
+
const index2 = Number.parseInt(answer2, 10) - 1;
|
|
1006
|
+
return tasks[index2] ?? null;
|
|
737
1007
|
}
|
|
1008
|
+
return tasks.find((task) => taskId2(task) === answer2) ?? null;
|
|
1009
|
+
}
|
|
1010
|
+
const options = tasks.map((task, index2) => ({
|
|
1011
|
+
value: `${index2}`,
|
|
1012
|
+
label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
|
|
1013
|
+
hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
|
|
1014
|
+
}));
|
|
1015
|
+
const answer = await select({
|
|
1016
|
+
message: "Select Rig task",
|
|
1017
|
+
options
|
|
738
1018
|
});
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
console.log(` ${row}`);
|
|
742
|
-
const answer = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
|
|
743
|
-
if (!answer)
|
|
1019
|
+
if (isCancel(answer)) {
|
|
1020
|
+
cancel("No task selected.");
|
|
744
1021
|
return null;
|
|
745
|
-
if (/^\d+$/.test(answer)) {
|
|
746
|
-
const index = Number.parseInt(answer, 10) - 1;
|
|
747
|
-
return tasks[index] ?? null;
|
|
748
1022
|
}
|
|
749
|
-
|
|
1023
|
+
const index = Number.parseInt(String(answer), 10);
|
|
1024
|
+
return Number.isFinite(index) ? tasks[index] ?? null : null;
|
|
750
1025
|
}
|
|
751
1026
|
|
|
752
|
-
// packages/cli/src/commands/
|
|
753
|
-
import {
|
|
1027
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
1028
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
1029
|
+
import { tmpdir } from "os";
|
|
1030
|
+
import { join } from "path";
|
|
1031
|
+
import {
|
|
1032
|
+
createAgentSessionFromServices,
|
|
1033
|
+
createAgentSessionServices,
|
|
1034
|
+
main as runPiMain
|
|
1035
|
+
} from "@earendil-works/pi-coding-agent";
|
|
1036
|
+
|
|
1037
|
+
// packages/cli/src/commands/_pi-remote-session.ts
|
|
1038
|
+
import { AgentSession as PiAgentSession, expandPromptTemplate } from "@earendil-works/pi-coding-agent";
|
|
754
1039
|
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
function
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1040
|
+
function defaultTransport() {
|
|
1041
|
+
return {
|
|
1042
|
+
getSession: getRunPiSessionViaServer,
|
|
1043
|
+
getMessages: getRunPiMessagesViaServer,
|
|
1044
|
+
getStatus: getRunPiStatusViaServer,
|
|
1045
|
+
getCommands: getRunPiCommandsViaServer,
|
|
1046
|
+
getCapabilities: getRunPiCapabilitiesViaServer,
|
|
1047
|
+
sendPrompt: sendRunPiPromptViaServer,
|
|
1048
|
+
sendShell: sendRunPiShellViaServer,
|
|
1049
|
+
runCommand: runRunPiCommandViaServer,
|
|
1050
|
+
abort: abortRunPiViaServer,
|
|
1051
|
+
buildEventsWebSocketUrl: buildRunPiEventsWebSocketUrl
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
function recordOf(value) {
|
|
1055
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1056
|
+
}
|
|
1057
|
+
function emptyRemoteStatus() {
|
|
1058
|
+
return {
|
|
1059
|
+
isStreaming: false,
|
|
1060
|
+
isCompacting: false,
|
|
1061
|
+
isBashRunning: false,
|
|
1062
|
+
pendingMessageCount: 0,
|
|
1063
|
+
steeringMessages: [],
|
|
1064
|
+
followUpMessages: [],
|
|
1065
|
+
model: null,
|
|
1066
|
+
thinkingLevel: null,
|
|
1067
|
+
sessionName: null,
|
|
1068
|
+
cwd: null,
|
|
1069
|
+
stats: null,
|
|
1070
|
+
contextUsage: null
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
function resolveAttachReadyTimeoutMs() {
|
|
1074
|
+
const raw = Number.parseInt(process.env.RIG_PI_ATTACH_TIMEOUT_MS ?? "", 10);
|
|
1075
|
+
return Number.isFinite(raw) && raw > 0 ? raw : 10 * 60000;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
class RigRemoteSessionController {
|
|
1079
|
+
context;
|
|
1080
|
+
runId;
|
|
1081
|
+
status = emptyRemoteStatus();
|
|
1082
|
+
transport;
|
|
1083
|
+
hooks = {};
|
|
1084
|
+
session = null;
|
|
1085
|
+
socket = null;
|
|
1086
|
+
closed = false;
|
|
1087
|
+
pendingShells = [];
|
|
1088
|
+
pendingCompactions = [];
|
|
1089
|
+
constructor(input) {
|
|
1090
|
+
this.context = input.context;
|
|
1091
|
+
this.runId = input.runId;
|
|
1092
|
+
this.transport = input.transport ?? defaultTransport();
|
|
1093
|
+
}
|
|
1094
|
+
ingestEnvelope(envelopeValue) {
|
|
1095
|
+
this.applyEnvelope(envelopeValue);
|
|
1096
|
+
}
|
|
1097
|
+
bindSession(session) {
|
|
1098
|
+
this.session = session;
|
|
1099
|
+
}
|
|
1100
|
+
setUiHooks(hooks) {
|
|
1101
|
+
this.hooks = hooks;
|
|
1102
|
+
}
|
|
1103
|
+
async connect() {
|
|
1104
|
+
const ready = await this.waitForReady();
|
|
1105
|
+
if (!ready || this.closed)
|
|
1106
|
+
return;
|
|
1107
|
+
let catchupDone = false;
|
|
1108
|
+
const buffered = [];
|
|
1109
|
+
const wsUrl = await this.transport.buildEventsWebSocketUrl(this.context, this.runId);
|
|
1110
|
+
const socket = new WebSocket(wsUrl);
|
|
1111
|
+
this.socket = socket;
|
|
1112
|
+
socket.onopen = () => {
|
|
1113
|
+
this.hooks.onConnectionChange?.(true);
|
|
1114
|
+
this.hooks.onStatusText?.("worker session live");
|
|
1115
|
+
};
|
|
1116
|
+
socket.onmessage = (message2) => {
|
|
1117
|
+
try {
|
|
1118
|
+
const payload = typeof message2.data === "string" ? JSON.parse(message2.data) : JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
1119
|
+
if (!catchupDone)
|
|
1120
|
+
buffered.push(payload);
|
|
1121
|
+
else
|
|
1122
|
+
this.applyEnvelope(payload);
|
|
1123
|
+
} catch (error) {
|
|
1124
|
+
this.hooks.onError?.(`Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
socket.onerror = () => socket.close();
|
|
1128
|
+
socket.onclose = () => {
|
|
1129
|
+
this.hooks.onConnectionChange?.(false);
|
|
1130
|
+
if (!this.closed)
|
|
1131
|
+
this.hooks.onStatusText?.("worker Pi WebSocket disconnected");
|
|
1132
|
+
};
|
|
1133
|
+
try {
|
|
1134
|
+
const [messagesPayload, statusPayload, commandsPayload, capabilitiesPayload] = await Promise.all([
|
|
1135
|
+
this.transport.getMessages(this.context, this.runId),
|
|
1136
|
+
this.transport.getStatus(this.context, this.runId),
|
|
1137
|
+
this.transport.getCommands(this.context, this.runId),
|
|
1138
|
+
this.transport.getCapabilities(this.context, this.runId).catch(() => ({ capabilities: null }))
|
|
1139
|
+
]);
|
|
1140
|
+
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
1141
|
+
this.applyStatusPayload(statusPayload);
|
|
1142
|
+
this.session?.replaceRemoteMessages(messages);
|
|
1143
|
+
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
1144
|
+
const capabilities = capabilitiesPayload.capabilities && typeof capabilitiesPayload.capabilities === "object" && !Array.isArray(capabilitiesPayload.capabilities) ? capabilitiesPayload.capabilities : null;
|
|
1145
|
+
this.hooks.onCatchUp?.(messages, commands, capabilities);
|
|
1146
|
+
catchupDone = true;
|
|
1147
|
+
for (const payload of buffered.splice(0))
|
|
1148
|
+
this.applyEnvelope(payload);
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
catchupDone = true;
|
|
1151
|
+
this.hooks.onError?.(`Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
close() {
|
|
1155
|
+
this.closed = true;
|
|
1156
|
+
this.socket?.close();
|
|
1157
|
+
for (const shell of this.pendingShells.splice(0))
|
|
1158
|
+
shell.reject(new Error("Remote session closed."));
|
|
1159
|
+
for (const compaction of this.pendingCompactions.splice(0))
|
|
1160
|
+
compaction.reject(new Error("Remote session closed."));
|
|
1161
|
+
}
|
|
1162
|
+
async sendPrompt(text, streamingBehavior) {
|
|
1163
|
+
await this.transport.sendPrompt(this.context, this.runId, text, streamingBehavior);
|
|
1164
|
+
}
|
|
1165
|
+
async sendCommand(text) {
|
|
1166
|
+
const result = await this.transport.runCommand(this.context, this.runId, text);
|
|
1167
|
+
return typeof result.message === "string" ? result.message : "worker command accepted";
|
|
1168
|
+
}
|
|
1169
|
+
async sendShell(text) {
|
|
1170
|
+
await this.transport.sendShell(this.context, this.runId, text);
|
|
1171
|
+
}
|
|
1172
|
+
async abort() {
|
|
1173
|
+
await this.transport.abort(this.context, this.runId);
|
|
1174
|
+
}
|
|
1175
|
+
registerPendingShell(shell) {
|
|
1176
|
+
this.pendingShells.push(shell);
|
|
1177
|
+
}
|
|
1178
|
+
failPendingShell(shell, error) {
|
|
1179
|
+
const index = this.pendingShells.indexOf(shell);
|
|
1180
|
+
if (index !== -1)
|
|
1181
|
+
this.pendingShells.splice(index, 1);
|
|
1182
|
+
shell.reject(error);
|
|
1183
|
+
}
|
|
1184
|
+
registerPendingCompaction(pending) {
|
|
1185
|
+
this.pendingCompactions.push(pending);
|
|
1186
|
+
}
|
|
1187
|
+
async waitForReady() {
|
|
1188
|
+
const startedAt = Date.now();
|
|
1189
|
+
const deadline = startedAt + resolveAttachReadyTimeoutMs();
|
|
1190
|
+
let consecutiveFailures = 0;
|
|
1191
|
+
while (!this.closed) {
|
|
1192
|
+
let requestFailed = false;
|
|
1193
|
+
const session = await this.transport.getSession(this.context, this.runId).catch((error) => {
|
|
1194
|
+
requestFailed = true;
|
|
1195
|
+
return { ready: false, status: error instanceof Error ? error.message : String(error), retryAfterMs: 1000 };
|
|
1196
|
+
});
|
|
1197
|
+
if (session.ready !== false)
|
|
1198
|
+
return true;
|
|
1199
|
+
consecutiveFailures = requestFailed ? consecutiveFailures + 1 : 0;
|
|
1200
|
+
const status = String(session.status ?? "starting");
|
|
1201
|
+
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
1202
|
+
this.hooks.onError?.(`Run ended before the worker Pi daemon became ready: ${status}. Inspect with \`rig run show ${this.runId}\`.`);
|
|
1203
|
+
return false;
|
|
1204
|
+
}
|
|
1205
|
+
this.hooks.onStatusText?.(consecutiveFailures >= 5 ? "Rig server unreachable \xB7 retrying \xB7 /detach to exit" : `waiting for worker Pi daemon \xB7 ${status} \xB7 /detach to exit`);
|
|
1206
|
+
if (Date.now() >= deadline) {
|
|
1207
|
+
this.hooks.onError?.(`Worker Pi daemon did not become ready (last status: ${status}). Set RIG_PI_ATTACH_TIMEOUT_MS to wait longer.`);
|
|
1208
|
+
return false;
|
|
1209
|
+
}
|
|
1210
|
+
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
1211
|
+
}
|
|
1212
|
+
return false;
|
|
1213
|
+
}
|
|
1214
|
+
applyEnvelope(envelopeValue) {
|
|
1215
|
+
const envelope = recordOf(envelopeValue);
|
|
1216
|
+
if (!envelope)
|
|
1217
|
+
return;
|
|
1218
|
+
const type = String(envelope.type ?? "");
|
|
1219
|
+
if (type === "status.update") {
|
|
1220
|
+
this.applyStatusPayload(envelope);
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
if (type === "activity.update") {
|
|
1224
|
+
const activity = recordOf(envelope.activity);
|
|
1225
|
+
this.hooks.onActivity?.(String(activity?.label ?? ""), activity?.detail ? String(activity.detail) : undefined);
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
if (type === "extension_ui_request") {
|
|
1229
|
+
const request = recordOf(envelope.request);
|
|
1230
|
+
if (request)
|
|
1231
|
+
this.hooks.onExtensionUiRequest?.(request);
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
if (type === "pi.ui_event") {
|
|
1235
|
+
this.applyShellUiEvent(envelope.event);
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
if (type === "pi.event") {
|
|
1239
|
+
this.session?.handleRemoteSessionEvent(envelope.event);
|
|
1240
|
+
this.settlePendingCompaction(envelope.event);
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (type === "error") {
|
|
1244
|
+
this.hooks.onError?.(String(envelope.message ?? envelope.detail ?? "unknown worker error"));
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
applyStatusPayload(payload) {
|
|
1248
|
+
const status = recordOf(payload.status) ?? payload;
|
|
1249
|
+
const next = this.status;
|
|
1250
|
+
next.isStreaming = status.isStreaming === true;
|
|
1251
|
+
next.isCompacting = status.isCompacting === true;
|
|
1252
|
+
next.isBashRunning = status.isBashRunning === true;
|
|
1253
|
+
next.pendingMessageCount = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
1254
|
+
next.steeringMessages = Array.isArray(status.steeringMessages) ? status.steeringMessages.map(String) : [];
|
|
1255
|
+
next.followUpMessages = Array.isArray(status.followUpMessages) ? status.followUpMessages.map(String) : [];
|
|
1256
|
+
next.model = recordOf(status.model) ?? next.model;
|
|
1257
|
+
next.thinkingLevel = typeof status.thinkingLevel === "string" ? status.thinkingLevel : next.thinkingLevel;
|
|
1258
|
+
next.sessionName = typeof status.sessionName === "string" ? status.sessionName : next.sessionName;
|
|
1259
|
+
next.cwd = typeof status.cwd === "string" ? status.cwd : next.cwd;
|
|
1260
|
+
next.stats = recordOf(status.stats) ?? next.stats;
|
|
1261
|
+
next.contextUsage = recordOf(status.contextUsage) ?? next.contextUsage;
|
|
1262
|
+
}
|
|
1263
|
+
applyShellUiEvent(value) {
|
|
1264
|
+
const event = recordOf(value);
|
|
1265
|
+
if (!event)
|
|
1266
|
+
return;
|
|
1267
|
+
const type = String(event.type ?? "");
|
|
1268
|
+
const pending = this.pendingShells[0];
|
|
1269
|
+
if (type === "shell.chunk" && pending) {
|
|
1270
|
+
pending.sawChunk = true;
|
|
1271
|
+
pending.onData(Buffer.from(String(event.chunk ?? "")));
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
if (type === "shell.end" && pending) {
|
|
1275
|
+
const output = String(event.output ?? "");
|
|
1276
|
+
if (output && !pending.sawChunk)
|
|
1277
|
+
pending.onData(Buffer.from(output));
|
|
1278
|
+
const index = this.pendingShells.indexOf(pending);
|
|
1279
|
+
if (index !== -1)
|
|
1280
|
+
this.pendingShells.splice(index, 1);
|
|
1281
|
+
pending.resolve({ exitCode: typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0 });
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
settlePendingCompaction(eventValue) {
|
|
1285
|
+
const event = recordOf(eventValue);
|
|
1286
|
+
if (!event)
|
|
1287
|
+
return;
|
|
1288
|
+
const type = String(event.type ?? "");
|
|
1289
|
+
if (type !== "compaction_end" || this.pendingCompactions.length === 0)
|
|
1290
|
+
return;
|
|
1291
|
+
const pending = this.pendingCompactions.shift();
|
|
1292
|
+
const result = recordOf(event.result);
|
|
1293
|
+
if (result)
|
|
1294
|
+
pending.resolve(result);
|
|
1295
|
+
else if (event.aborted === true)
|
|
1296
|
+
pending.reject(new Error("Compaction aborted on the worker."));
|
|
1297
|
+
else
|
|
1298
|
+
pending.resolve({});
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
class RigRemoteAgentSession extends PiAgentSession {
|
|
1303
|
+
remote;
|
|
1304
|
+
constructor(config, remote) {
|
|
1305
|
+
super(config);
|
|
1306
|
+
this.remote = remote;
|
|
1307
|
+
remote.bindSession(this);
|
|
1308
|
+
}
|
|
1309
|
+
handleRemoteSessionEvent(eventValue) {
|
|
1310
|
+
const event = recordOf(eventValue);
|
|
1311
|
+
if (!event)
|
|
1312
|
+
return;
|
|
1313
|
+
const type = String(event.type ?? "");
|
|
1314
|
+
if ((type === "message_end" || type === "turn_end") && recordOf(event.message)) {
|
|
1315
|
+
this.agent.state.messages = [...this.agent.state.messages, event.message];
|
|
1316
|
+
}
|
|
1317
|
+
this._emit(eventValue);
|
|
1318
|
+
}
|
|
1319
|
+
replaceRemoteMessages(messages) {
|
|
1320
|
+
this.agent.state.messages = messages;
|
|
1321
|
+
}
|
|
1322
|
+
async expandLocalInput(text) {
|
|
1323
|
+
let current = text;
|
|
1324
|
+
const runner = this.extensionRunner;
|
|
1325
|
+
if (runner.hasHandlers("input")) {
|
|
1326
|
+
const result = await runner.emitInput(current, undefined, "interactive");
|
|
1327
|
+
if (result.action === "handled")
|
|
1328
|
+
return null;
|
|
1329
|
+
if (result.action === "transform")
|
|
1330
|
+
current = result.text;
|
|
1331
|
+
}
|
|
1332
|
+
current = this._expandSkillCommand(current);
|
|
1333
|
+
current = expandPromptTemplate(current, [...this.promptTemplates]);
|
|
1334
|
+
return current;
|
|
1335
|
+
}
|
|
1336
|
+
async prompt(text, options) {
|
|
1337
|
+
const trimmed = text.trim();
|
|
1338
|
+
if (!trimmed)
|
|
1339
|
+
return;
|
|
1340
|
+
if (trimmed.startsWith("/")) {
|
|
1341
|
+
if (await this._tryExecuteExtensionCommand(trimmed))
|
|
1342
|
+
return;
|
|
1343
|
+
const expanded2 = await this.expandLocalInput(trimmed);
|
|
1344
|
+
if (expanded2 === null)
|
|
1345
|
+
return;
|
|
1346
|
+
if (expanded2 !== trimmed) {
|
|
1347
|
+
const behavior2 = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
1348
|
+
options?.preflightResult?.(true);
|
|
1349
|
+
await this.remote.sendPrompt(expanded2, behavior2);
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
await this.remote.sendCommand(trimmed);
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
if (trimmed.startsWith("!")) {
|
|
1356
|
+
await this.remote.sendShell(trimmed);
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
const expanded = await this.expandLocalInput(trimmed);
|
|
1360
|
+
if (expanded === null)
|
|
1361
|
+
return;
|
|
1362
|
+
const behavior = options?.streamingBehavior ?? (this.isStreaming || this.isCompacting ? "steer" : undefined);
|
|
1363
|
+
options?.preflightResult?.(true);
|
|
1364
|
+
await this.remote.sendPrompt(expanded, behavior);
|
|
1365
|
+
}
|
|
1366
|
+
async steer(text) {
|
|
1367
|
+
const trimmed = text.trim();
|
|
1368
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
1369
|
+
return;
|
|
1370
|
+
const expanded = await this.expandLocalInput(trimmed);
|
|
1371
|
+
if (expanded === null)
|
|
1372
|
+
return;
|
|
1373
|
+
await this.remote.sendPrompt(expanded, "steer");
|
|
1374
|
+
}
|
|
1375
|
+
async followUp(text) {
|
|
1376
|
+
const trimmed = text.trim();
|
|
1377
|
+
if (trimmed.startsWith("/") && await this._tryExecuteExtensionCommand(trimmed))
|
|
1378
|
+
return;
|
|
1379
|
+
const expanded = await this.expandLocalInput(trimmed);
|
|
1380
|
+
if (expanded === null)
|
|
1381
|
+
return;
|
|
1382
|
+
await this.remote.sendPrompt(expanded, "followUp");
|
|
1383
|
+
}
|
|
1384
|
+
async abort() {
|
|
1385
|
+
await this.remote.abort();
|
|
1386
|
+
}
|
|
1387
|
+
async compact(customInstructions) {
|
|
1388
|
+
const pending = new Promise((resolve3, reject) => {
|
|
1389
|
+
this.remote.registerPendingCompaction({ resolve: resolve3, reject });
|
|
1390
|
+
});
|
|
1391
|
+
await this.remote.sendCommand(`/compact${customInstructions ? ` ${customInstructions}` : ""}`);
|
|
1392
|
+
return pending;
|
|
1393
|
+
}
|
|
1394
|
+
clearQueue() {
|
|
1395
|
+
const cleared = {
|
|
1396
|
+
steering: [...this.remote.status.steeringMessages],
|
|
1397
|
+
followUp: [...this.remote.status.followUpMessages]
|
|
1398
|
+
};
|
|
1399
|
+
this.remote.status.steeringMessages = [];
|
|
1400
|
+
this.remote.status.followUpMessages = [];
|
|
1401
|
+
this.remote.status.pendingMessageCount = 0;
|
|
1402
|
+
this.remote.sendCommand("/queue-clear").catch(() => {});
|
|
1403
|
+
return cleared;
|
|
1404
|
+
}
|
|
1405
|
+
get isStreaming() {
|
|
1406
|
+
return this.remote.status.isStreaming;
|
|
1407
|
+
}
|
|
1408
|
+
get isCompacting() {
|
|
1409
|
+
return this.remote.status.isCompacting;
|
|
1410
|
+
}
|
|
1411
|
+
get isBashRunning() {
|
|
1412
|
+
return this.remote.status.isBashRunning;
|
|
1413
|
+
}
|
|
1414
|
+
get pendingMessageCount() {
|
|
1415
|
+
return this.remote.status.pendingMessageCount;
|
|
1416
|
+
}
|
|
1417
|
+
getSteeringMessages() {
|
|
1418
|
+
return this.remote.status.steeringMessages;
|
|
1419
|
+
}
|
|
1420
|
+
getFollowUpMessages() {
|
|
1421
|
+
return this.remote.status.followUpMessages;
|
|
1422
|
+
}
|
|
1423
|
+
get model() {
|
|
1424
|
+
return this.remote.status.model ?? super.model;
|
|
1425
|
+
}
|
|
1426
|
+
async setModel(model) {
|
|
1427
|
+
await this.remote.sendCommand(`/model ${model.provider}/${model.id}`);
|
|
1428
|
+
this.remote.status.model = model;
|
|
1429
|
+
}
|
|
1430
|
+
get thinkingLevel() {
|
|
1431
|
+
return this.remote.status.thinkingLevel ?? super.thinkingLevel;
|
|
1432
|
+
}
|
|
1433
|
+
setThinkingLevel(level) {
|
|
1434
|
+
this.remote.status.thinkingLevel = level;
|
|
1435
|
+
this.remote.sendCommand(`/thinking ${level}`).catch(() => {});
|
|
1436
|
+
}
|
|
1437
|
+
get sessionName() {
|
|
1438
|
+
return this.remote.status.sessionName ?? super.sessionName;
|
|
1439
|
+
}
|
|
1440
|
+
setSessionName(name) {
|
|
1441
|
+
this.remote.status.sessionName = name;
|
|
1442
|
+
this.remote.sendCommand(`/name ${name}`).catch(() => {});
|
|
1443
|
+
}
|
|
1444
|
+
getSessionStats() {
|
|
1445
|
+
return this.remote.status.stats ?? super.getSessionStats();
|
|
1446
|
+
}
|
|
1447
|
+
getContextUsage() {
|
|
1448
|
+
return this.remote.status.contextUsage ?? super.getContextUsage();
|
|
1449
|
+
}
|
|
1450
|
+
dispose() {
|
|
1451
|
+
this.remote.close();
|
|
1452
|
+
super.dispose();
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
function createRemoteBashOperations(controller, excludeFromContext) {
|
|
1456
|
+
return {
|
|
1457
|
+
exec(command, _cwd, execOptions) {
|
|
1458
|
+
return new Promise((resolve3, reject) => {
|
|
1459
|
+
const pending = { onData: execOptions.onData, resolve: resolve3, reject, sawChunk: false };
|
|
1460
|
+
const cleanup = () => {
|
|
1461
|
+
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
1462
|
+
if (timer)
|
|
1463
|
+
clearTimeout(timer);
|
|
1464
|
+
};
|
|
1465
|
+
const onAbort = () => {
|
|
1466
|
+
cleanup();
|
|
1467
|
+
controller.failPendingShell(pending, new Error("Remote worker shell command aborted locally."));
|
|
1468
|
+
};
|
|
1469
|
+
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
1470
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
1471
|
+
cleanup();
|
|
1472
|
+
controller.failPendingShell(pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
1473
|
+
}, timeoutMs) : null;
|
|
1474
|
+
const wrappedResolve = pending.resolve;
|
|
1475
|
+
const wrappedReject = pending.reject;
|
|
1476
|
+
pending.resolve = (result) => {
|
|
1477
|
+
cleanup();
|
|
1478
|
+
wrappedResolve(result);
|
|
1479
|
+
};
|
|
1480
|
+
pending.reject = (error) => {
|
|
1481
|
+
cleanup();
|
|
1482
|
+
wrappedReject(error);
|
|
1483
|
+
};
|
|
1484
|
+
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1485
|
+
controller.registerPendingShell(pending);
|
|
1486
|
+
controller.sendShell(`${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
1487
|
+
cleanup();
|
|
1488
|
+
controller.failPendingShell(pending, error instanceof Error ? error : new Error(String(error)));
|
|
1489
|
+
});
|
|
1490
|
+
});
|
|
1491
|
+
}
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// packages/cli/src/commands/_spinner.ts
|
|
1496
|
+
var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
1497
|
+
|
|
1498
|
+
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
1499
|
+
function recordOf2(value) {
|
|
1500
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1501
|
+
}
|
|
1502
|
+
function asText(value) {
|
|
1503
|
+
if (typeof value === "string")
|
|
1504
|
+
return value;
|
|
1505
|
+
if (value === null || value === undefined)
|
|
1506
|
+
return "";
|
|
1507
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1508
|
+
return String(value);
|
|
1509
|
+
try {
|
|
1510
|
+
return JSON.stringify(value);
|
|
1511
|
+
} catch {
|
|
1512
|
+
return String(value);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
function names(value, key = "name") {
|
|
1516
|
+
if (!Array.isArray(value))
|
|
1517
|
+
return [];
|
|
1518
|
+
return value.flatMap((entry) => {
|
|
1519
|
+
if (typeof entry === "string")
|
|
1520
|
+
return [entry];
|
|
1521
|
+
const record = recordOf2(entry);
|
|
1522
|
+
const name = record?.[key];
|
|
1523
|
+
return typeof name === "string" ? [name] : [];
|
|
777
1524
|
});
|
|
778
|
-
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
779
|
-
`);
|
|
780
1525
|
}
|
|
1526
|
+
function renderWorkerCapabilities(capabilities) {
|
|
1527
|
+
const lines = ["Worker session capabilities (in effect for this run)"];
|
|
1528
|
+
const tools = Array.isArray(capabilities.tools) ? capabilities.tools : [];
|
|
1529
|
+
const activeTools = tools.flatMap((tool) => {
|
|
1530
|
+
const record = recordOf2(tool);
|
|
1531
|
+
return record && record.active === true && typeof record.name === "string" ? [record.name] : [];
|
|
1532
|
+
});
|
|
1533
|
+
const inactiveCount = tools.length - activeTools.length;
|
|
1534
|
+
lines.push(` tools ${activeTools.join(", ") || "(none)"}${inactiveCount > 0 ? ` (+${inactiveCount} inactive)` : ""}`);
|
|
1535
|
+
const extensions = Array.isArray(capabilities.extensions) ? capabilities.extensions : [];
|
|
1536
|
+
const extensionLabels = extensions.flatMap((entry) => {
|
|
1537
|
+
const record = recordOf2(entry);
|
|
1538
|
+
if (!record)
|
|
1539
|
+
return [];
|
|
1540
|
+
const path = typeof record.path === "string" ? record.path : "";
|
|
1541
|
+
const short = path.split("/").filter(Boolean).slice(-2).join("/") || path || "extension";
|
|
1542
|
+
return [short];
|
|
1543
|
+
});
|
|
1544
|
+
lines.push(` extensions ${extensionLabels.join(", ") || "(none)"}`);
|
|
1545
|
+
const hookEvents = names(capabilities.hookEvents);
|
|
1546
|
+
const hookList = Array.isArray(capabilities.hookEvents) ? capabilities.hookEvents.map(asText).filter(Boolean) : hookEvents;
|
|
1547
|
+
lines.push(` hooks ${hookList.join(", ") || "(none)"}`);
|
|
1548
|
+
lines.push(` skills ${names(capabilities.skills).join(", ") || "(none)"}`);
|
|
1549
|
+
lines.push(` prompts ${names(capabilities.prompts).join(", ") || "(none)"}`);
|
|
1550
|
+
const model = typeof capabilities.model === "string" ? capabilities.model : "(unknown)";
|
|
1551
|
+
const thinking = typeof capabilities.thinkingLevel === "string" ? capabilities.thinkingLevel : "";
|
|
1552
|
+
const cwd = typeof capabilities.cwd === "string" ? capabilities.cwd : "";
|
|
1553
|
+
lines.push(` model ${model}${thinking ? ` \xB7 ${thinking}` : ""}`);
|
|
1554
|
+
if (cwd)
|
|
1555
|
+
lines.push(` cwd ${cwd}`);
|
|
1556
|
+
lines.push(" (worker commands are in your palette as [worker \u2026] \xB7 /worker shows this again)");
|
|
1557
|
+
return lines;
|
|
1558
|
+
}
|
|
1559
|
+
async function answerExtensionUiRequest(options, ctx, request) {
|
|
1560
|
+
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
1561
|
+
const method = String(request.method ?? request.type ?? "input");
|
|
1562
|
+
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
1563
|
+
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
1564
|
+
const choices = rawOptions.map((option) => {
|
|
1565
|
+
const record = recordOf2(option);
|
|
1566
|
+
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
1567
|
+
}).filter(Boolean);
|
|
1568
|
+
try {
|
|
1569
|
+
if (method === "confirm") {
|
|
1570
|
+
const confirmed = await ctx.ui.confirm("Worker request", prompt);
|
|
1571
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, { value: confirmed, confirmed });
|
|
1572
|
+
return;
|
|
1573
|
+
}
|
|
1574
|
+
if (choices.length > 0) {
|
|
1575
|
+
const selected = await ctx.ui.select(prompt, choices);
|
|
1576
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, selected === undefined ? { cancelled: true } : { value: selected });
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
const value = await ctx.ui.input("Worker request", prompt);
|
|
1580
|
+
await respondRunPiExtensionUiViaServer(options.context, options.runId, requestId, value === undefined ? { cancelled: true } : { value });
|
|
1581
|
+
} catch (error) {
|
|
1582
|
+
ctx.ui.notify(`Failed to answer worker UI request: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
var LOCALLY_OWNED_COMMANDS = new Set(["detach", "quit", "q", "stop", "worker", "settings", "model", "thinking", "compact", "session", "name", "reload"]);
|
|
1586
|
+
function registerDaemonCommands(pi, options, ctx, commands, registered) {
|
|
1587
|
+
for (const command of commands) {
|
|
1588
|
+
const record = recordOf2(command);
|
|
1589
|
+
const name = typeof record?.name === "string" ? record.name : "";
|
|
1590
|
+
const source = typeof record?.source === "string" ? record.source : "worker";
|
|
1591
|
+
if (!name || source === "builtin" || registered.has(name) || LOCALLY_OWNED_COMMANDS.has(name))
|
|
1592
|
+
continue;
|
|
1593
|
+
registered.add(name);
|
|
1594
|
+
const description = typeof record?.description === "string" ? record.description : undefined;
|
|
1595
|
+
try {
|
|
1596
|
+
pi.registerCommand(name, {
|
|
1597
|
+
description: `[worker ${source}] ${description ?? ""}`.trim(),
|
|
1598
|
+
handler: async (args) => {
|
|
1599
|
+
try {
|
|
1600
|
+
const message2 = await options.controller.sendCommand(`/${name}${args ? ` ${args}` : ""}`);
|
|
1601
|
+
ctx.ui.notify(message2, "info");
|
|
1602
|
+
} catch (error) {
|
|
1603
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
});
|
|
1607
|
+
} catch {}
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
function createRigWorkerPiBridgeExtension(options) {
|
|
1611
|
+
return (pi) => {
|
|
1612
|
+
const registeredDaemonCommands = new Set;
|
|
1613
|
+
let capabilityLines = null;
|
|
1614
|
+
let statusText = "connecting to worker session";
|
|
1615
|
+
let busy = true;
|
|
1616
|
+
let connected = false;
|
|
1617
|
+
let frame = 0;
|
|
1618
|
+
let spinnerTimer = null;
|
|
1619
|
+
const renderStatus = (ctx) => {
|
|
1620
|
+
const prefix = busy ? `${SPINNER_FRAMES[frame]} ` : connected ? "\u25CF " : "\u25CB ";
|
|
1621
|
+
ctx.ui.setStatus("rig-worker-pi", `${prefix}${statusText}`);
|
|
1622
|
+
};
|
|
1623
|
+
const setStatus = (ctx, text, isBusy) => {
|
|
1624
|
+
statusText = text;
|
|
1625
|
+
busy = isBusy;
|
|
1626
|
+
renderStatus(ctx);
|
|
1627
|
+
};
|
|
1628
|
+
pi.registerCommand("detach", {
|
|
1629
|
+
description: "Detach from this run; the worker keeps going",
|
|
1630
|
+
handler: async (_args, ctx) => {
|
|
1631
|
+
ctx.ui.notify("Detached locally; the worker Pi daemon continues.", "info");
|
|
1632
|
+
ctx.shutdown();
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
pi.registerCommand("stop", {
|
|
1636
|
+
description: "Stop the worker Pi run and detach",
|
|
1637
|
+
handler: async (_args, ctx) => {
|
|
1638
|
+
await options.controller.abort();
|
|
1639
|
+
ctx.ui.notify("Stop requested for the worker Pi daemon.", "info");
|
|
1640
|
+
ctx.shutdown();
|
|
1641
|
+
}
|
|
1642
|
+
});
|
|
1643
|
+
pi.registerCommand("worker", {
|
|
1644
|
+
description: "Show the worker session's real capabilities (tools, extensions, hooks, skills)",
|
|
1645
|
+
handler: async (_args, ctx) => {
|
|
1646
|
+
if (capabilityLines)
|
|
1647
|
+
ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
|
|
1648
|
+
else
|
|
1649
|
+
ctx.ui.notify("Worker capabilities are not available yet (still connecting).", "info");
|
|
1650
|
+
}
|
|
1651
|
+
});
|
|
1652
|
+
pi.on("user_bash", (event) => ({
|
|
1653
|
+
operations: createRemoteBashOperations(options.controller, event.excludeFromContext === true)
|
|
1654
|
+
}));
|
|
1655
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1656
|
+
ctx.ui.setTitle("Rig \xB7 enriched bundled Pi");
|
|
1657
|
+
setStatus(ctx, "waiting for worker Pi daemon", true);
|
|
1658
|
+
spinnerTimer = setInterval(() => {
|
|
1659
|
+
frame = (frame + 1) % SPINNER_FRAMES.length;
|
|
1660
|
+
if (busy)
|
|
1661
|
+
renderStatus(ctx);
|
|
1662
|
+
}, 150);
|
|
1663
|
+
ctx.ui.notify(`Enriched bundled Pi \u2014 native UI + Rig layers, worker brain. Attached to run ${options.runId}. /worker shows live capabilities \xB7 /detach exits \xB7 /stop cancels.`, "info");
|
|
1664
|
+
if (options.initialMessageSent)
|
|
1665
|
+
ctx.ui.notify("Initial message sent to the worker Pi daemon.", "info");
|
|
1666
|
+
const nativeUi = ctx.ui;
|
|
1667
|
+
options.controller.setUiHooks({
|
|
1668
|
+
onStatusText: (text) => setStatus(ctx, text, !connected),
|
|
1669
|
+
onActivity: (label, detail) => {
|
|
1670
|
+
const active = label !== "idle" && !/complete|ready/i.test(label);
|
|
1671
|
+
setStatus(ctx, [label, detail].filter(Boolean).join(" \u2014 "), active);
|
|
1672
|
+
if (/agent running|tool:/.test(label))
|
|
1673
|
+
ctx.ui.setWidget("rig-worker-capabilities", undefined);
|
|
1674
|
+
},
|
|
1675
|
+
onConnectionChange: (nextConnected) => {
|
|
1676
|
+
connected = nextConnected;
|
|
1677
|
+
setStatus(ctx, nextConnected ? "worker session live" : "worker session disconnected", false);
|
|
1678
|
+
},
|
|
1679
|
+
onError: (message2) => ctx.ui.notify(message2, "error"),
|
|
1680
|
+
onExtensionUiRequest: (request) => {
|
|
1681
|
+
answerExtensionUiRequest(options, ctx, request);
|
|
1682
|
+
},
|
|
1683
|
+
onCatchUp: (messages, commands, capabilities) => {
|
|
1684
|
+
if (nativeUi.appendSessionMessages)
|
|
1685
|
+
nativeUi.appendSessionMessages(messages);
|
|
1686
|
+
const cwd = options.controller.status.cwd;
|
|
1687
|
+
if (nativeUi.setDisplayCwd && cwd)
|
|
1688
|
+
nativeUi.setDisplayCwd(cwd);
|
|
1689
|
+
registerDaemonCommands(pi, options, ctx, commands, registeredDaemonCommands);
|
|
1690
|
+
if (capabilities) {
|
|
1691
|
+
capabilityLines = renderWorkerCapabilities(capabilities);
|
|
1692
|
+
ctx.ui.setWidget("rig-worker-capabilities", capabilityLines, { placement: "aboveEditor" });
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
options.controller.connect().catch((error) => {
|
|
1697
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
1698
|
+
});
|
|
1699
|
+
});
|
|
1700
|
+
pi.on("session_shutdown", () => {
|
|
1701
|
+
if (spinnerTimer)
|
|
1702
|
+
clearInterval(spinnerTimer);
|
|
1703
|
+
options.controller.close();
|
|
1704
|
+
});
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
// packages/cli/src/commands/_pi-frontend.ts
|
|
1709
|
+
function setTemporaryEnv(updates) {
|
|
1710
|
+
const previous = new Map;
|
|
1711
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
1712
|
+
previous.set(key, process.env[key]);
|
|
1713
|
+
process.env[key] = value;
|
|
1714
|
+
}
|
|
1715
|
+
return () => {
|
|
1716
|
+
for (const [key, value] of previous) {
|
|
1717
|
+
if (value === undefined)
|
|
1718
|
+
delete process.env[key];
|
|
1719
|
+
else
|
|
1720
|
+
process.env[key] = value;
|
|
1721
|
+
}
|
|
1722
|
+
};
|
|
1723
|
+
}
|
|
1724
|
+
async function attachRunBundledPiFrontend(context, input) {
|
|
1725
|
+
const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
|
|
1726
|
+
const restoreEnv = setTemporaryEnv({
|
|
1727
|
+
PI_CODING_AGENT_SESSION_DIR: tempSessionDir,
|
|
1728
|
+
PI_SKIP_VERSION_CHECK: "1",
|
|
1729
|
+
PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust"
|
|
1730
|
+
});
|
|
1731
|
+
const controller = new RigRemoteSessionController({ context, runId: input.runId });
|
|
1732
|
+
const createRemoteRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent }) => {
|
|
1733
|
+
const services = await createAgentSessionServices({
|
|
1734
|
+
cwd,
|
|
1735
|
+
agentDir,
|
|
1736
|
+
resourceLoaderOptions: {
|
|
1737
|
+
extensionFactories: [
|
|
1738
|
+
createRigWorkerPiBridgeExtension({
|
|
1739
|
+
context,
|
|
1740
|
+
controller,
|
|
1741
|
+
runId: input.runId,
|
|
1742
|
+
initialMessageSent: input.steered === true
|
|
1743
|
+
})
|
|
1744
|
+
],
|
|
1745
|
+
noExtensions: true,
|
|
1746
|
+
noSkills: true,
|
|
1747
|
+
noPromptTemplates: true,
|
|
1748
|
+
noContextFiles: true
|
|
1749
|
+
}
|
|
1750
|
+
});
|
|
1751
|
+
const created = await createAgentSessionFromServices({
|
|
1752
|
+
services,
|
|
1753
|
+
sessionManager,
|
|
1754
|
+
sessionStartEvent,
|
|
1755
|
+
noTools: "all",
|
|
1756
|
+
sessionFactory: (config) => new RigRemoteAgentSession(config, controller)
|
|
1757
|
+
});
|
|
1758
|
+
return { ...created, services, diagnostics: services.diagnostics };
|
|
1759
|
+
};
|
|
1760
|
+
let detached = false;
|
|
1761
|
+
try {
|
|
1762
|
+
await runPiMain([], {
|
|
1763
|
+
createRuntimeOverride: () => createRemoteRuntime
|
|
1764
|
+
});
|
|
1765
|
+
detached = true;
|
|
1766
|
+
} finally {
|
|
1767
|
+
restoreEnv();
|
|
1768
|
+
controller.close();
|
|
1769
|
+
rmSync(tempSessionDir, { recursive: true, force: true });
|
|
1770
|
+
}
|
|
1771
|
+
let run = { runId: input.runId, status: "unknown" };
|
|
1772
|
+
try {
|
|
1773
|
+
run = await getRunDetailsViaServer(context, input.runId);
|
|
1774
|
+
} catch {}
|
|
1775
|
+
return {
|
|
1776
|
+
run,
|
|
1777
|
+
logs: [],
|
|
1778
|
+
timeline: [],
|
|
1779
|
+
timelineCursor: null,
|
|
1780
|
+
steered: input.steered === true,
|
|
1781
|
+
detached,
|
|
1782
|
+
rendered: "enriched bundled Pi frontend with remote worker session runtime"
|
|
1783
|
+
};
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1786
|
+
// packages/cli/src/commands/_operator-view.ts
|
|
1787
|
+
var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
781
1788
|
function runStatusFromPayload(payload) {
|
|
782
1789
|
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
783
1790
|
return String(run.status ?? "unknown").toLowerCase();
|
|
@@ -799,56 +1806,640 @@ async function applyOperatorCommand(context, input, deps = {}) {
|
|
|
799
1806
|
await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
|
|
800
1807
|
return { action: "continue", message: "Steering message queued." };
|
|
801
1808
|
}
|
|
802
|
-
async function readOperatorSnapshot(context, runId) {
|
|
1809
|
+
async function readOperatorSnapshot(context, runId, options = {}) {
|
|
803
1810
|
const run = await getRunDetailsViaServer(context, runId);
|
|
804
1811
|
const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
|
|
805
|
-
const
|
|
806
|
-
|
|
1812
|
+
const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
|
|
1813
|
+
entries: [{
|
|
1814
|
+
id: `timeline-unavailable:${runId}`,
|
|
1815
|
+
type: "timeline_warning",
|
|
1816
|
+
detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
|
|
1817
|
+
createdAt: new Date().toISOString()
|
|
1818
|
+
}],
|
|
1819
|
+
nextCursor: options.timelineCursor ?? null
|
|
1820
|
+
}));
|
|
1821
|
+
const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
|
|
1822
|
+
const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1823
|
+
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
1824
|
+
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
807
1825
|
}
|
|
808
1826
|
async function attachRunOperatorView(context, input) {
|
|
809
1827
|
let steered = false;
|
|
810
1828
|
if (input.message?.trim()) {
|
|
811
|
-
await steerRunViaServer(context, input.runId, input.message.trim());
|
|
1829
|
+
await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
|
|
812
1830
|
steered = true;
|
|
813
1831
|
}
|
|
1832
|
+
if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
1833
|
+
return attachRunBundledPiFrontend(context, {
|
|
1834
|
+
runId: input.runId,
|
|
1835
|
+
steered
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
814
1839
|
let snapshot = await readOperatorSnapshot(context, input.runId);
|
|
815
1840
|
if (context.outputMode === "text") {
|
|
816
|
-
|
|
1841
|
+
surface.renderSnapshot(snapshot);
|
|
1842
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1843
|
+
surface.renderLogs(snapshot.logs);
|
|
817
1844
|
if (steered)
|
|
818
|
-
|
|
1845
|
+
surface.info("Message submitted to worker Pi.");
|
|
819
1846
|
}
|
|
820
1847
|
let detached = false;
|
|
821
|
-
let
|
|
1848
|
+
let commandInput = null;
|
|
822
1849
|
if (input.follow && !input.once && context.outputMode === "text") {
|
|
823
1850
|
if (input.interactive !== false && process.stdin.isTTY) {
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
}
|
|
834
|
-
}).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
1851
|
+
surface.info("Controls: /user <message>, /stop, /detach");
|
|
1852
|
+
commandInput = surface.attachCommandInput(async (line) => {
|
|
1853
|
+
const result = await applyOperatorCommand(context, { runId: input.runId, line });
|
|
1854
|
+
if (result.message)
|
|
1855
|
+
surface.info(result.message);
|
|
1856
|
+
if (result.action === "detach" || result.action === "stopped") {
|
|
1857
|
+
detached = true;
|
|
1858
|
+
commandInput?.close();
|
|
1859
|
+
}
|
|
835
1860
|
});
|
|
836
1861
|
}
|
|
837
|
-
let lastRendered = snapshot.rendered;
|
|
838
1862
|
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
839
|
-
|
|
1863
|
+
let timelineCursor = snapshot.timelineCursor;
|
|
1864
|
+
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
840
1865
|
await Bun.sleep(pollMs);
|
|
841
|
-
snapshot = await readOperatorSnapshot(context, input.runId);
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
1866
|
+
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
1867
|
+
timelineCursor = snapshot.timelineCursor;
|
|
1868
|
+
surface.renderSnapshot(snapshot);
|
|
1869
|
+
surface.renderTimeline(snapshot.timeline);
|
|
1870
|
+
surface.renderLogs(snapshot.logs);
|
|
846
1871
|
}
|
|
847
|
-
|
|
1872
|
+
commandInput?.close();
|
|
848
1873
|
}
|
|
849
1874
|
return { ...snapshot, steered, detached };
|
|
850
1875
|
}
|
|
851
1876
|
|
|
1877
|
+
// packages/cli/src/commands/_cli-format.ts
|
|
1878
|
+
import { log, note } from "@clack/prompts";
|
|
1879
|
+
import pc from "picocolors";
|
|
1880
|
+
function stringField(record, key, fallback = "") {
|
|
1881
|
+
const value = record[key];
|
|
1882
|
+
return typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
1883
|
+
}
|
|
1884
|
+
function numberField(record, key) {
|
|
1885
|
+
const value = record[key];
|
|
1886
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1887
|
+
}
|
|
1888
|
+
function arrayField(record, key) {
|
|
1889
|
+
const value = record[key];
|
|
1890
|
+
return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
|
|
1891
|
+
}
|
|
1892
|
+
function rawObject(record) {
|
|
1893
|
+
const raw = record.raw;
|
|
1894
|
+
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
1895
|
+
}
|
|
1896
|
+
function truncate(value, width) {
|
|
1897
|
+
if (value.length <= width)
|
|
1898
|
+
return value;
|
|
1899
|
+
if (width <= 1)
|
|
1900
|
+
return "\u2026";
|
|
1901
|
+
return `${value.slice(0, width - 1)}\u2026`;
|
|
1902
|
+
}
|
|
1903
|
+
function pad(value, width) {
|
|
1904
|
+
return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
|
|
1905
|
+
}
|
|
1906
|
+
function statusColor(status) {
|
|
1907
|
+
const normalized = status.toLowerCase();
|
|
1908
|
+
if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved"].includes(normalized))
|
|
1909
|
+
return pc.green;
|
|
1910
|
+
if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
|
|
1911
|
+
return pc.red;
|
|
1912
|
+
if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
|
|
1913
|
+
return pc.cyan;
|
|
1914
|
+
if (["ready", "open", "queued", "created", "preparing", "local", "pending"].includes(normalized))
|
|
1915
|
+
return pc.yellow;
|
|
1916
|
+
return pc.dim;
|
|
1917
|
+
}
|
|
1918
|
+
function compactValue(value) {
|
|
1919
|
+
if (value === null || value === undefined)
|
|
1920
|
+
return "";
|
|
1921
|
+
if (typeof value === "string")
|
|
1922
|
+
return value;
|
|
1923
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1924
|
+
return String(value);
|
|
1925
|
+
if (Array.isArray(value))
|
|
1926
|
+
return value.map(compactValue).filter(Boolean).join(", ");
|
|
1927
|
+
return JSON.stringify(value);
|
|
1928
|
+
}
|
|
1929
|
+
function shouldUseClackOutput() {
|
|
1930
|
+
return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
|
|
1931
|
+
}
|
|
1932
|
+
function printFormattedOutput(message2, options = {}) {
|
|
1933
|
+
if (!shouldUseClackOutput()) {
|
|
1934
|
+
console.log(message2);
|
|
1935
|
+
return;
|
|
1936
|
+
}
|
|
1937
|
+
if (options.title)
|
|
1938
|
+
note(message2, options.title);
|
|
1939
|
+
else
|
|
1940
|
+
log.message(message2);
|
|
1941
|
+
}
|
|
1942
|
+
function formatStatusPill(status) {
|
|
1943
|
+
const label = status || "unknown";
|
|
1944
|
+
return statusColor(label)(`\u25CF ${label}`);
|
|
1945
|
+
}
|
|
1946
|
+
function formatSection(title, subtitle) {
|
|
1947
|
+
return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
|
|
1948
|
+
}
|
|
1949
|
+
function formatSuccessCard(title, rows = []) {
|
|
1950
|
+
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}`);
|
|
1951
|
+
return [formatSection(title), ...body].join(`
|
|
1952
|
+
`);
|
|
1953
|
+
}
|
|
1954
|
+
function formatNextSteps(steps) {
|
|
1955
|
+
if (steps.length === 0)
|
|
1956
|
+
return [];
|
|
1957
|
+
return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
|
|
1958
|
+
}
|
|
1959
|
+
function formatTaskList(tasks, options = {}) {
|
|
1960
|
+
if (options.raw)
|
|
1961
|
+
return tasks.map((task) => JSON.stringify(task)).join(`
|
|
1962
|
+
`);
|
|
1963
|
+
if (tasks.length === 0)
|
|
1964
|
+
return [formatSection("Tasks", "none found"), ...formatNextSteps(["Try `rig server status` to confirm the selected server.", "Relax filters or run `rig task run --title ... --initial-prompt ...` for ad hoc work."])].join(`
|
|
1965
|
+
`);
|
|
1966
|
+
const rows = tasks.map((task) => {
|
|
1967
|
+
const raw = rawObject(task);
|
|
1968
|
+
const id = stringField(task, "id", "<unknown>");
|
|
1969
|
+
const status = stringField(task, "status", "unknown");
|
|
1970
|
+
const title = stringField(task, "title", "Untitled task");
|
|
1971
|
+
const source = stringField(task, "source", stringField(raw, "source", ""));
|
|
1972
|
+
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
1973
|
+
return { id, status, title, source, labels };
|
|
1974
|
+
});
|
|
1975
|
+
const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
|
|
1976
|
+
const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
|
|
1977
|
+
const header = `${pc.bold(pad("TASK", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
|
|
1978
|
+
const body = rows.map((row) => {
|
|
1979
|
+
const labels = row.labels.length > 0 ? pc.dim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
|
|
1980
|
+
const source = row.source ? pc.dim(` ${row.source}`) : "";
|
|
1981
|
+
return [
|
|
1982
|
+
pc.bold(pad(truncate(row.id, idWidth), idWidth)),
|
|
1983
|
+
statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
|
|
1984
|
+
`${row.title}${labels}${source}`
|
|
1985
|
+
].join(" ");
|
|
1986
|
+
});
|
|
1987
|
+
return [formatSection("Tasks", `${rows.length} shown`), header, ...body, "", ...formatNextSteps(["Run one: `rig task run <id>` or `rig task run --next`", "Attach later: `rig run attach <run-id> --follow`"])].join(`
|
|
1988
|
+
`);
|
|
1989
|
+
}
|
|
1990
|
+
function formatTaskCard(task, options = {}) {
|
|
1991
|
+
const raw = rawObject(task);
|
|
1992
|
+
const id = stringField(task, "id", stringField(raw, "id", "<unknown>"));
|
|
1993
|
+
const status = stringField(task, "status", stringField(raw, "status", "unknown"));
|
|
1994
|
+
const title = stringField(task, "title", stringField(raw, "title", "Untitled task"));
|
|
1995
|
+
const source = stringField(task, "source", stringField(raw, "source", ""));
|
|
1996
|
+
const url = stringField(task, "url", stringField(raw, "url", ""));
|
|
1997
|
+
const number = numberField(task, "number") ?? numberField(raw, "number");
|
|
1998
|
+
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
1999
|
+
const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
|
|
2000
|
+
const readiness = compactValue(task.readiness ?? raw.readiness);
|
|
2001
|
+
const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
|
|
2002
|
+
const rows = [
|
|
2003
|
+
["task", pc.bold(id)],
|
|
2004
|
+
["status", formatStatusPill(status)],
|
|
2005
|
+
["title", title],
|
|
2006
|
+
["source", source],
|
|
2007
|
+
["number", number],
|
|
2008
|
+
["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
|
|
2009
|
+
["assignees", assignees.join(", ")],
|
|
2010
|
+
["readiness", readiness],
|
|
2011
|
+
["validators", validators],
|
|
2012
|
+
["url", url]
|
|
2013
|
+
];
|
|
2014
|
+
return [
|
|
2015
|
+
formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
|
|
2016
|
+
"",
|
|
2017
|
+
...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
|
|
2018
|
+
].join(`
|
|
2019
|
+
`);
|
|
2020
|
+
}
|
|
2021
|
+
function formatTaskDetails(task) {
|
|
2022
|
+
return formatTaskCard(task, { title: "Task details" });
|
|
2023
|
+
}
|
|
2024
|
+
function formatSubmittedRun(input) {
|
|
2025
|
+
const rows = [["run", pc.bold(input.runId)]];
|
|
2026
|
+
if (input.task) {
|
|
2027
|
+
const id = stringField(input.task, "id", "<unknown>");
|
|
2028
|
+
const status = stringField(input.task, "status", "unknown");
|
|
2029
|
+
const title = stringField(input.task, "title", "Untitled task");
|
|
2030
|
+
rows.push(["task", `${pc.bold(id)} ${formatStatusPill(status)} ${title}`]);
|
|
2031
|
+
}
|
|
2032
|
+
const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
|
|
2033
|
+
rows.push(["runtime", runtime]);
|
|
2034
|
+
return [
|
|
2035
|
+
formatSuccessCard("Run submitted", rows),
|
|
2036
|
+
"",
|
|
2037
|
+
...formatNextSteps([
|
|
2038
|
+
`Attach: \`rig run attach ${input.runId} --follow\``,
|
|
2039
|
+
`Inspect: \`rig run show ${input.runId}\``,
|
|
2040
|
+
input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the enriched bundled Pi (native UI + Rig layers, worker brain)."
|
|
2041
|
+
])
|
|
2042
|
+
].join(`
|
|
2043
|
+
`);
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
// packages/cli/src/commands/_help-catalog.ts
|
|
2047
|
+
import { intro, log as log2, note as note2, outro } from "@clack/prompts";
|
|
2048
|
+
import pc2 from "picocolors";
|
|
2049
|
+
var TOP_LEVEL_SECTIONS = [
|
|
2050
|
+
{
|
|
2051
|
+
title: "Start here",
|
|
2052
|
+
subtitle: "one-time setup for a repo",
|
|
2053
|
+
commands: [
|
|
2054
|
+
{ command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
|
|
2055
|
+
{ command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
|
|
2056
|
+
{ command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." }
|
|
2057
|
+
]
|
|
2058
|
+
},
|
|
2059
|
+
{
|
|
2060
|
+
title: "Work",
|
|
2061
|
+
subtitle: "find a task and put an agent on it",
|
|
2062
|
+
commands: [
|
|
2063
|
+
{ command: "rig task list", description: "What's on the board (from the selected source/server)." },
|
|
2064
|
+
{ command: "rig task next", description: "The next ready task, as a card." },
|
|
2065
|
+
{ command: "rig task run --next", description: "Dispatch an agent; interactive mode opens the native Pi session." },
|
|
2066
|
+
{ command: "rig task run <id> --detach", description: "Fire-and-forget a specific task." }
|
|
2067
|
+
]
|
|
2068
|
+
},
|
|
2069
|
+
{
|
|
2070
|
+
title: "Watch & steer",
|
|
2071
|
+
subtitle: "live runs are observable and steerable, attached or not",
|
|
2072
|
+
commands: [
|
|
2073
|
+
{ command: "rig run status", description: "Active and recent runs at a glance." },
|
|
2074
|
+
{ command: "rig run attach <id> --follow", description: "Join the live Pi session (worker keeps running if you /detach)." },
|
|
2075
|
+
{ command: "rig run steer <id> -m <text>", description: "Drop a message into a live worker without attaching." },
|
|
2076
|
+
{ command: "rig run stop <id>", description: "Cancel a running worker." }
|
|
2077
|
+
]
|
|
2078
|
+
},
|
|
2079
|
+
{
|
|
2080
|
+
title: "Unblock & gate",
|
|
2081
|
+
subtitle: "answer what workers ask; control what merges",
|
|
2082
|
+
commands: [
|
|
2083
|
+
{ command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." },
|
|
2084
|
+
{ command: "rig inbox inputs", description: "Questions workers asked (then `rig inbox respond \u2026`)." },
|
|
2085
|
+
{ command: "rig review show|set", description: "The completion review gate (Greptile is mandatory on merges)." }
|
|
2086
|
+
]
|
|
2087
|
+
},
|
|
2088
|
+
{
|
|
2089
|
+
title: "Extend",
|
|
2090
|
+
subtitle: "more Pi, more plugins",
|
|
2091
|
+
commands: [
|
|
2092
|
+
{ command: "rig pi search <term>", description: "Discover community Pi extensions on npm." },
|
|
2093
|
+
{ command: "rig pi add <pkg>", description: "Add a Pi extension to this project (workers pick it up too)." },
|
|
2094
|
+
{ command: "rig plugin list", description: "What the rig.config.ts plugins contribute." }
|
|
2095
|
+
]
|
|
2096
|
+
}
|
|
2097
|
+
];
|
|
2098
|
+
var PRIMARY_GROUPS = [
|
|
2099
|
+
{
|
|
2100
|
+
name: "server",
|
|
2101
|
+
summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
|
|
2102
|
+
usage: ["rig server <status|list|add|use|start> [options]"],
|
|
2103
|
+
commands: [
|
|
2104
|
+
{ command: "status", description: "Show the selected server for this repo.", primary: true },
|
|
2105
|
+
{ command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
|
|
2106
|
+
{ command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
|
|
2107
|
+
{ command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
|
|
2108
|
+
{ command: "list", description: "List saved local/remote server aliases.", primary: true },
|
|
2109
|
+
{ command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
|
|
2110
|
+
],
|
|
2111
|
+
examples: [
|
|
2112
|
+
"rig server status",
|
|
2113
|
+
"rig server add prod https://where.rig-does.work",
|
|
2114
|
+
"rig server use prod",
|
|
2115
|
+
"rig server use local",
|
|
2116
|
+
"rig server start --port 3773"
|
|
2117
|
+
],
|
|
2118
|
+
next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."],
|
|
2119
|
+
advanced: ["Compatibility alias: `rig connect ...` remains callable."]
|
|
2120
|
+
},
|
|
2121
|
+
{
|
|
2122
|
+
name: "task",
|
|
2123
|
+
summary: "Find work, start Pi-backed runs, and validate task results.",
|
|
2124
|
+
usage: ["rig task <list|next|show|run> [options]"],
|
|
2125
|
+
commands: [
|
|
2126
|
+
{ command: "list [--assignee <login|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
|
|
2127
|
+
{ command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
|
|
2128
|
+
{ command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
|
|
2129
|
+
{ command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
|
|
2130
|
+
{ command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
|
|
2131
|
+
{ command: "details --task <id>", description: "Show full task info from the configured source." },
|
|
2132
|
+
{ command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
|
|
2133
|
+
{ command: "reset --task <id>", description: "Compatibility spelling of `reopen --task <id>`." },
|
|
2134
|
+
{ command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
|
|
2135
|
+
{ command: "report-bug", description: "Create a structured bug report/task." }
|
|
2136
|
+
],
|
|
2137
|
+
examples: [
|
|
2138
|
+
"rig task list --assignee @me --limit 20",
|
|
2139
|
+
"rig task next",
|
|
2140
|
+
"rig task show 123 --raw",
|
|
2141
|
+
"rig task run --next",
|
|
2142
|
+
"rig task run #123 --runtime-adapter pi",
|
|
2143
|
+
"rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
|
|
2144
|
+
],
|
|
2145
|
+
next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
|
|
2146
|
+
},
|
|
2147
|
+
{
|
|
2148
|
+
name: "run",
|
|
2149
|
+
summary: "Observe, attach to, and control Rig runs.",
|
|
2150
|
+
usage: ["rig run <list|status|show|attach|stop> [options]"],
|
|
2151
|
+
commands: [
|
|
2152
|
+
{ command: "list", description: "List recent runs from the selected server or local state.", primary: true },
|
|
2153
|
+
{ command: "status", description: "Render active and recent run groups.", primary: true },
|
|
2154
|
+
{ command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
|
|
2155
|
+
{ command: "attach <run-id>|--run <id> [--follow]", description: "Attach to the run; --follow opens the enriched bundled Pi (worker brain).", primary: true },
|
|
2156
|
+
{ command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
|
|
2157
|
+
{ command: "steer <run-id> --message <text>", description: "Queue a steering message into a live worker without attaching." },
|
|
2158
|
+
{ command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events." },
|
|
2159
|
+
{ command: "resume", description: "Resume the most recent interrupted local run." },
|
|
2160
|
+
{ command: "restart", description: "Restart the most recent local run from a clean runtime." },
|
|
2161
|
+
{ command: "delete|cleanup", description: "Remove completed run records/artifacts." }
|
|
2162
|
+
],
|
|
2163
|
+
examples: [
|
|
2164
|
+
"rig run list",
|
|
2165
|
+
"rig run status",
|
|
2166
|
+
"rig run show <run-id>",
|
|
2167
|
+
"rig run attach <run-id> --follow",
|
|
2168
|
+
"rig run stop <run-id>"
|
|
2169
|
+
],
|
|
2170
|
+
next: ["Use `rig task run --next` to create a new run.", "Use `--json` when scripts need the full structured record."]
|
|
2171
|
+
},
|
|
2172
|
+
{
|
|
2173
|
+
name: "inbox",
|
|
2174
|
+
summary: "Review approval and user-input requests that block worker runs.",
|
|
2175
|
+
usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
|
|
2176
|
+
commands: [
|
|
2177
|
+
{ command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
|
|
2178
|
+
{ command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
|
|
2179
|
+
{ command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
|
|
2180
|
+
{ command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
|
|
2181
|
+
],
|
|
2182
|
+
examples: [
|
|
2183
|
+
"rig inbox approvals",
|
|
2184
|
+
"rig inbox inputs --run <run-id>",
|
|
2185
|
+
"rig inbox approve --run <run-id> --request <request-id> --decision approve"
|
|
2186
|
+
],
|
|
2187
|
+
next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
|
|
2188
|
+
},
|
|
2189
|
+
{
|
|
2190
|
+
name: "review",
|
|
2191
|
+
summary: "Inspect or change completion review gate policy.",
|
|
2192
|
+
usage: ["rig review <show|set>"],
|
|
2193
|
+
commands: [
|
|
2194
|
+
{ command: "show", description: "Show current review gate settings.", primary: true },
|
|
2195
|
+
{ command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider.", primary: true }
|
|
2196
|
+
],
|
|
2197
|
+
examples: ["rig review show", "rig review set required --provider greptile"],
|
|
2198
|
+
next: ["Use `rig inbox approvals` for blocked run handoffs."]
|
|
2199
|
+
},
|
|
2200
|
+
{
|
|
2201
|
+
name: "init",
|
|
2202
|
+
summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
|
|
2203
|
+
usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
|
|
2204
|
+
commands: [
|
|
2205
|
+
{ command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
|
|
2206
|
+
{ command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
|
|
2207
|
+
{ command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
|
|
2208
|
+
{ command: "init --repair", description: "Repair missing private state without replacing project config." }
|
|
2209
|
+
],
|
|
2210
|
+
examples: [
|
|
2211
|
+
"rig init",
|
|
2212
|
+
"rig init --yes --repo humanity-org/humanwork",
|
|
2213
|
+
"rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
|
|
2214
|
+
],
|
|
2215
|
+
next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
|
|
2216
|
+
},
|
|
2217
|
+
{
|
|
2218
|
+
name: "doctor",
|
|
2219
|
+
summary: "Diagnostics for project/server/GitHub/Pi state.",
|
|
2220
|
+
usage: ["rig doctor"],
|
|
2221
|
+
commands: [
|
|
2222
|
+
{ command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
|
|
2223
|
+
{ command: "check", description: "Compatibility spelling for diagnostics." }
|
|
2224
|
+
],
|
|
2225
|
+
examples: ["rig doctor", "rig doctor --json"],
|
|
2226
|
+
next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
|
|
2227
|
+
},
|
|
2228
|
+
{
|
|
2229
|
+
name: "github",
|
|
2230
|
+
summary: "GitHub auth helpers for the selected Rig server.",
|
|
2231
|
+
usage: ["rig github auth <status|import-gh|token>"],
|
|
2232
|
+
commands: [
|
|
2233
|
+
{ command: "auth status", description: "Show GitHub auth state.", primary: true },
|
|
2234
|
+
{ command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
|
|
2235
|
+
{ command: "auth token --token <token>", description: "Store a token on the selected server." }
|
|
2236
|
+
],
|
|
2237
|
+
examples: ["rig github auth status", "rig github auth import-gh"],
|
|
2238
|
+
next: ["After auth is valid, use `rig task run --next`."]
|
|
2239
|
+
}
|
|
2240
|
+
];
|
|
2241
|
+
var ADVANCED_GROUPS = [
|
|
2242
|
+
{ name: "connect", summary: "Compatibility alias for `rig server` selection commands.", usage: ["rig connect <status|list|add|use>"], commands: [{ command: "status|list|add|use", description: "Use `rig server ...` for the primary UX." }] },
|
|
2243
|
+
{ name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
|
|
2244
|
+
{
|
|
2245
|
+
name: "inspect",
|
|
2246
|
+
summary: "Inspect logs, artifacts, graphs, failures for a task.",
|
|
2247
|
+
usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
|
|
2248
|
+
commands: [
|
|
2249
|
+
{ command: "logs --task <id>", description: "Latest run log for a task (local or selected server)." },
|
|
2250
|
+
{ command: "artifacts --task <id>", description: "List the task's completion artifacts." },
|
|
2251
|
+
{ command: "failures --task <id>", description: "Recorded failures for a task." },
|
|
2252
|
+
{ command: "graph", description: "Task dependency graph." },
|
|
2253
|
+
{ command: "audit", description: "Controlled-command audit trail." },
|
|
2254
|
+
{ command: "diff --task <id>", description: "Changed files for a task." }
|
|
2255
|
+
]
|
|
2256
|
+
},
|
|
2257
|
+
{ name: "repo", summary: "Repository sync/baseline helpers.", usage: ["rig repo <sync|reset-baseline>"], commands: [{ command: "sync", description: "Sync project repository state." }] },
|
|
2258
|
+
{ name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
|
|
2259
|
+
{
|
|
2260
|
+
name: "browser",
|
|
2261
|
+
summary: "Browser/app diagnostics for browser-required tasks.",
|
|
2262
|
+
usage: ["rig browser <help|explain|demo|app|hp-next> [options]"],
|
|
2263
|
+
commands: [
|
|
2264
|
+
{ command: "help", description: "Rich browser command help (canonical: `rig browser help`)." },
|
|
2265
|
+
{ command: "explain", description: "Explain the browser-required task contract." },
|
|
2266
|
+
{ command: "demo", description: "Run browser demo flows against a local page." },
|
|
2267
|
+
{ command: "app", description: "Launch the Rig Browser workstation app." },
|
|
2268
|
+
{ command: "hp-next <dev|check|e2e|reset>", description: "Drive the hp-next browser test harness." }
|
|
2269
|
+
]
|
|
2270
|
+
},
|
|
2271
|
+
{
|
|
2272
|
+
name: "pi",
|
|
2273
|
+
summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
|
|
2274
|
+
usage: ["rig pi <list|add|remove|search> [args]"],
|
|
2275
|
+
commands: [
|
|
2276
|
+
{ command: "list", description: "Show project and user Pi extension packages." },
|
|
2277
|
+
{ command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
|
|
2278
|
+
{ command: "remove <source>", description: "Remove an operator-added Pi extension." },
|
|
2279
|
+
{ command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
|
|
2280
|
+
],
|
|
2281
|
+
examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
|
|
2282
|
+
next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
|
|
2283
|
+
},
|
|
2284
|
+
{
|
|
2285
|
+
name: "plugin",
|
|
2286
|
+
summary: "Plugin listing, validation, and plugin-contributed commands.",
|
|
2287
|
+
usage: ["rig plugin <list|validate|run> [options]"],
|
|
2288
|
+
commands: [
|
|
2289
|
+
{ command: "list", description: "List plugins declared in rig.config.ts and their contributions." },
|
|
2290
|
+
{ command: "validate --task <id>", description: "Run plugin-contributed validators for a task." },
|
|
2291
|
+
{ command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
|
|
2292
|
+
]
|
|
2293
|
+
},
|
|
2294
|
+
{ name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
|
|
2295
|
+
{ name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
|
|
2296
|
+
{ name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
|
|
2297
|
+
{ name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
|
|
2298
|
+
{ name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
|
|
2299
|
+
{ name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
|
|
2300
|
+
{ name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
|
|
2301
|
+
{ name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
|
|
2302
|
+
{ name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
|
|
2303
|
+
];
|
|
2304
|
+
var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
|
|
2305
|
+
function heading(title) {
|
|
2306
|
+
return pc2.bold(pc2.cyan(title));
|
|
2307
|
+
}
|
|
2308
|
+
function renderRigBanner(version) {
|
|
2309
|
+
const m = (s) => pc2.bold(pc2.magenta(s));
|
|
2310
|
+
const c = (s) => pc2.bold(pc2.cyan(s));
|
|
2311
|
+
const y = (s) => pc2.yellow(s);
|
|
2312
|
+
const d = (s) => pc2.dim(s);
|
|
2313
|
+
const lines = [
|
|
2314
|
+
m(" \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ") + d(" \u2591\u2592\u2593\u2588 "),
|
|
2315
|
+
m(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D ") + d("\u2593\u2592\u2591"),
|
|
2316
|
+
c(" \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557") + d(" \u2591\u2592"),
|
|
2317
|
+
c(" \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551") + d(" \u2588\u2593\u2591"),
|
|
2318
|
+
y(" \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D") + d(" \u2592\u2591"),
|
|
2319
|
+
y(" \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D "),
|
|
2320
|
+
"",
|
|
2321
|
+
` ${c("\u25E2\u25E4")} ${pc2.bold("the control rig for autonomous coding agents")} ${m("//")} ${d("you are the operator")}`,
|
|
2322
|
+
version ? ` ${d(`v${version} \xB7 jack in: rig task run --next`)}` : ` ${d("jack in: rig task run --next")}`
|
|
2323
|
+
];
|
|
2324
|
+
return lines.join(`
|
|
2325
|
+
`);
|
|
2326
|
+
}
|
|
2327
|
+
function commandLine(command, description) {
|
|
2328
|
+
const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
|
|
2329
|
+
return `${pc2.dim("\u2502")} ${pc2.bold(commandColumn)} ${description}`;
|
|
2330
|
+
}
|
|
2331
|
+
function renderCommandBlock(commands) {
|
|
2332
|
+
return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
|
|
2333
|
+
`);
|
|
2334
|
+
}
|
|
2335
|
+
function renderGroup(group) {
|
|
2336
|
+
const lines = [
|
|
2337
|
+
`${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
|
|
2338
|
+
"",
|
|
2339
|
+
pc2.bold("Usage"),
|
|
2340
|
+
...group.usage.map((line) => ` ${line}`),
|
|
2341
|
+
"",
|
|
2342
|
+
pc2.bold("Commands"),
|
|
2343
|
+
...group.commands.map((entry) => commandLine(entry.command, entry.description))
|
|
2344
|
+
];
|
|
2345
|
+
if (group.examples?.length) {
|
|
2346
|
+
lines.push("", pc2.bold("Examples"), ...group.examples.map((line) => ` ${pc2.dim("$")} ${line}`));
|
|
2347
|
+
}
|
|
2348
|
+
if (group.next?.length) {
|
|
2349
|
+
lines.push("", pc2.bold("Next steps"), ...group.next.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
|
|
2350
|
+
}
|
|
2351
|
+
if (group.advanced?.length) {
|
|
2352
|
+
lines.push("", pc2.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
|
|
2353
|
+
}
|
|
2354
|
+
return lines.join(`
|
|
2355
|
+
`);
|
|
2356
|
+
}
|
|
2357
|
+
function renderTopLevelHelp() {
|
|
2358
|
+
return [
|
|
2359
|
+
`${heading("rig")} ${pc2.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
|
|
2360
|
+
pc2.dim("Current path: select a server, choose a task, submit a run, attach with native Pi, clear inbox/review gates."),
|
|
2361
|
+
"",
|
|
2362
|
+
...TOP_LEVEL_SECTIONS.flatMap((section) => [
|
|
2363
|
+
`${pc2.bold(pc2.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc2.dim(section.subtitle)}`,
|
|
2364
|
+
renderCommandBlock(section.commands),
|
|
2365
|
+
""
|
|
2366
|
+
]),
|
|
2367
|
+
pc2.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
|
|
2368
|
+
"",
|
|
2369
|
+
pc2.bold("Global options"),
|
|
2370
|
+
commandLine("--project <path>", "Use a project root instead of auto-discovery."),
|
|
2371
|
+
commandLine("--json", "Emit structured output for scripts/agents."),
|
|
2372
|
+
commandLine("--dry-run", "Print the command plan without mutating state.")
|
|
2373
|
+
].join(`
|
|
2374
|
+
`).trimEnd();
|
|
2375
|
+
}
|
|
2376
|
+
function renderGroupHelp(groupName) {
|
|
2377
|
+
const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
|
|
2378
|
+
return group ? renderGroup(group) : null;
|
|
2379
|
+
}
|
|
2380
|
+
function shouldUseClackOutput2() {
|
|
2381
|
+
return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
|
|
2382
|
+
}
|
|
2383
|
+
function printTopLevelHelp(state = {}) {
|
|
2384
|
+
if (!shouldUseClackOutput2()) {
|
|
2385
|
+
console.log(renderTopLevelHelp());
|
|
2386
|
+
return;
|
|
2387
|
+
}
|
|
2388
|
+
console.log(renderRigBanner(state.version));
|
|
2389
|
+
console.log("");
|
|
2390
|
+
if (state.projectInitialized === false) {
|
|
2391
|
+
intro("no rig project in this directory");
|
|
2392
|
+
note2([
|
|
2393
|
+
commandLine("rig init", "Set this repo up: config, GitHub auth, task source, server, Pi."),
|
|
2394
|
+
commandLine("rig init --yes", "Same, non-interactive, sensible defaults."),
|
|
2395
|
+
commandLine("rig doctor", "Already initialized somewhere else? Check the wiring.")
|
|
2396
|
+
].join(`
|
|
2397
|
+
`), "Get started");
|
|
2398
|
+
outro("After init: rig task run --next puts an agent on your next task.");
|
|
2399
|
+
return;
|
|
2400
|
+
}
|
|
2401
|
+
intro(state.selectedServer ? `server: ${state.selectedServer}` : "rig");
|
|
2402
|
+
for (const section of TOP_LEVEL_SECTIONS) {
|
|
2403
|
+
note2(renderCommandBlock(section.commands), `${section.title} \u2014 ${section.subtitle}`);
|
|
2404
|
+
}
|
|
2405
|
+
log2.info("More: rig help --advanced \xB7 rig <group> --help \xB7 rig --version");
|
|
2406
|
+
note2([
|
|
2407
|
+
commandLine("--project <path>", "Use a project root instead of auto-discovery."),
|
|
2408
|
+
commandLine("--json", "Emit structured output for scripts/agents."),
|
|
2409
|
+
commandLine("--dry-run", "Print the command plan without mutating state.")
|
|
2410
|
+
].join(`
|
|
2411
|
+
`), "Global options");
|
|
2412
|
+
outro("init \u2192 task run \u2192 watch/steer \u2192 inbox/review \u2192 merged.");
|
|
2413
|
+
}
|
|
2414
|
+
function printGroupHelpDocument(groupName) {
|
|
2415
|
+
const rendered = renderGroupHelp(groupName) ?? renderTopLevelHelp();
|
|
2416
|
+
if (!shouldUseClackOutput2()) {
|
|
2417
|
+
console.log(rendered);
|
|
2418
|
+
return;
|
|
2419
|
+
}
|
|
2420
|
+
const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
|
|
2421
|
+
if (!group) {
|
|
2422
|
+
printTopLevelHelp();
|
|
2423
|
+
return;
|
|
2424
|
+
}
|
|
2425
|
+
intro(`rig ${group.name}`);
|
|
2426
|
+
note2(group.summary, "Purpose");
|
|
2427
|
+
note2(group.usage.join(`
|
|
2428
|
+
`), "Usage");
|
|
2429
|
+
note2(group.commands.map((entry) => commandLine(entry.command, entry.description)).join(`
|
|
2430
|
+
`), "Commands");
|
|
2431
|
+
if (group.examples?.length)
|
|
2432
|
+
note2(group.examples.map((line) => `$ ${line}`).join(`
|
|
2433
|
+
`), "Examples");
|
|
2434
|
+
if (group.next?.length)
|
|
2435
|
+
note2(group.next.map((line) => `\u203A ${line}`).join(`
|
|
2436
|
+
`), "Next steps");
|
|
2437
|
+
if (group.advanced?.length)
|
|
2438
|
+
log2.info(group.advanced.join(`
|
|
2439
|
+
`));
|
|
2440
|
+
outro("Run with --json when scripts need structured output.");
|
|
2441
|
+
}
|
|
2442
|
+
|
|
852
2443
|
// packages/cli/src/commands/task.ts
|
|
853
2444
|
import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
|
|
854
2445
|
import { loadConfig } from "@rig/core/load-config";
|
|
@@ -924,7 +2515,7 @@ function normalizePrMode(value) {
|
|
|
924
2515
|
throw new CliError2("--pr must be auto, ask, or off.", 2);
|
|
925
2516
|
}
|
|
926
2517
|
function detectLocalDirtyState(projectRoot) {
|
|
927
|
-
const result =
|
|
2518
|
+
const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
|
|
928
2519
|
if (result.status !== 0)
|
|
929
2520
|
return { dirty: false, modified: 0, untracked: 0, lines: [] };
|
|
930
2521
|
const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
|
|
@@ -958,13 +2549,15 @@ async function resolveDirtyBaselineForTaskRun(context, explicit) {
|
|
|
958
2549
|
if (explicit)
|
|
959
2550
|
return { mode: explicit, state };
|
|
960
2551
|
if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
|
|
961
|
-
const
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
2552
|
+
const answer = await confirm({
|
|
2553
|
+
message: "Include current uncommitted changes in run baseline?",
|
|
2554
|
+
initialValue: false
|
|
2555
|
+
});
|
|
2556
|
+
if (isCancel2(answer)) {
|
|
2557
|
+
cancel2("Run cancelled.");
|
|
2558
|
+
throw new CliError2("Run cancelled by user.", 1);
|
|
967
2559
|
}
|
|
2560
|
+
return { mode: answer ? "dirty-snapshot" : "head", state };
|
|
968
2561
|
}
|
|
969
2562
|
return { mode: "head", state };
|
|
970
2563
|
}
|
|
@@ -998,38 +2591,30 @@ function summarizeTask(task, options = {}) {
|
|
|
998
2591
|
...options.raw ? { raw: raw ?? task } : {}
|
|
999
2592
|
};
|
|
1000
2593
|
}
|
|
1001
|
-
function printTaskSummary(task) {
|
|
1002
|
-
const id = readTaskId(task) ?? "<unknown>";
|
|
1003
|
-
const title = readTaskString(task, "title") ?? "Untitled task";
|
|
1004
|
-
const status = readTaskString(task, "status") ?? "unknown";
|
|
1005
|
-
console.log(`- ${id} \xB7 ${status} \xB7 ${title}`);
|
|
1006
|
-
}
|
|
1007
2594
|
async function validatorRegistryForTaskCommands(projectRoot) {
|
|
1008
2595
|
return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
|
|
1009
2596
|
return;
|
|
1010
2597
|
});
|
|
1011
2598
|
}
|
|
1012
2599
|
async function executeTask(context, args, options) {
|
|
1013
|
-
|
|
2600
|
+
if (args.length === 0) {
|
|
2601
|
+
if (context.outputMode === "text") {
|
|
2602
|
+
printGroupHelpDocument("task");
|
|
2603
|
+
}
|
|
2604
|
+
return { ok: true, group: "task", command: "help" };
|
|
2605
|
+
}
|
|
2606
|
+
const [command = "help", ...rest] = args;
|
|
1014
2607
|
switch (command) {
|
|
1015
2608
|
case "list": {
|
|
1016
2609
|
let pending = rest;
|
|
1017
2610
|
const rawResult = takeFlag(pending, "--raw");
|
|
1018
2611
|
pending = rawResult.rest;
|
|
1019
2612
|
const { filters, rest: remaining } = parseTaskFilters(pending);
|
|
1020
|
-
requireNoExtraArgs(remaining, "
|
|
2613
|
+
requireNoExtraArgs(remaining, "rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
1021
2614
|
const tasks = await listWorkspaceTasksViaServer(context, filters);
|
|
1022
2615
|
if (context.outputMode === "text") {
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
} else {
|
|
1026
|
-
for (const task of tasks) {
|
|
1027
|
-
if (rawResult.value)
|
|
1028
|
-
console.log(JSON.stringify(summarizeTask(task, { raw: true })));
|
|
1029
|
-
else
|
|
1030
|
-
printTaskSummary(task);
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
2616
|
+
const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
|
|
2617
|
+
printFormattedOutput(formatTaskList(renderedTasks, { raw: rawResult.value }));
|
|
1033
2618
|
}
|
|
1034
2619
|
return {
|
|
1035
2620
|
ok: true,
|
|
@@ -1039,30 +2624,34 @@ async function executeTask(context, args, options) {
|
|
|
1039
2624
|
};
|
|
1040
2625
|
}
|
|
1041
2626
|
case "show": {
|
|
1042
|
-
|
|
2627
|
+
let pending = rest;
|
|
2628
|
+
const rawResult = takeFlag(pending, "--raw");
|
|
2629
|
+
pending = rawResult.rest;
|
|
2630
|
+
const taskOption = takeOption(pending, "--task");
|
|
1043
2631
|
const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
|
|
1044
2632
|
const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
|
|
1045
|
-
requireNoExtraArgs(remaining, "
|
|
1046
|
-
const
|
|
1047
|
-
if (!
|
|
2633
|
+
requireNoExtraArgs(remaining, "rig task show <id>|--task <id> [--raw]");
|
|
2634
|
+
const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
|
|
2635
|
+
if (!taskId3)
|
|
1048
2636
|
throw new CliError2("task show requires a task id.", 2);
|
|
1049
|
-
const task = await getWorkspaceTaskViaServer(context,
|
|
2637
|
+
const task = await getWorkspaceTaskViaServer(context, taskId3);
|
|
1050
2638
|
if (!task)
|
|
1051
|
-
throw new CliError2(`Task not found: ${
|
|
2639
|
+
throw new CliError2(`Task not found: ${taskId3}`, 3);
|
|
1052
2640
|
const summary = summarizeTask(task, { raw: true });
|
|
1053
|
-
if (context.outputMode === "text")
|
|
1054
|
-
|
|
1055
|
-
|
|
2641
|
+
if (context.outputMode === "text") {
|
|
2642
|
+
printFormattedOutput(rawResult.value ? JSON.stringify(summary, null, 2) : formatTaskDetails(summary));
|
|
2643
|
+
}
|
|
2644
|
+
return { ok: true, group: "task", command, details: { task: summary, raw: rawResult.value } };
|
|
1056
2645
|
}
|
|
1057
2646
|
case "next": {
|
|
1058
2647
|
const { filters, rest: remaining } = parseTaskFilters(rest);
|
|
1059
|
-
requireNoExtraArgs(remaining, "
|
|
2648
|
+
requireNoExtraArgs(remaining, "rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
1060
2649
|
const selected = await selectNextWorkspaceTaskViaServer(context, filters);
|
|
1061
2650
|
if (context.outputMode === "text") {
|
|
1062
2651
|
if (selected.task) {
|
|
1063
|
-
|
|
2652
|
+
printFormattedOutput(formatTaskCard(summarizeTask(selected.task, { raw: true }), { title: "Selected task", selected: true }));
|
|
1064
2653
|
} else {
|
|
1065
|
-
|
|
2654
|
+
printFormattedOutput("No matching tasks.\n\nNext\n\u203A Try `rig task list` to inspect available work.\n\u203A Check server: `rig server status`");
|
|
1066
2655
|
}
|
|
1067
2656
|
}
|
|
1068
2657
|
return {
|
|
@@ -1078,31 +2667,31 @@ async function executeTask(context, args, options) {
|
|
|
1078
2667
|
}
|
|
1079
2668
|
case "info": {
|
|
1080
2669
|
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
1081
|
-
requireNoExtraArgs(remaining, "
|
|
2670
|
+
requireNoExtraArgs(remaining, "rig task info [--task <task-id>]");
|
|
1082
2671
|
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
|
|
1083
2672
|
return { ok: true, group: "task", command, details: { task: task || null } };
|
|
1084
2673
|
}
|
|
1085
2674
|
case "scope": {
|
|
1086
2675
|
const filesFlag = takeFlag(rest, "--files");
|
|
1087
2676
|
const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
|
|
1088
|
-
requireNoExtraArgs(remaining, "
|
|
2677
|
+
requireNoExtraArgs(remaining, "rig task scope [--task <id>] [--files]");
|
|
1089
2678
|
await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
|
|
1090
2679
|
return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
|
|
1091
2680
|
}
|
|
1092
2681
|
case "deps":
|
|
1093
|
-
requireNoExtraArgs(rest, "
|
|
2682
|
+
requireNoExtraArgs(rest, "rig task deps");
|
|
1094
2683
|
await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
|
|
1095
2684
|
return { ok: true, group: "task", command };
|
|
1096
2685
|
case "status":
|
|
1097
|
-
requireNoExtraArgs(rest, "
|
|
2686
|
+
requireNoExtraArgs(rest, "rig task status");
|
|
1098
2687
|
withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
|
|
1099
2688
|
return { ok: true, group: "task", command };
|
|
1100
2689
|
case "artifacts":
|
|
1101
|
-
requireNoExtraArgs(rest, "
|
|
2690
|
+
requireNoExtraArgs(rest, "rig task artifacts");
|
|
1102
2691
|
withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
|
|
1103
2692
|
return { ok: true, group: "task", command };
|
|
1104
2693
|
case "artifact-dir": {
|
|
1105
|
-
requireNoExtraArgs(rest, "
|
|
2694
|
+
requireNoExtraArgs(rest, "rig task artifact-dir");
|
|
1106
2695
|
const path = taskArtifactDir(context.projectRoot);
|
|
1107
2696
|
if (context.outputMode === "text") {
|
|
1108
2697
|
console.log(path);
|
|
@@ -1111,7 +2700,7 @@ async function executeTask(context, args, options) {
|
|
|
1111
2700
|
}
|
|
1112
2701
|
case "artifact-write": {
|
|
1113
2702
|
if (rest.length < 1) {
|
|
1114
|
-
throw new CliError2(`Usage:
|
|
2703
|
+
throw new CliError2(`Usage: rig task artifact-write <filename> [--file <path>]
|
|
1115
2704
|
` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
|
|
1116
2705
|
` + " Example: echo '...' | rig task artifact-write collection-audit.md");
|
|
1117
2706
|
}
|
|
@@ -1119,12 +2708,12 @@ async function executeTask(context, args, options) {
|
|
|
1119
2708
|
const fileFlag = takeOption(rest.slice(1), "--file");
|
|
1120
2709
|
let content;
|
|
1121
2710
|
if (fileFlag.value) {
|
|
1122
|
-
content =
|
|
2711
|
+
content = readFileSync3(resolve3(context.projectRoot, fileFlag.value), "utf-8");
|
|
1123
2712
|
} else {
|
|
1124
2713
|
content = await readStdin();
|
|
1125
2714
|
}
|
|
1126
2715
|
if (!artifactFilename) {
|
|
1127
|
-
throw new CliError2("Usage:
|
|
2716
|
+
throw new CliError2("Usage: rig task artifact-write <filename> [--file path]");
|
|
1128
2717
|
}
|
|
1129
2718
|
withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
|
|
1130
2719
|
return { ok: true, group: "task", command, details: { filename: artifactFilename } };
|
|
@@ -1133,11 +2722,11 @@ async function executeTask(context, args, options) {
|
|
|
1133
2722
|
return options.executeTaskReportBug(context, rest);
|
|
1134
2723
|
case "lookup": {
|
|
1135
2724
|
if (rest.length !== 1) {
|
|
1136
|
-
throw new CliError2("Usage:
|
|
2725
|
+
throw new CliError2("Usage: rig task lookup <task-id>");
|
|
1137
2726
|
}
|
|
1138
2727
|
const lookupId = rest[0];
|
|
1139
2728
|
if (!lookupId) {
|
|
1140
|
-
throw new CliError2("Usage:
|
|
2729
|
+
throw new CliError2("Usage: rig task lookup <task-id>");
|
|
1141
2730
|
}
|
|
1142
2731
|
const result = taskLookup(context.projectRoot, lookupId);
|
|
1143
2732
|
if (context.outputMode === "text") {
|
|
@@ -1147,17 +2736,17 @@ async function executeTask(context, args, options) {
|
|
|
1147
2736
|
}
|
|
1148
2737
|
case "record": {
|
|
1149
2738
|
if (rest.length < 2) {
|
|
1150
|
-
throw new CliError2("Usage:
|
|
2739
|
+
throw new CliError2("Usage: rig task record <decision|failure> <text>");
|
|
1151
2740
|
}
|
|
1152
2741
|
const type = rest[0];
|
|
1153
2742
|
if (type !== "decision" && type !== "failure") {
|
|
1154
|
-
throw new CliError2("Usage:
|
|
2743
|
+
throw new CliError2("Usage: rig task record <decision|failure> <text>");
|
|
1155
2744
|
}
|
|
1156
2745
|
withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
|
|
1157
2746
|
return { ok: true, group: "task", command, details: { type: rest[0] } };
|
|
1158
2747
|
}
|
|
1159
2748
|
case "ready":
|
|
1160
|
-
requireNoExtraArgs(rest, "
|
|
2749
|
+
requireNoExtraArgs(rest, "rig task ready");
|
|
1161
2750
|
await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
|
|
1162
2751
|
return { ok: true, group: "task", command };
|
|
1163
2752
|
case "run": {
|
|
@@ -1194,7 +2783,7 @@ async function executeTask(context, args, options) {
|
|
|
1194
2783
|
if (positionalTaskId) {
|
|
1195
2784
|
pending = pending.slice(1);
|
|
1196
2785
|
}
|
|
1197
|
-
requireNoExtraArgs(pending, "
|
|
2786
|
+
requireNoExtraArgs(pending, "rig task run [#<issue>|<task-id>] [--next] [--task <id>] [--detach] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>] [--title <text>] [--runtime-adapter claude-code|codex|pi] [--model <model>] [--runtime-mode <mode>] [--interaction-mode <mode>] [--initial-prompt <text>] [--pr auto|ask|off] [--no-pr] [--dirty-baseline head|dirty-snapshot] [--skip-project-sync]");
|
|
1198
2787
|
if (nextResult.value && (taskResult.value || positionalTaskId)) {
|
|
1199
2788
|
throw new CliError2("task run cannot combine --next with an explicit task id.", 2);
|
|
1200
2789
|
}
|
|
@@ -1248,16 +2837,24 @@ async function executeTask(context, args, options) {
|
|
|
1248
2837
|
});
|
|
1249
2838
|
let attachDetails = null;
|
|
1250
2839
|
if (!detachResult.value && context.outputMode === "text") {
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
2840
|
+
printFormattedOutput(formatSubmittedRun({
|
|
2841
|
+
runId: submitted.runId,
|
|
2842
|
+
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2843
|
+
runtimeAdapter,
|
|
2844
|
+
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2845
|
+
interactionMode: interactionModeResult.value || "default",
|
|
2846
|
+
detached: false
|
|
2847
|
+
}));
|
|
1255
2848
|
attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
|
|
1256
2849
|
} else if (context.outputMode === "text") {
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
2850
|
+
printFormattedOutput(formatSubmittedRun({
|
|
2851
|
+
runId: submitted.runId,
|
|
2852
|
+
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2853
|
+
runtimeAdapter,
|
|
2854
|
+
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2855
|
+
interactionMode: interactionModeResult.value || "default",
|
|
2856
|
+
detached: true
|
|
2857
|
+
}));
|
|
1261
2858
|
}
|
|
1262
2859
|
return {
|
|
1263
2860
|
ok: true,
|
|
@@ -1281,7 +2878,7 @@ async function executeTask(context, args, options) {
|
|
|
1281
2878
|
}
|
|
1282
2879
|
case "validate": {
|
|
1283
2880
|
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
1284
|
-
requireNoExtraArgs(remaining, "
|
|
2881
|
+
requireNoExtraArgs(remaining, "rig task validate [--task <task-id>]");
|
|
1285
2882
|
if (context.dryRun) {
|
|
1286
2883
|
await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
|
|
1287
2884
|
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
@@ -1294,12 +2891,12 @@ async function executeTask(context, args, options) {
|
|
|
1294
2891
|
}
|
|
1295
2892
|
case "verify": {
|
|
1296
2893
|
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
1297
|
-
requireNoExtraArgs(remaining, "
|
|
2894
|
+
requireNoExtraArgs(remaining, "rig task verify [--task <task-id>]");
|
|
1298
2895
|
if (context.dryRun) {
|
|
1299
2896
|
await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
|
|
1300
2897
|
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
1301
2898
|
}
|
|
1302
|
-
const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot,
|
|
2899
|
+
const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, task || undefined));
|
|
1303
2900
|
if (!ok) {
|
|
1304
2901
|
throw new CliError2(`Verification rejected for ${task || "active task"}.`, 2);
|
|
1305
2902
|
}
|
|
@@ -1307,15 +2904,19 @@ async function executeTask(context, args, options) {
|
|
|
1307
2904
|
}
|
|
1308
2905
|
case "reset": {
|
|
1309
2906
|
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
1310
|
-
requireNoExtraArgs(remaining, "
|
|
1311
|
-
const requiredTask = requireTask(task, "
|
|
1312
|
-
|
|
1313
|
-
|
|
2907
|
+
requireNoExtraArgs(remaining, "rig task reset --task <task-id>");
|
|
2908
|
+
const requiredTask = requireTask(task, "rig task reset --task <task-id>");
|
|
2909
|
+
const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
|
|
2910
|
+
all: false,
|
|
2911
|
+
taskId: requiredTask,
|
|
2912
|
+
dryRun: false
|
|
2913
|
+
}));
|
|
2914
|
+
return { ok: true, group: "task", command, details: summary };
|
|
1314
2915
|
}
|
|
1315
2916
|
case "details": {
|
|
1316
2917
|
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
1317
|
-
requireNoExtraArgs(remaining, "
|
|
1318
|
-
const requiredTask = requireTask(task, "
|
|
2918
|
+
requireNoExtraArgs(remaining, "rig task details --task <task-id>");
|
|
2919
|
+
const requiredTask = requireTask(task, "rig task details --task <task-id>");
|
|
1319
2920
|
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
|
|
1320
2921
|
return { ok: true, group: "task", command, details: { task: requiredTask } };
|
|
1321
2922
|
}
|
|
@@ -1323,9 +2924,9 @@ async function executeTask(context, args, options) {
|
|
|
1323
2924
|
const { value: task, rest: rest1 } = takeOption(rest, "--task");
|
|
1324
2925
|
const allFlag = takeFlag(rest1, "--all");
|
|
1325
2926
|
const { rest: remaining } = takeOption(allFlag.rest, "--reason");
|
|
1326
|
-
requireNoExtraArgs(remaining, "
|
|
2927
|
+
requireNoExtraArgs(remaining, "rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
1327
2928
|
if (!allFlag.value && !task) {
|
|
1328
|
-
throw new CliError2("Usage:
|
|
2929
|
+
throw new CliError2("Usage: rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
1329
2930
|
}
|
|
1330
2931
|
const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
|
|
1331
2932
|
all: allFlag.value,
|