@h-rig/cli 0.0.6-alpha.28 → 0.0.6-alpha.281
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -28
- package/package.json +11 -28
- package/dist/bin/build-rig-binaries.js +0 -107
- package/dist/bin/rig.js +0 -11739
- package/dist/src/commands/_authority-runs.js +0 -111
- package/dist/src/commands/_cli-format.js +0 -369
- package/dist/src/commands/_connection-state.js +0 -123
- package/dist/src/commands/_doctor-checks.js +0 -507
- package/dist/src/commands/_help-catalog.js +0 -364
- package/dist/src/commands/_operator-surface.js +0 -204
- package/dist/src/commands/_operator-view.js +0 -1147
- package/dist/src/commands/_parsers.js +0 -107
- package/dist/src/commands/_paths.js +0 -50
- package/dist/src/commands/_pi-frontend.js +0 -843
- package/dist/src/commands/_pi-install.js +0 -185
- package/dist/src/commands/_pi-worker-bridge-extension.js +0 -761
- package/dist/src/commands/_policy.js +0 -79
- package/dist/src/commands/_preflight.js +0 -403
- package/dist/src/commands/_probes.js +0 -13
- package/dist/src/commands/_run-driver-helpers.js +0 -289
- package/dist/src/commands/_server-client.js +0 -514
- package/dist/src/commands/_snapshot-upload.js +0 -318
- package/dist/src/commands/_task-picker.js +0 -76
- package/dist/src/commands/agent.js +0 -499
- package/dist/src/commands/browser.js +0 -890
- package/dist/src/commands/connect.js +0 -289
- package/dist/src/commands/dist.js +0 -402
- package/dist/src/commands/doctor.js +0 -517
- package/dist/src/commands/github.js +0 -281
- package/dist/src/commands/inbox.js +0 -482
- package/dist/src/commands/init.js +0 -1563
- package/dist/src/commands/inspect.js +0 -174
- package/dist/src/commands/inspector.js +0 -256
- package/dist/src/commands/plugin.js +0 -167
- package/dist/src/commands/profile-and-review.js +0 -178
- package/dist/src/commands/queue.js +0 -198
- package/dist/src/commands/remote.js +0 -507
- package/dist/src/commands/repo-git-harness.js +0 -221
- package/dist/src/commands/run.js +0 -1808
- package/dist/src/commands/server.js +0 -572
- package/dist/src/commands/setup.js +0 -687
- package/dist/src/commands/task-report-bug.js +0 -1083
- package/dist/src/commands/task-run-driver.js +0 -2600
- package/dist/src/commands/task.js +0 -2606
- package/dist/src/commands/test.js +0 -39
- package/dist/src/commands/workspace.js +0 -123
- package/dist/src/commands.js +0 -11418
- package/dist/src/index.js +0 -11757
- package/dist/src/launcher.js +0 -133
- package/dist/src/report-bug.js +0 -260
- package/dist/src/runner.js +0 -273
- package/dist/src/withMutedConsole.js +0 -42
|
@@ -1,2606 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
// packages/cli/src/commands/task.ts
|
|
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
|
-
|
|
8
|
-
// packages/cli/src/runner.ts
|
|
9
|
-
import { EventBus } from "@rig/runtime/control-plane/runtime/events";
|
|
10
|
-
import { CliError } from "@rig/runtime/control-plane/errors";
|
|
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
|
-
import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
|
|
15
|
-
import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
|
|
16
|
-
function takeFlag(args, flag) {
|
|
17
|
-
const rest = [];
|
|
18
|
-
let value = false;
|
|
19
|
-
for (const arg of args) {
|
|
20
|
-
if (arg === flag) {
|
|
21
|
-
value = true;
|
|
22
|
-
continue;
|
|
23
|
-
}
|
|
24
|
-
rest.push(arg);
|
|
25
|
-
}
|
|
26
|
-
return { value, rest };
|
|
27
|
-
}
|
|
28
|
-
function takeOption(args, option) {
|
|
29
|
-
const rest = [];
|
|
30
|
-
let value;
|
|
31
|
-
for (let index = 0;index < args.length; index += 1) {
|
|
32
|
-
const current = args[index];
|
|
33
|
-
if (current === option) {
|
|
34
|
-
const next = args[index + 1];
|
|
35
|
-
if (!next || next.startsWith("-")) {
|
|
36
|
-
throw new CliError(`Missing value for ${option}`);
|
|
37
|
-
}
|
|
38
|
-
value = next;
|
|
39
|
-
index += 1;
|
|
40
|
-
continue;
|
|
41
|
-
}
|
|
42
|
-
if (current !== undefined) {
|
|
43
|
-
rest.push(current);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
return { value, rest };
|
|
47
|
-
}
|
|
48
|
-
function requireNoExtraArgs(args, usage) {
|
|
49
|
-
if (args.length > 0) {
|
|
50
|
-
throw new CliError(`Unexpected arguments: ${args.join(" ")}
|
|
51
|
-
Usage: ${usage}`);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
function requireTask(taskId, usage) {
|
|
55
|
-
if (!taskId) {
|
|
56
|
-
throw new CliError(`Missing --task option.
|
|
57
|
-
Usage: ${usage}`);
|
|
58
|
-
}
|
|
59
|
-
return taskId;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// packages/cli/src/commands/task.ts
|
|
63
|
-
import {
|
|
64
|
-
taskArtifactDir,
|
|
65
|
-
taskArtifacts,
|
|
66
|
-
taskArtifactWrite,
|
|
67
|
-
taskDeps,
|
|
68
|
-
taskInfo,
|
|
69
|
-
taskLookup,
|
|
70
|
-
taskReady,
|
|
71
|
-
taskRecord,
|
|
72
|
-
taskReopen,
|
|
73
|
-
taskScope,
|
|
74
|
-
taskStatus as taskStatus2,
|
|
75
|
-
taskValidate,
|
|
76
|
-
taskVerify
|
|
77
|
-
} from "@rig/runtime/control-plane/native/task-ops";
|
|
78
|
-
|
|
79
|
-
// packages/cli/src/commands/_authority-runs.ts
|
|
80
|
-
import {
|
|
81
|
-
readAuthorityRun,
|
|
82
|
-
readJsonlFile,
|
|
83
|
-
resolveAuthorityRunDir,
|
|
84
|
-
writeJsonFile
|
|
85
|
-
} from "@rig/runtime/control-plane/authority-files";
|
|
86
|
-
|
|
87
|
-
// packages/cli/src/commands/_paths.ts
|
|
88
|
-
import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
|
|
89
|
-
|
|
90
|
-
// packages/cli/src/commands/_authority-runs.ts
|
|
91
|
-
function normalizeRuntimeAdapter(value) {
|
|
92
|
-
const normalized = value?.trim().toLowerCase();
|
|
93
|
-
if (!normalized) {
|
|
94
|
-
return "pi";
|
|
95
|
-
}
|
|
96
|
-
if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
|
|
97
|
-
return "codex";
|
|
98
|
-
}
|
|
99
|
-
if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
|
|
100
|
-
return "pi";
|
|
101
|
-
}
|
|
102
|
-
return "claude-code";
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// packages/cli/src/commands/_preflight.ts
|
|
106
|
-
import { ensureProjectMainFreshBeforeRun } from "@rig/runtime/control-plane/project-main-pre-run-sync";
|
|
107
|
-
|
|
108
|
-
// packages/cli/src/commands/_connection-state.ts
|
|
109
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
110
|
-
import { homedir } from "os";
|
|
111
|
-
import { dirname, resolve } from "path";
|
|
112
|
-
function resolveGlobalConnectionsPath(env = process.env) {
|
|
113
|
-
const explicit = env.RIG_CONNECTIONS_FILE?.trim();
|
|
114
|
-
if (explicit)
|
|
115
|
-
return resolve(explicit);
|
|
116
|
-
const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
|
|
117
|
-
if (stateDir)
|
|
118
|
-
return resolve(stateDir, "connections.json");
|
|
119
|
-
return resolve(homedir(), ".rig", "connections.json");
|
|
120
|
-
}
|
|
121
|
-
function resolveRepoConnectionPath(projectRoot) {
|
|
122
|
-
return resolve(projectRoot, ".rig", "state", "connection.json");
|
|
123
|
-
}
|
|
124
|
-
function readJsonFile(path) {
|
|
125
|
-
if (!existsSync(path))
|
|
126
|
-
return null;
|
|
127
|
-
try {
|
|
128
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
129
|
-
} catch (error) {
|
|
130
|
-
throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
function normalizeConnection(value) {
|
|
134
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
135
|
-
return null;
|
|
136
|
-
const record = value;
|
|
137
|
-
if (record.kind === "local")
|
|
138
|
-
return { kind: "local", mode: "auto" };
|
|
139
|
-
if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
|
|
140
|
-
const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
|
|
141
|
-
return { kind: "remote", baseUrl };
|
|
142
|
-
}
|
|
143
|
-
return null;
|
|
144
|
-
}
|
|
145
|
-
function readGlobalConnections(options = {}) {
|
|
146
|
-
const path = resolveGlobalConnectionsPath(options.env ?? process.env);
|
|
147
|
-
const payload = readJsonFile(path);
|
|
148
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
149
|
-
return { connections: {} };
|
|
150
|
-
}
|
|
151
|
-
const rawConnections = payload.connections;
|
|
152
|
-
const connections = {};
|
|
153
|
-
if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
|
|
154
|
-
for (const [alias, raw] of Object.entries(rawConnections)) {
|
|
155
|
-
const connection = normalizeConnection(raw);
|
|
156
|
-
if (connection)
|
|
157
|
-
connections[alias] = connection;
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
return { connections };
|
|
161
|
-
}
|
|
162
|
-
function readRepoConnection(projectRoot) {
|
|
163
|
-
const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
|
|
164
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
165
|
-
return null;
|
|
166
|
-
const record = payload;
|
|
167
|
-
const selected = typeof record.selected === "string" ? record.selected.trim() : "";
|
|
168
|
-
if (!selected)
|
|
169
|
-
return null;
|
|
170
|
-
return {
|
|
171
|
-
selected,
|
|
172
|
-
project: typeof record.project === "string" ? record.project : undefined,
|
|
173
|
-
linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
function resolveSelectedConnection(projectRoot, options = {}) {
|
|
177
|
-
const repo = readRepoConnection(projectRoot);
|
|
178
|
-
if (!repo)
|
|
179
|
-
return null;
|
|
180
|
-
if (repo.selected === "local")
|
|
181
|
-
return { alias: "local", connection: { kind: "local", mode: "auto" } };
|
|
182
|
-
const global = readGlobalConnections(options);
|
|
183
|
-
const connection = global.connections[repo.selected];
|
|
184
|
-
if (!connection) {
|
|
185
|
-
throw new CliError2(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
|
|
186
|
-
}
|
|
187
|
-
return { alias: repo.selected, connection };
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// packages/cli/src/commands/_server-client.ts
|
|
191
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
192
|
-
import { resolve as resolve2 } from "path";
|
|
193
|
-
import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
|
|
194
|
-
var scopedGitHubBearerTokens = new Map;
|
|
195
|
-
function cleanToken(value) {
|
|
196
|
-
const trimmed = value?.trim();
|
|
197
|
-
return trimmed ? trimmed : null;
|
|
198
|
-
}
|
|
199
|
-
function readPrivateRemoteSessionToken(projectRoot) {
|
|
200
|
-
const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
|
|
201
|
-
if (!existsSync2(path))
|
|
202
|
-
return null;
|
|
203
|
-
try {
|
|
204
|
-
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
205
|
-
return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
|
|
206
|
-
} catch {
|
|
207
|
-
return null;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
function readGitHubBearerTokenForRemote(projectRoot) {
|
|
211
|
-
const scopedKey = resolve2(projectRoot);
|
|
212
|
-
if (scopedGitHubBearerTokens.has(scopedKey))
|
|
213
|
-
return scopedGitHubBearerTokens.get(scopedKey) ?? null;
|
|
214
|
-
const privateSession = readPrivateRemoteSessionToken(projectRoot);
|
|
215
|
-
if (privateSession)
|
|
216
|
-
return privateSession;
|
|
217
|
-
return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
|
|
218
|
-
}
|
|
219
|
-
async function ensureServerForCli(projectRoot) {
|
|
220
|
-
try {
|
|
221
|
-
const selected = resolveSelectedConnection(projectRoot);
|
|
222
|
-
if (selected?.connection.kind === "remote") {
|
|
223
|
-
return {
|
|
224
|
-
baseUrl: selected.connection.baseUrl,
|
|
225
|
-
authToken: readGitHubBearerTokenForRemote(projectRoot),
|
|
226
|
-
connectionKind: "remote"
|
|
227
|
-
};
|
|
228
|
-
}
|
|
229
|
-
const connection = await ensureLocalRigServerConnection(projectRoot);
|
|
230
|
-
return {
|
|
231
|
-
baseUrl: connection.baseUrl,
|
|
232
|
-
authToken: connection.authToken,
|
|
233
|
-
connectionKind: "local"
|
|
234
|
-
};
|
|
235
|
-
} catch (error) {
|
|
236
|
-
if (error instanceof Error) {
|
|
237
|
-
throw new CliError2(error.message, 1);
|
|
238
|
-
}
|
|
239
|
-
throw error;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
function appendTaskFilterParams(url, filters) {
|
|
243
|
-
if (filters.assignee)
|
|
244
|
-
url.searchParams.set("assignee", filters.assignee);
|
|
245
|
-
if (filters.state)
|
|
246
|
-
url.searchParams.set("state", filters.state);
|
|
247
|
-
if (filters.status)
|
|
248
|
-
url.searchParams.set("status", filters.status);
|
|
249
|
-
if (filters.limit !== undefined)
|
|
250
|
-
url.searchParams.set("limit", String(filters.limit));
|
|
251
|
-
}
|
|
252
|
-
function mergeHeaders(headers, authToken) {
|
|
253
|
-
const merged = new Headers(headers);
|
|
254
|
-
if (authToken) {
|
|
255
|
-
merged.set("authorization", `Bearer ${authToken}`);
|
|
256
|
-
}
|
|
257
|
-
return merged;
|
|
258
|
-
}
|
|
259
|
-
function diagnosticMessage(payload) {
|
|
260
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
261
|
-
return null;
|
|
262
|
-
const record = payload;
|
|
263
|
-
const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
|
|
264
|
-
const messages = diagnostics.flatMap((entry) => {
|
|
265
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
266
|
-
return [];
|
|
267
|
-
const diagnostic = entry;
|
|
268
|
-
const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
|
|
269
|
-
const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
|
|
270
|
-
return message ? [`${kind}: ${message}`] : [];
|
|
271
|
-
});
|
|
272
|
-
return messages.length > 0 ? messages.join("; ") : null;
|
|
273
|
-
}
|
|
274
|
-
async function requestServerJson(context, pathname, init = {}) {
|
|
275
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
276
|
-
const response = await fetch(`${server.baseUrl}${pathname}`, {
|
|
277
|
-
...init,
|
|
278
|
-
headers: mergeHeaders(init.headers, server.authToken)
|
|
279
|
-
});
|
|
280
|
-
const text = await response.text();
|
|
281
|
-
const payload = text.trim().length > 0 ? (() => {
|
|
282
|
-
try {
|
|
283
|
-
return JSON.parse(text);
|
|
284
|
-
} catch {
|
|
285
|
-
return null;
|
|
286
|
-
}
|
|
287
|
-
})() : null;
|
|
288
|
-
if (!response.ok) {
|
|
289
|
-
const diagnostics = diagnosticMessage(payload);
|
|
290
|
-
const detail = diagnostics ?? (text || response.statusText);
|
|
291
|
-
throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
|
|
292
|
-
}
|
|
293
|
-
return payload;
|
|
294
|
-
}
|
|
295
|
-
async function listWorkspaceTasksViaServer(context, filters = {}) {
|
|
296
|
-
const url = new URL("http://rig.local/api/workspace/tasks");
|
|
297
|
-
appendTaskFilterParams(url, filters);
|
|
298
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
299
|
-
if (!Array.isArray(payload)) {
|
|
300
|
-
throw new CliError2("Rig server returned an invalid task list payload.", 1);
|
|
301
|
-
}
|
|
302
|
-
return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
|
|
303
|
-
}
|
|
304
|
-
async function getWorkspaceTaskViaServer(context, taskId) {
|
|
305
|
-
const payload = await requestServerJson(context, `/api/workspace/tasks/${encodeURIComponent(taskId)}`);
|
|
306
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
307
|
-
return null;
|
|
308
|
-
const task = payload.task;
|
|
309
|
-
return task && typeof task === "object" && !Array.isArray(task) ? task : null;
|
|
310
|
-
}
|
|
311
|
-
async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
|
|
312
|
-
const url = new URL("http://rig.local/api/workspace/tasks/next");
|
|
313
|
-
appendTaskFilterParams(url, filters);
|
|
314
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
315
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
316
|
-
throw new CliError2("Rig server returned an invalid next-task payload.", 1);
|
|
317
|
-
}
|
|
318
|
-
const record = payload;
|
|
319
|
-
const rawTask = record.task;
|
|
320
|
-
const task = rawTask && typeof rawTask === "object" && !Array.isArray(rawTask) ? rawTask : null;
|
|
321
|
-
const count = typeof record.count === "number" && Number.isFinite(record.count) ? record.count : task ? 1 : 0;
|
|
322
|
-
return { task, count };
|
|
323
|
-
}
|
|
324
|
-
async function getRunDetailsViaServer(context, runId) {
|
|
325
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}`);
|
|
326
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
327
|
-
}
|
|
328
|
-
async function getRunLogsViaServer(context, runId, options = {}) {
|
|
329
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/logs`);
|
|
330
|
-
if (options.limit !== undefined)
|
|
331
|
-
url.searchParams.set("limit", String(options.limit));
|
|
332
|
-
if (options.cursor)
|
|
333
|
-
url.searchParams.set("cursor", options.cursor);
|
|
334
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
335
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
336
|
-
}
|
|
337
|
-
async function getRunTimelineViaServer(context, runId, options = {}) {
|
|
338
|
-
const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
|
|
339
|
-
if (options.limit !== undefined)
|
|
340
|
-
url.searchParams.set("limit", String(options.limit));
|
|
341
|
-
if (options.cursor)
|
|
342
|
-
url.searchParams.set("cursor", options.cursor);
|
|
343
|
-
const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
|
|
344
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
|
|
345
|
-
}
|
|
346
|
-
async function stopRunViaServer(context, runId) {
|
|
347
|
-
const payload = await requestServerJson(context, "/api/runs/stop", {
|
|
348
|
-
method: "POST",
|
|
349
|
-
headers: { "content-type": "application/json" },
|
|
350
|
-
body: JSON.stringify({ runId })
|
|
351
|
-
});
|
|
352
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
|
|
353
|
-
}
|
|
354
|
-
async function steerRunViaServer(context, runId, message) {
|
|
355
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/steer`, {
|
|
356
|
-
method: "POST",
|
|
357
|
-
headers: { "content-type": "application/json" },
|
|
358
|
-
body: JSON.stringify({ message })
|
|
359
|
-
});
|
|
360
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
|
|
361
|
-
}
|
|
362
|
-
async function getRunPiSessionViaServer(context, runId) {
|
|
363
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi`);
|
|
364
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
365
|
-
}
|
|
366
|
-
async function getRunPiMessagesViaServer(context, runId) {
|
|
367
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/messages`);
|
|
368
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { messages: [] };
|
|
369
|
-
}
|
|
370
|
-
async function getRunPiStatusViaServer(context, runId) {
|
|
371
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/status`);
|
|
372
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
373
|
-
}
|
|
374
|
-
async function getRunPiCommandsViaServer(context, runId) {
|
|
375
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands`);
|
|
376
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { commands: [] };
|
|
377
|
-
}
|
|
378
|
-
async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
|
|
379
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
|
|
380
|
-
method: "POST",
|
|
381
|
-
headers: { "content-type": "application/json" },
|
|
382
|
-
body: JSON.stringify({ text, streamingBehavior })
|
|
383
|
-
});
|
|
384
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
385
|
-
}
|
|
386
|
-
async function sendRunPiShellViaServer(context, runId, text) {
|
|
387
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/shell`, {
|
|
388
|
-
method: "POST",
|
|
389
|
-
headers: { "content-type": "application/json" },
|
|
390
|
-
body: JSON.stringify({ text })
|
|
391
|
-
});
|
|
392
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
393
|
-
}
|
|
394
|
-
async function runRunPiCommandViaServer(context, runId, text) {
|
|
395
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/commands/run`, {
|
|
396
|
-
method: "POST",
|
|
397
|
-
headers: { "content-type": "application/json" },
|
|
398
|
-
body: JSON.stringify({ text })
|
|
399
|
-
});
|
|
400
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { type: "done" };
|
|
401
|
-
}
|
|
402
|
-
async function respondRunPiExtensionUiViaServer(context, runId, requestId, valueOrCancel) {
|
|
403
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/extension-ui/respond`, {
|
|
404
|
-
method: "POST",
|
|
405
|
-
headers: { "content-type": "application/json" },
|
|
406
|
-
body: JSON.stringify({ requestId, ...valueOrCancel })
|
|
407
|
-
});
|
|
408
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
|
|
409
|
-
}
|
|
410
|
-
async function abortRunPiViaServer(context, runId) {
|
|
411
|
-
const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/abort`, { method: "POST" });
|
|
412
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { aborted: true };
|
|
413
|
-
}
|
|
414
|
-
async function buildRunPiEventsWebSocketUrl(context, runId) {
|
|
415
|
-
const server = await ensureServerForCli(context.projectRoot);
|
|
416
|
-
const url = new URL(`${server.baseUrl.replace(/\/+$/, "")}/api/runs/${encodeURIComponent(runId)}/pi/events`);
|
|
417
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
418
|
-
if (server.authToken)
|
|
419
|
-
url.searchParams.set("token", server.authToken);
|
|
420
|
-
return url.toString();
|
|
421
|
-
}
|
|
422
|
-
async function submitTaskRunViaServer(context, input) {
|
|
423
|
-
const isTaskRun = Boolean(input.taskId);
|
|
424
|
-
const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
|
|
425
|
-
const payload = await requestServerJson(context, endpoint, {
|
|
426
|
-
method: "POST",
|
|
427
|
-
headers: {
|
|
428
|
-
"content-type": "application/json"
|
|
429
|
-
},
|
|
430
|
-
body: JSON.stringify({
|
|
431
|
-
runId: input.runId,
|
|
432
|
-
taskId: input.taskId,
|
|
433
|
-
title: input.title,
|
|
434
|
-
runtimeAdapter: input.runtimeAdapter,
|
|
435
|
-
model: input.model,
|
|
436
|
-
runtimeMode: input.runtimeMode,
|
|
437
|
-
interactionMode: input.interactionMode,
|
|
438
|
-
initialPrompt: input.initialPrompt,
|
|
439
|
-
baselineMode: input.baselineMode,
|
|
440
|
-
prMode: input.prMode,
|
|
441
|
-
executionTarget: "local"
|
|
442
|
-
})
|
|
443
|
-
});
|
|
444
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
445
|
-
throw new CliError2("Rig server returned an invalid run submission payload.", 1);
|
|
446
|
-
}
|
|
447
|
-
const runId = payload.runId;
|
|
448
|
-
if (typeof runId !== "string" || runId.trim().length === 0) {
|
|
449
|
-
throw new CliError2("Rig server returned no runId for the submitted run.", 1);
|
|
450
|
-
}
|
|
451
|
-
return { runId };
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// packages/cli/src/commands/_preflight.ts
|
|
455
|
-
function preflightCheck(id, label, status, detail, remediation) {
|
|
456
|
-
return {
|
|
457
|
-
id,
|
|
458
|
-
label,
|
|
459
|
-
status,
|
|
460
|
-
...detail ? { detail } : {},
|
|
461
|
-
...remediation ? { remediation } : {}
|
|
462
|
-
};
|
|
463
|
-
}
|
|
464
|
-
function message(error) {
|
|
465
|
-
return error instanceof Error ? error.message : String(error);
|
|
466
|
-
}
|
|
467
|
-
function isAuthenticated(payload) {
|
|
468
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
469
|
-
return false;
|
|
470
|
-
const record = payload;
|
|
471
|
-
return record.signedIn === true || record.authenticated === true || record.status === "authenticated" || record.ok === true && typeof record.login === "string" && record.login.trim().length > 0;
|
|
472
|
-
}
|
|
473
|
-
function taskMatchesId(entry, taskId) {
|
|
474
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
475
|
-
return false;
|
|
476
|
-
const record = entry;
|
|
477
|
-
if (record.id === taskId || record.taskId === taskId)
|
|
478
|
-
return true;
|
|
479
|
-
const raw = record.raw;
|
|
480
|
-
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
481
|
-
const rawRecord = raw;
|
|
482
|
-
if (String(rawRecord.number ?? "") === taskId.replace(/^#/, ""))
|
|
483
|
-
return true;
|
|
484
|
-
}
|
|
485
|
-
return false;
|
|
486
|
-
}
|
|
487
|
-
function isActiveRunStatus(status) {
|
|
488
|
-
const normalized = String(status ?? "running").toLowerCase();
|
|
489
|
-
return !["completed", "complete", "done", "merged", "closed", "failed", "cancelled", "canceled", "needs_attention", "needs-attention", "stopped"].includes(normalized);
|
|
490
|
-
}
|
|
491
|
-
function permissionAllowsPr(payload) {
|
|
492
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
493
|
-
return null;
|
|
494
|
-
const record = payload;
|
|
495
|
-
if (record.canOpenPullRequest === true || record.pullRequests === true || record.push === true || record.maintain === true || record.admin === true)
|
|
496
|
-
return true;
|
|
497
|
-
if (record.canOpenPullRequest === false || record.pullRequests === false || record.push === false)
|
|
498
|
-
return false;
|
|
499
|
-
const permissions = record.permissions;
|
|
500
|
-
if (permissions && typeof permissions === "object" && !Array.isArray(permissions)) {
|
|
501
|
-
const p = permissions;
|
|
502
|
-
if (p.push === true || p.maintain === true || p.admin === true)
|
|
503
|
-
return true;
|
|
504
|
-
if (p.push === false && p.maintain !== true && p.admin !== true)
|
|
505
|
-
return false;
|
|
506
|
-
}
|
|
507
|
-
return null;
|
|
508
|
-
}
|
|
509
|
-
function isNotFoundError(error) {
|
|
510
|
-
return /\b(404|not found)\b/i.test(message(error));
|
|
511
|
-
}
|
|
512
|
-
function projectCheckoutReady(payload) {
|
|
513
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
|
514
|
-
return null;
|
|
515
|
-
const record = payload;
|
|
516
|
-
if (record.checkoutReady === true || record.ready === true)
|
|
517
|
-
return true;
|
|
518
|
-
if (record.checkoutReady === false || record.ready === false)
|
|
519
|
-
return false;
|
|
520
|
-
const project = record.project;
|
|
521
|
-
if (project && typeof project === "object" && !Array.isArray(project)) {
|
|
522
|
-
const checkouts = project.checkouts;
|
|
523
|
-
if (Array.isArray(checkouts))
|
|
524
|
-
return checkouts.length > 0;
|
|
525
|
-
}
|
|
526
|
-
return null;
|
|
527
|
-
}
|
|
528
|
-
function activeDuplicateRun(runs, taskId) {
|
|
529
|
-
if (!Array.isArray(runs))
|
|
530
|
-
return null;
|
|
531
|
-
for (const run of runs) {
|
|
532
|
-
if (!run || typeof run !== "object" || Array.isArray(run))
|
|
533
|
-
continue;
|
|
534
|
-
const record = run;
|
|
535
|
-
if ((record.taskId === taskId || record.task === taskId) && isActiveRunStatus(record.status))
|
|
536
|
-
return record;
|
|
537
|
-
}
|
|
538
|
-
return null;
|
|
539
|
-
}
|
|
540
|
-
async function runFastTaskRunPreflight(context, options = {}) {
|
|
541
|
-
const checks = [];
|
|
542
|
-
const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
|
|
543
|
-
const taskId = options.taskId?.trim() || null;
|
|
544
|
-
const requiresCurrentRunApi = Boolean(taskId);
|
|
545
|
-
const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
|
|
546
|
-
const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
|
|
547
|
-
let legacyServerCompatibility = false;
|
|
548
|
-
try {
|
|
549
|
-
await request("/api/server/status");
|
|
550
|
-
checks.push(preflightCheck("server", "Rig server reachable", "pass"));
|
|
551
|
-
} catch (error) {
|
|
552
|
-
if (isNotFoundError(error)) {
|
|
553
|
-
try {
|
|
554
|
-
await request("/health");
|
|
555
|
-
legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
|
|
556
|
-
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"));
|
|
557
|
-
} catch (healthError) {
|
|
558
|
-
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
|
|
559
|
-
}
|
|
560
|
-
} else {
|
|
561
|
-
checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
const repo = readRepoConnection(context.projectRoot);
|
|
565
|
-
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>`."));
|
|
566
|
-
try {
|
|
567
|
-
const auth = await request("/api/github/auth/status");
|
|
568
|
-
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>`."));
|
|
569
|
-
} catch (error) {
|
|
570
|
-
checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
|
|
571
|
-
}
|
|
572
|
-
try {
|
|
573
|
-
const projection = await request("/api/workspace/task-projection");
|
|
574
|
-
checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
|
|
575
|
-
} catch (error) {
|
|
576
|
-
checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
|
|
577
|
-
}
|
|
578
|
-
try {
|
|
579
|
-
const permissions = await request("/api/github/repo/permissions");
|
|
580
|
-
const allowed = permissionAllowsPr(permissions);
|
|
581
|
-
checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
|
|
582
|
-
} catch (error) {
|
|
583
|
-
checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
|
|
584
|
-
}
|
|
585
|
-
if (repo?.project) {
|
|
586
|
-
try {
|
|
587
|
-
const project = await request(`/api/projects/${encodeURIComponent(repo.project)}`);
|
|
588
|
-
const ready = projectCheckoutReady(project);
|
|
589
|
-
checks.push(ready === false ? preflightCheck("remote-checkout", "execution checkout ready", "fail", JSON.stringify(project).slice(0, 120), "Repair the server checkout or rerun `rig init` with a valid checkout strategy.") : preflightCheck("remote-checkout", "execution checkout ready", ready === true ? "pass" : "warn", JSON.stringify(project).slice(0, 120), "Confirm the selected server has a prepared execution checkout."));
|
|
590
|
-
} catch (error) {
|
|
591
|
-
checks.push(preflightCheck("remote-checkout", "execution checkout ready", "warn", message(error), "Run `rig init` or repair the server checkout before launch."));
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
if (taskId) {
|
|
595
|
-
try {
|
|
596
|
-
const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
|
|
597
|
-
const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
|
|
598
|
-
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."));
|
|
599
|
-
} catch (error) {
|
|
600
|
-
checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
|
|
601
|
-
}
|
|
602
|
-
try {
|
|
603
|
-
const runs = await request("/api/runs?limit=200");
|
|
604
|
-
const duplicate = activeDuplicateRun(runs, taskId);
|
|
605
|
-
checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
|
|
606
|
-
} catch (error) {
|
|
607
|
-
checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
if ((options.runtimeAdapter ?? "pi") === "pi") {
|
|
611
|
-
checks.push(preflightCheck("runtime", "worker Pi SDK session daemon", "pass", selectedServer?.connectionKind === "remote" ? "remote worker-owned runtime" : "bundled server-owned runtime"));
|
|
612
|
-
} else {
|
|
613
|
-
checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
|
|
614
|
-
}
|
|
615
|
-
const failures = checks.filter((check) => check.status === "fail");
|
|
616
|
-
if (failures.length > 0) {
|
|
617
|
-
const summary = failures.map((check) => `${check.label}${check.detail ? `: ${check.detail}` : ""}`).join("; ");
|
|
618
|
-
if (failures.some((check) => check.id === "duplicate-active-run") && taskId) {
|
|
619
|
-
throw new CliError2(`Task ${taskId} already has an active Rig run. ${summary}`, 1);
|
|
620
|
-
}
|
|
621
|
-
throw new CliError2(`Task run preflight failed: ${summary}`, 1);
|
|
622
|
-
}
|
|
623
|
-
return { ok: true, checks };
|
|
624
|
-
}
|
|
625
|
-
async function runProjectMainSyncPreflight(context, options) {
|
|
626
|
-
if (context.dryRun) {
|
|
627
|
-
if (context.outputMode === "text" && !options.disabled) {
|
|
628
|
-
console.log("[dry-run] project-rig pre-run sync check");
|
|
629
|
-
}
|
|
630
|
-
return;
|
|
631
|
-
}
|
|
632
|
-
const result = await ensureProjectMainFreshBeforeRun({
|
|
633
|
-
projectRoot: context.projectRoot,
|
|
634
|
-
disabled: options.disabled,
|
|
635
|
-
runBootstrap: async () => {
|
|
636
|
-
const bootstrap = await context.runCommand(["bun", "run", "bootstrap"]);
|
|
637
|
-
if (bootstrap.exitCode !== 0) {
|
|
638
|
-
throw new CliError2(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
});
|
|
642
|
-
if (context.outputMode !== "text") {
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
switch (result.status) {
|
|
646
|
-
case "disabled":
|
|
647
|
-
console.log("Project pre-run sync skipped (--skip-project-sync).");
|
|
648
|
-
break;
|
|
649
|
-
case "skipped_not_main":
|
|
650
|
-
console.log(`Project pre-run sync skipped (current branch: ${result.branch}).`);
|
|
651
|
-
break;
|
|
652
|
-
case "up_to_date":
|
|
653
|
-
break;
|
|
654
|
-
case "local_ahead":
|
|
655
|
-
console.log(`Project pre-run sync skipped (local main ahead by ${result.localAhead} commit(s)).`);
|
|
656
|
-
break;
|
|
657
|
-
case "updated":
|
|
658
|
-
console.log(`Project pre-run sync updated local main from origin/main (+${result.remoteAhead}) and bootstrapped.`);
|
|
659
|
-
break;
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
// packages/cli/src/withMutedConsole.ts
|
|
664
|
-
function isPromise(value) {
|
|
665
|
-
if (typeof value !== "object" && typeof value !== "function") {
|
|
666
|
-
return false;
|
|
667
|
-
}
|
|
668
|
-
return value !== null && typeof value.then === "function";
|
|
669
|
-
}
|
|
670
|
-
function withMutedConsole(mute, fn) {
|
|
671
|
-
if (!mute) {
|
|
672
|
-
return fn();
|
|
673
|
-
}
|
|
674
|
-
const originalLog = console.log;
|
|
675
|
-
const originalWarn = console.warn;
|
|
676
|
-
const originalInfo = console.info;
|
|
677
|
-
const restore = () => {
|
|
678
|
-
console.log = originalLog;
|
|
679
|
-
console.warn = originalWarn;
|
|
680
|
-
console.info = originalInfo;
|
|
681
|
-
};
|
|
682
|
-
console.log = () => {};
|
|
683
|
-
console.warn = () => {};
|
|
684
|
-
console.info = () => {};
|
|
685
|
-
try {
|
|
686
|
-
const result = fn();
|
|
687
|
-
if (isPromise(result)) {
|
|
688
|
-
return result.finally(restore);
|
|
689
|
-
}
|
|
690
|
-
restore();
|
|
691
|
-
return result;
|
|
692
|
-
} catch (error) {
|
|
693
|
-
restore();
|
|
694
|
-
throw error;
|
|
695
|
-
} finally {
|
|
696
|
-
if (console.log === originalLog) {
|
|
697
|
-
restore();
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
// packages/cli/src/commands/_task-picker.ts
|
|
703
|
-
import { cancel, isCancel, select } from "@clack/prompts";
|
|
704
|
-
|
|
705
|
-
// packages/cli/src/commands/_operator-surface.ts
|
|
706
|
-
import { createInterface } from "readline";
|
|
707
|
-
import { createInterface as createPromptInterface } from "readline/promises";
|
|
708
|
-
var CANONICAL_STAGES = [
|
|
709
|
-
"Connect",
|
|
710
|
-
"GitHub/task sync",
|
|
711
|
-
"Prepare workspace",
|
|
712
|
-
"Launch Pi",
|
|
713
|
-
"Plan",
|
|
714
|
-
"Implement",
|
|
715
|
-
"Validate",
|
|
716
|
-
"Commit",
|
|
717
|
-
"Open PR",
|
|
718
|
-
"Review/CI",
|
|
719
|
-
"Merge",
|
|
720
|
-
"Complete"
|
|
721
|
-
];
|
|
722
|
-
function logDetail(log) {
|
|
723
|
-
return typeof log.detail === "string" ? log.detail.trim() : "";
|
|
724
|
-
}
|
|
725
|
-
function parseProviderProtocolLog(title, detail) {
|
|
726
|
-
if (title.trim().toLowerCase() !== "agent output")
|
|
727
|
-
return null;
|
|
728
|
-
if (!detail.startsWith("{") || !detail.endsWith("}"))
|
|
729
|
-
return null;
|
|
730
|
-
try {
|
|
731
|
-
const record = JSON.parse(detail);
|
|
732
|
-
if (!record || typeof record !== "object" || Array.isArray(record))
|
|
733
|
-
return null;
|
|
734
|
-
const type = record.type;
|
|
735
|
-
return typeof type === "string" && [
|
|
736
|
-
"assistant",
|
|
737
|
-
"message_start",
|
|
738
|
-
"message_update",
|
|
739
|
-
"message_end",
|
|
740
|
-
"stream_event",
|
|
741
|
-
"tool_result",
|
|
742
|
-
"tool_execution_start",
|
|
743
|
-
"tool_execution_update",
|
|
744
|
-
"tool_execution_end",
|
|
745
|
-
"turn_start",
|
|
746
|
-
"turn_end"
|
|
747
|
-
].includes(type) ? record : null;
|
|
748
|
-
} catch {
|
|
749
|
-
return null;
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
function renderProviderProtocolLog(record) {
|
|
753
|
-
const type = typeof record.type === "string" ? record.type : "";
|
|
754
|
-
if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
|
|
755
|
-
const toolName = String(record.toolName ?? record.name ?? "tool");
|
|
756
|
-
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";
|
|
757
|
-
return `[Pi tool] ${toolName} ${status}`;
|
|
758
|
-
}
|
|
759
|
-
return null;
|
|
760
|
-
}
|
|
761
|
-
function entryId(entry, fallback) {
|
|
762
|
-
return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
|
|
763
|
-
}
|
|
764
|
-
function renderOperatorSnapshot(snapshot) {
|
|
765
|
-
const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
|
|
766
|
-
const runId = String(run.runId ?? run.id ?? "run");
|
|
767
|
-
const status = String(run.status ?? "unknown");
|
|
768
|
-
const logs = snapshot.logs ?? [];
|
|
769
|
-
const latestByStage = new Map;
|
|
770
|
-
for (const log of logs) {
|
|
771
|
-
const title = String(log.title ?? "").toLowerCase();
|
|
772
|
-
const stageName = String(log.stage ?? "").toLowerCase();
|
|
773
|
-
const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
|
|
774
|
-
if (stage)
|
|
775
|
-
latestByStage.set(stage, log);
|
|
776
|
-
}
|
|
777
|
-
const stageLines = CANONICAL_STAGES.flatMap((stage) => {
|
|
778
|
-
const match = latestByStage.get(stage);
|
|
779
|
-
return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
|
|
780
|
-
});
|
|
781
|
-
return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
|
|
782
|
-
`);
|
|
783
|
-
}
|
|
784
|
-
function createPiRunStreamRenderer(output = process.stdout) {
|
|
785
|
-
let lastSnapshot = "";
|
|
786
|
-
const assistantTextById = new Map;
|
|
787
|
-
const seenTimeline = new Set;
|
|
788
|
-
const seenLogs = new Set;
|
|
789
|
-
const writeLine = (line) => output.write(`${line}
|
|
790
|
-
`);
|
|
791
|
-
return {
|
|
792
|
-
renderSnapshot(snapshot) {
|
|
793
|
-
const rendered = renderOperatorSnapshot(snapshot);
|
|
794
|
-
if (rendered && rendered !== lastSnapshot) {
|
|
795
|
-
writeLine(rendered);
|
|
796
|
-
lastSnapshot = rendered;
|
|
797
|
-
}
|
|
798
|
-
},
|
|
799
|
-
renderTimeline(entries) {
|
|
800
|
-
for (const [index, entry] of entries.entries()) {
|
|
801
|
-
const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
|
|
802
|
-
if (entry.type === "assistant_message" && typeof entry.text === "string") {
|
|
803
|
-
const text = entry.text;
|
|
804
|
-
const previousText = assistantTextById.get(id) ?? "";
|
|
805
|
-
if (!previousText && text.trim()) {
|
|
806
|
-
writeLine("[Pi assistant]");
|
|
807
|
-
}
|
|
808
|
-
if (text.startsWith(previousText)) {
|
|
809
|
-
const delta = text.slice(previousText.length);
|
|
810
|
-
if (delta)
|
|
811
|
-
output.write(delta);
|
|
812
|
-
} else if (text.trim() && text !== previousText) {
|
|
813
|
-
if (previousText)
|
|
814
|
-
writeLine(`
|
|
815
|
-
[Pi assistant]`);
|
|
816
|
-
output.write(text);
|
|
817
|
-
}
|
|
818
|
-
assistantTextById.set(id, text);
|
|
819
|
-
continue;
|
|
820
|
-
}
|
|
821
|
-
if (seenTimeline.has(id))
|
|
822
|
-
continue;
|
|
823
|
-
seenTimeline.add(id);
|
|
824
|
-
if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
|
|
825
|
-
writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
|
|
826
|
-
continue;
|
|
827
|
-
}
|
|
828
|
-
if (entry.type === "timeline_warning") {
|
|
829
|
-
writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
},
|
|
833
|
-
renderLogs(entries) {
|
|
834
|
-
for (const [index, entry] of entries.entries()) {
|
|
835
|
-
const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
|
|
836
|
-
if (seenLogs.has(id))
|
|
837
|
-
continue;
|
|
838
|
-
seenLogs.add(id);
|
|
839
|
-
const title = String(entry.title ?? "");
|
|
840
|
-
if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
|
|
841
|
-
continue;
|
|
842
|
-
const detail = logDetail(entry);
|
|
843
|
-
if (!detail)
|
|
844
|
-
continue;
|
|
845
|
-
const protocolRecord = parseProviderProtocolLog(title, detail);
|
|
846
|
-
if (protocolRecord) {
|
|
847
|
-
const protocolLine = renderProviderProtocolLog(protocolRecord);
|
|
848
|
-
if (protocolLine)
|
|
849
|
-
writeLine(protocolLine);
|
|
850
|
-
continue;
|
|
851
|
-
}
|
|
852
|
-
writeLine(`[${title || "Rig log"}] ${detail}`);
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
};
|
|
856
|
-
}
|
|
857
|
-
function createOperatorSurface(options = {}) {
|
|
858
|
-
const input = options.input ?? process.stdin;
|
|
859
|
-
const output = options.output ?? process.stdout;
|
|
860
|
-
const errorOutput = options.errorOutput ?? process.stderr;
|
|
861
|
-
const renderer = createPiRunStreamRenderer(output);
|
|
862
|
-
const writeLine = (line) => output.write(`${line}
|
|
863
|
-
`);
|
|
864
|
-
return {
|
|
865
|
-
mode: "pi-compatible-text",
|
|
866
|
-
...renderer,
|
|
867
|
-
info: writeLine,
|
|
868
|
-
error: (message2) => errorOutput.write(`${message2}
|
|
869
|
-
`),
|
|
870
|
-
attachCommandInput(handler) {
|
|
871
|
-
if (options.interactive === false || !input.isTTY)
|
|
872
|
-
return null;
|
|
873
|
-
const rl = createInterface({ input, output: process.stdout, terminal: false });
|
|
874
|
-
rl.on("line", (line) => {
|
|
875
|
-
Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
876
|
-
});
|
|
877
|
-
return { close: () => rl.close() };
|
|
878
|
-
}
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
|
-
function taskId(task) {
|
|
882
|
-
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
883
|
-
}
|
|
884
|
-
function taskTitle(task) {
|
|
885
|
-
return typeof task.title === "string" && task.title.trim() ? task.title : "Untitled task";
|
|
886
|
-
}
|
|
887
|
-
function taskStatus(task) {
|
|
888
|
-
return typeof task.status === "string" && task.status.trim() ? task.status : "unknown";
|
|
889
|
-
}
|
|
890
|
-
function renderTaskPickerRows(tasks) {
|
|
891
|
-
return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
|
|
892
|
-
}
|
|
893
|
-
async function promptForTaskSelection(question) {
|
|
894
|
-
const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
|
|
895
|
-
try {
|
|
896
|
-
return await rl.question(question);
|
|
897
|
-
} finally {
|
|
898
|
-
rl.close();
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
// packages/cli/src/commands/_task-picker.ts
|
|
903
|
-
function taskId2(task) {
|
|
904
|
-
return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
|
|
905
|
-
}
|
|
906
|
-
async function selectTaskWithTextPicker(tasks, io = {}) {
|
|
907
|
-
if (tasks.length === 0)
|
|
908
|
-
return null;
|
|
909
|
-
if (tasks.length === 1)
|
|
910
|
-
return tasks[0];
|
|
911
|
-
const isTty = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
912
|
-
if (!isTty) {
|
|
913
|
-
throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
|
|
914
|
-
}
|
|
915
|
-
if (io.prompt || io.renderer) {
|
|
916
|
-
const prompt = io.prompt ?? promptForTaskSelection;
|
|
917
|
-
const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
|
|
918
|
-
`) };
|
|
919
|
-
renderer.writeLine("Select Rig task:");
|
|
920
|
-
for (const row of renderTaskPickerRows(tasks))
|
|
921
|
-
renderer.writeLine(` ${row}`);
|
|
922
|
-
const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
|
|
923
|
-
if (!answer2)
|
|
924
|
-
return null;
|
|
925
|
-
if (/^\d+$/.test(answer2)) {
|
|
926
|
-
const index2 = Number.parseInt(answer2, 10) - 1;
|
|
927
|
-
return tasks[index2] ?? null;
|
|
928
|
-
}
|
|
929
|
-
return tasks.find((task) => taskId2(task) === answer2) ?? null;
|
|
930
|
-
}
|
|
931
|
-
const options = tasks.map((task, index2) => ({
|
|
932
|
-
value: `${index2}`,
|
|
933
|
-
label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
|
|
934
|
-
hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
|
|
935
|
-
}));
|
|
936
|
-
const answer = await select({
|
|
937
|
-
message: "Select Rig task",
|
|
938
|
-
options
|
|
939
|
-
});
|
|
940
|
-
if (isCancel(answer)) {
|
|
941
|
-
cancel("No task selected.");
|
|
942
|
-
return null;
|
|
943
|
-
}
|
|
944
|
-
const index = Number.parseInt(String(answer), 10);
|
|
945
|
-
return Number.isFinite(index) ? tasks[index] ?? null : null;
|
|
946
|
-
}
|
|
947
|
-
|
|
948
|
-
// packages/cli/src/commands/_pi-frontend.ts
|
|
949
|
-
import { mkdtempSync, rmSync } from "fs";
|
|
950
|
-
import { tmpdir } from "os";
|
|
951
|
-
import { join } from "path";
|
|
952
|
-
import { main as runPiMain } from "@earendil-works/pi-coding-agent";
|
|
953
|
-
|
|
954
|
-
// packages/cli/src/commands/_pi-worker-bridge-extension.ts
|
|
955
|
-
var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
956
|
-
var MAX_TRANSCRIPT_LINES = 120;
|
|
957
|
-
function recordOf(value) {
|
|
958
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
959
|
-
}
|
|
960
|
-
function asText(value) {
|
|
961
|
-
if (typeof value === "string")
|
|
962
|
-
return value;
|
|
963
|
-
if (value === null || value === undefined)
|
|
964
|
-
return "";
|
|
965
|
-
if (typeof value === "number" || typeof value === "boolean")
|
|
966
|
-
return String(value);
|
|
967
|
-
try {
|
|
968
|
-
return JSON.stringify(value);
|
|
969
|
-
} catch {
|
|
970
|
-
return String(value);
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
function textFromContent(content) {
|
|
974
|
-
if (typeof content === "string")
|
|
975
|
-
return content;
|
|
976
|
-
if (!Array.isArray(content))
|
|
977
|
-
return asText(content);
|
|
978
|
-
return content.flatMap((part) => {
|
|
979
|
-
const item = recordOf(part);
|
|
980
|
-
if (!item)
|
|
981
|
-
return [];
|
|
982
|
-
if (typeof item.text === "string")
|
|
983
|
-
return [item.text];
|
|
984
|
-
if (typeof item.content === "string")
|
|
985
|
-
return [item.content];
|
|
986
|
-
if (item.type === "toolCall")
|
|
987
|
-
return [`\u23FA ${String(item.name ?? "tool")} ${asText(item.arguments ?? "")}`.trim()];
|
|
988
|
-
if (item.type === "toolResult")
|
|
989
|
-
return [`\u21B3 ${asText(item.content ?? item.result ?? "")}`.trim()];
|
|
990
|
-
return [];
|
|
991
|
-
}).join(`
|
|
992
|
-
`);
|
|
993
|
-
}
|
|
994
|
-
function appendTranscript(state, label, text) {
|
|
995
|
-
const trimmed = text.trimEnd();
|
|
996
|
-
if (!trimmed)
|
|
997
|
-
return;
|
|
998
|
-
const lines = trimmed.split(/\r?\n/);
|
|
999
|
-
state.transcript.push(`${label}: ${lines[0] ?? ""}`);
|
|
1000
|
-
for (const line of lines.slice(1))
|
|
1001
|
-
state.transcript.push(` ${line}`);
|
|
1002
|
-
if (state.transcript.length > MAX_TRANSCRIPT_LINES) {
|
|
1003
|
-
state.transcript.splice(0, state.transcript.length - MAX_TRANSCRIPT_LINES);
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
function nativePiUi(ctx) {
|
|
1007
|
-
const ui = ctx.ui;
|
|
1008
|
-
return typeof ui.emitSessionEvent === "function" && typeof ui.appendSessionMessages === "function" ? ui : null;
|
|
1009
|
-
}
|
|
1010
|
-
function syncNativeDisplayCwd(ctx, state) {
|
|
1011
|
-
const ui = nativePiUi(ctx);
|
|
1012
|
-
if (ui?.setDisplayCwd && state.cwd)
|
|
1013
|
-
ui.setDisplayCwd(state.cwd);
|
|
1014
|
-
}
|
|
1015
|
-
function parseExtensionUiRequest(value) {
|
|
1016
|
-
const request = recordOf(value) ?? {};
|
|
1017
|
-
const requestId = String(request.requestId ?? request.id ?? `ui-${Date.now()}`);
|
|
1018
|
-
const method = String(request.method ?? request.type ?? "input");
|
|
1019
|
-
const prompt = asText(request.prompt ?? request.message ?? request.title ?? method);
|
|
1020
|
-
const rawOptions = Array.isArray(request.options) ? request.options : Array.isArray(request.items) ? request.items : [];
|
|
1021
|
-
const options = rawOptions.map((option) => {
|
|
1022
|
-
const record = recordOf(option);
|
|
1023
|
-
return record ? asText(record.label ?? record.value ?? record.name ?? option) : asText(option);
|
|
1024
|
-
}).filter(Boolean);
|
|
1025
|
-
return { requestId, method, prompt, options };
|
|
1026
|
-
}
|
|
1027
|
-
function renderBridgeWidget(state) {
|
|
1028
|
-
const statusParts = [
|
|
1029
|
-
state.wsConnected ? "live WS" : "WS pending",
|
|
1030
|
-
state.status,
|
|
1031
|
-
state.model,
|
|
1032
|
-
state.cwd
|
|
1033
|
-
].filter(Boolean);
|
|
1034
|
-
const lines = [`Worker Pi daemon bridge \xB7 ${statusParts.join(" \xB7 ")}`];
|
|
1035
|
-
if (state.activity)
|
|
1036
|
-
lines.push(state.activity);
|
|
1037
|
-
if (state.commands.length > 0) {
|
|
1038
|
-
lines.push(`Worker commands: ${state.commands.slice(0, 10).join(", ")}${state.commands.length > 10 ? ", \u2026" : ""}`);
|
|
1039
|
-
}
|
|
1040
|
-
lines.push("");
|
|
1041
|
-
if (state.transcript.length > 0) {
|
|
1042
|
-
lines.push(...state.transcript.slice(-MAX_TRANSCRIPT_LINES));
|
|
1043
|
-
} else {
|
|
1044
|
-
lines.push("Waiting for worker Pi daemon transcript\u2026");
|
|
1045
|
-
}
|
|
1046
|
-
if (state.pendingUi) {
|
|
1047
|
-
lines.push("");
|
|
1048
|
-
lines.push(`Extension UI request \xB7 ${state.pendingUi.method}`);
|
|
1049
|
-
lines.push(state.pendingUi.prompt);
|
|
1050
|
-
state.pendingUi.options.forEach((option, index) => lines.push(`${index + 1}. ${option}`));
|
|
1051
|
-
lines.push("Reply in the Pi editor. /cancel cancels this request.");
|
|
1052
|
-
}
|
|
1053
|
-
return lines;
|
|
1054
|
-
}
|
|
1055
|
-
function updatePiUi(ctx, state) {
|
|
1056
|
-
ctx.ui.setTitle("Pi \xB7 Rig worker daemon");
|
|
1057
|
-
ctx.ui.setStatus("rig-worker-pi", state.wsConnected ? "worker Pi WS live" : state.status);
|
|
1058
|
-
syncNativeDisplayCwd(ctx, state);
|
|
1059
|
-
if (state.nativeStream && nativePiUi(ctx)) {
|
|
1060
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", undefined);
|
|
1061
|
-
return;
|
|
1062
|
-
}
|
|
1063
|
-
ctx.ui.setWorkingVisible(false);
|
|
1064
|
-
ctx.ui.setWidget("rig-worker-pi-transcript", [`Worker Pi daemon bridge \xB7 degraded widget transcript`, ...renderBridgeWidget(state)], { placement: "aboveEditor" });
|
|
1065
|
-
}
|
|
1066
|
-
function applyStatus(state, payload) {
|
|
1067
|
-
const status = recordOf(payload.status) ?? payload;
|
|
1068
|
-
state.streaming = status.isStreaming === true || status.isCompacting === true || status.isBashRunning === true;
|
|
1069
|
-
state.cwd = typeof status.cwd === "string" ? status.cwd : state.cwd;
|
|
1070
|
-
state.model = typeof status.model === "string" ? status.model : state.model;
|
|
1071
|
-
const pending = typeof status.pendingMessageCount === "number" ? status.pendingMessageCount : 0;
|
|
1072
|
-
state.status = `${state.streaming ? "streaming" : "idle"}${pending ? ` \xB7 ${pending} queued` : ""}`;
|
|
1073
|
-
}
|
|
1074
|
-
function applyMessage(state, message2) {
|
|
1075
|
-
const record = recordOf(message2);
|
|
1076
|
-
if (!record)
|
|
1077
|
-
return;
|
|
1078
|
-
const role = String(record.role ?? "system");
|
|
1079
|
-
const label = role === "assistant" ? "Pi" : role === "user" ? "You" : role === "tool" || role === "toolResult" ? "Tool" : "System";
|
|
1080
|
-
appendTranscript(state, label, textFromContent(record.content ?? record.message ?? record.text ?? ""));
|
|
1081
|
-
}
|
|
1082
|
-
function applyPiEvent(ctx, state, eventValue) {
|
|
1083
|
-
const event = recordOf(eventValue);
|
|
1084
|
-
if (!event)
|
|
1085
|
-
return;
|
|
1086
|
-
const type = String(event.type ?? "event");
|
|
1087
|
-
if (type === "agent_start") {
|
|
1088
|
-
state.streaming = true;
|
|
1089
|
-
state.status = "streaming";
|
|
1090
|
-
} else if (type === "agent_end") {
|
|
1091
|
-
state.streaming = false;
|
|
1092
|
-
state.status = "idle";
|
|
1093
|
-
} else if (type === "queue_update") {
|
|
1094
|
-
const steering = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
1095
|
-
const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
1096
|
-
state.status = `queued \xB7 steer ${steering} \xB7 follow-up ${followUp}`;
|
|
1097
|
-
}
|
|
1098
|
-
const native = nativePiUi(ctx);
|
|
1099
|
-
if (state.nativeStream && native?.emitSessionEvent) {
|
|
1100
|
-
native.emitSessionEvent(eventValue);
|
|
1101
|
-
return;
|
|
1102
|
-
}
|
|
1103
|
-
if (type === "agent_end") {
|
|
1104
|
-
appendTranscript(state, "System", "Agent turn complete.");
|
|
1105
|
-
return;
|
|
1106
|
-
}
|
|
1107
|
-
if (type === "message_start" || type === "message_end" || type === "turn_end") {
|
|
1108
|
-
applyMessage(state, event.message);
|
|
1109
|
-
return;
|
|
1110
|
-
}
|
|
1111
|
-
if (type === "message_update") {
|
|
1112
|
-
const assistantEvent = recordOf(event.assistantMessageEvent);
|
|
1113
|
-
const delta = typeof assistantEvent?.delta === "string" ? assistantEvent.delta : typeof assistantEvent?.text === "string" ? assistantEvent.text : "";
|
|
1114
|
-
if (delta)
|
|
1115
|
-
appendTranscript(state, assistantEvent?.type === "thinking_delta" ? "Thinking" : "Pi", delta);
|
|
1116
|
-
return;
|
|
1117
|
-
}
|
|
1118
|
-
if (type === "tool_execution_start") {
|
|
1119
|
-
appendTranscript(state, "Tool", `${String(event.toolName ?? "tool")} ${asText(event.args ?? "")}`.trim());
|
|
1120
|
-
return;
|
|
1121
|
-
}
|
|
1122
|
-
if (type === "tool_execution_update") {
|
|
1123
|
-
appendTranscript(state, "Tool", asText(event.partialResult ?? ""));
|
|
1124
|
-
return;
|
|
1125
|
-
}
|
|
1126
|
-
if (type === "tool_execution_end") {
|
|
1127
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", asText(event.result ?? `${String(event.toolName ?? "tool")} complete`));
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
function firstPendingShell(state) {
|
|
1131
|
-
return state.pendingShells[0];
|
|
1132
|
-
}
|
|
1133
|
-
function finishPendingShell(state, shell, result) {
|
|
1134
|
-
const index = state.pendingShells.indexOf(shell);
|
|
1135
|
-
if (index !== -1)
|
|
1136
|
-
state.pendingShells.splice(index, 1);
|
|
1137
|
-
shell.resolve(result);
|
|
1138
|
-
}
|
|
1139
|
-
function failPendingShell(state, shell, error) {
|
|
1140
|
-
const index = state.pendingShells.indexOf(shell);
|
|
1141
|
-
if (index !== -1)
|
|
1142
|
-
state.pendingShells.splice(index, 1);
|
|
1143
|
-
shell.reject(error);
|
|
1144
|
-
}
|
|
1145
|
-
function applyUiEvent(state, value) {
|
|
1146
|
-
const event = recordOf(value);
|
|
1147
|
-
if (!event)
|
|
1148
|
-
return;
|
|
1149
|
-
const type = String(event.type ?? "ui");
|
|
1150
|
-
if (type === "shell.chunk") {
|
|
1151
|
-
const pending = firstPendingShell(state);
|
|
1152
|
-
const chunk = asText(event.chunk);
|
|
1153
|
-
if (pending) {
|
|
1154
|
-
pending.sawChunk = true;
|
|
1155
|
-
pending.onData(Buffer.from(chunk));
|
|
1156
|
-
} else {
|
|
1157
|
-
appendTranscript(state, "Tool", chunk);
|
|
1158
|
-
}
|
|
1159
|
-
return;
|
|
1160
|
-
}
|
|
1161
|
-
if (type === "shell.end") {
|
|
1162
|
-
const pending = firstPendingShell(state);
|
|
1163
|
-
const output = asText(event.output ?? "");
|
|
1164
|
-
const exitCode = typeof event.exitCode === "number" ? event.exitCode : event.isError === true ? 1 : 0;
|
|
1165
|
-
if (pending) {
|
|
1166
|
-
if (output && !pending.sawChunk)
|
|
1167
|
-
pending.onData(Buffer.from(output));
|
|
1168
|
-
finishPendingShell(state, pending, { exitCode });
|
|
1169
|
-
} else {
|
|
1170
|
-
appendTranscript(state, event.isError === true ? "Error" : "Tool", output || `exit ${String(exitCode)}`);
|
|
1171
|
-
}
|
|
1172
|
-
return;
|
|
1173
|
-
}
|
|
1174
|
-
if (type === "shell.start") {
|
|
1175
|
-
if (!firstPendingShell(state))
|
|
1176
|
-
appendTranscript(state, "Tool", `$ ${asText(event.command)}`);
|
|
1177
|
-
return;
|
|
1178
|
-
}
|
|
1179
|
-
appendTranscript(state, "System", `${type}: ${asText(event)}`);
|
|
1180
|
-
}
|
|
1181
|
-
function applyEnvelope(ctx, state, envelopeValue) {
|
|
1182
|
-
const envelope = recordOf(envelopeValue);
|
|
1183
|
-
if (!envelope)
|
|
1184
|
-
return;
|
|
1185
|
-
const type = String(envelope.type ?? "");
|
|
1186
|
-
if (type === "ready") {
|
|
1187
|
-
const metadata = recordOf(envelope.metadata);
|
|
1188
|
-
state.cwd = typeof metadata?.cwd === "string" ? metadata.cwd : state.cwd;
|
|
1189
|
-
state.status = "worker Pi daemon ready";
|
|
1190
|
-
if (!state.nativeStream)
|
|
1191
|
-
appendTranscript(state, "System", "Connected to worker Pi daemon.");
|
|
1192
|
-
} else if (type === "status.update") {
|
|
1193
|
-
applyStatus(state, envelope);
|
|
1194
|
-
} else if (type === "activity.update") {
|
|
1195
|
-
const activity = recordOf(envelope.activity);
|
|
1196
|
-
state.activity = [activity?.label, activity?.detail].map(asText).filter(Boolean).join(" \u2014 ");
|
|
1197
|
-
} else if (type === "extension_ui_request") {
|
|
1198
|
-
state.pendingUi = parseExtensionUiRequest(envelope.request);
|
|
1199
|
-
appendTranscript(state, "System", `Extension UI request: ${state.pendingUi.prompt}`);
|
|
1200
|
-
} else if (type === "pi.ui_event") {
|
|
1201
|
-
applyUiEvent(state, envelope.event);
|
|
1202
|
-
} else if (type === "pi.event") {
|
|
1203
|
-
applyPiEvent(ctx, state, envelope.event);
|
|
1204
|
-
} else if (type === "error") {
|
|
1205
|
-
appendTranscript(state, "Error", asText(envelope.message ?? envelope.detail ?? "unknown error"));
|
|
1206
|
-
}
|
|
1207
|
-
syncNativeDisplayCwd(ctx, state);
|
|
1208
|
-
}
|
|
1209
|
-
async function waitForWorkerReady(options, ctx, state) {
|
|
1210
|
-
while (true) {
|
|
1211
|
-
const session = await getRunPiSessionViaServer(options.context, options.runId).catch((error) => ({
|
|
1212
|
-
ready: false,
|
|
1213
|
-
status: error instanceof Error ? error.message : String(error),
|
|
1214
|
-
retryAfterMs: 1000
|
|
1215
|
-
}));
|
|
1216
|
-
if (session.ready === false) {
|
|
1217
|
-
const status = String(session.status ?? "starting");
|
|
1218
|
-
state.status = `waiting for worker Pi daemon \xB7 ${status}`;
|
|
1219
|
-
updatePiUi(ctx, state);
|
|
1220
|
-
if (TERMINAL_RUN_STATUSES.has(status.toLowerCase())) {
|
|
1221
|
-
appendTranscript(state, "Error", `Run ended before worker Pi daemon became ready: ${status}`);
|
|
1222
|
-
return false;
|
|
1223
|
-
}
|
|
1224
|
-
await Bun.sleep(typeof session.retryAfterMs === "number" ? session.retryAfterMs : 750);
|
|
1225
|
-
continue;
|
|
1226
|
-
}
|
|
1227
|
-
const sessionRecord = recordOf(session) ?? {};
|
|
1228
|
-
applyEnvelope(ctx, state, { type: "ready", metadata: sessionRecord.metadata ?? sessionRecord });
|
|
1229
|
-
updatePiUi(ctx, state);
|
|
1230
|
-
return true;
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
function parseWsPayload(message2) {
|
|
1234
|
-
if (typeof message2.data === "string")
|
|
1235
|
-
return JSON.parse(message2.data);
|
|
1236
|
-
return JSON.parse(Buffer.from(message2.data).toString("utf8"));
|
|
1237
|
-
}
|
|
1238
|
-
async function connectWorkerStream(options, ctx, state) {
|
|
1239
|
-
const ready = await waitForWorkerReady(options, ctx, state);
|
|
1240
|
-
if (!ready)
|
|
1241
|
-
return;
|
|
1242
|
-
let catchupDone = false;
|
|
1243
|
-
const buffered = [];
|
|
1244
|
-
const wsUrl = await buildRunPiEventsWebSocketUrl(options.context, options.runId);
|
|
1245
|
-
const socket = new WebSocket(wsUrl);
|
|
1246
|
-
const closePromise = new Promise((resolve3) => {
|
|
1247
|
-
socket.onopen = () => {
|
|
1248
|
-
state.wsConnected = true;
|
|
1249
|
-
state.status = "live worker Pi WebSocket connected";
|
|
1250
|
-
updatePiUi(ctx, state);
|
|
1251
|
-
};
|
|
1252
|
-
socket.onmessage = (message2) => {
|
|
1253
|
-
try {
|
|
1254
|
-
const payload = parseWsPayload(message2);
|
|
1255
|
-
if (!catchupDone)
|
|
1256
|
-
buffered.push(payload);
|
|
1257
|
-
else {
|
|
1258
|
-
applyEnvelope(ctx, state, payload);
|
|
1259
|
-
updatePiUi(ctx, state);
|
|
1260
|
-
}
|
|
1261
|
-
} catch (error) {
|
|
1262
|
-
appendTranscript(state, "Error", `Unparseable worker Pi event: ${error instanceof Error ? error.message : String(error)}`);
|
|
1263
|
-
updatePiUi(ctx, state);
|
|
1264
|
-
}
|
|
1265
|
-
};
|
|
1266
|
-
socket.onerror = () => socket.close();
|
|
1267
|
-
socket.onclose = () => {
|
|
1268
|
-
state.wsConnected = false;
|
|
1269
|
-
state.status = "worker Pi WebSocket disconnected";
|
|
1270
|
-
updatePiUi(ctx, state);
|
|
1271
|
-
resolve3();
|
|
1272
|
-
};
|
|
1273
|
-
});
|
|
1274
|
-
try {
|
|
1275
|
-
const [messagesPayload, statusPayload, commandsPayload] = await Promise.all([
|
|
1276
|
-
getRunPiMessagesViaServer(options.context, options.runId),
|
|
1277
|
-
getRunPiStatusViaServer(options.context, options.runId),
|
|
1278
|
-
getRunPiCommandsViaServer(options.context, options.runId)
|
|
1279
|
-
]);
|
|
1280
|
-
const messages = Array.isArray(messagesPayload.messages) ? messagesPayload.messages : [];
|
|
1281
|
-
const native = nativePiUi(ctx);
|
|
1282
|
-
if (state.nativeStream && native?.appendSessionMessages)
|
|
1283
|
-
native.appendSessionMessages(messages);
|
|
1284
|
-
else
|
|
1285
|
-
for (const message2 of messages)
|
|
1286
|
-
applyMessage(state, message2);
|
|
1287
|
-
applyStatus(state, statusPayload);
|
|
1288
|
-
const commands = Array.isArray(commandsPayload.commands) ? commandsPayload.commands : [];
|
|
1289
|
-
state.commands = commands.flatMap((command) => {
|
|
1290
|
-
const record = recordOf(command);
|
|
1291
|
-
return typeof record?.name === "string" ? [`/${record.name}`] : [];
|
|
1292
|
-
});
|
|
1293
|
-
catchupDone = true;
|
|
1294
|
-
for (const payload of buffered.splice(0))
|
|
1295
|
-
applyEnvelope(ctx, state, payload);
|
|
1296
|
-
updatePiUi(ctx, state);
|
|
1297
|
-
} catch (error) {
|
|
1298
|
-
appendTranscript(state, "Error", `Worker Pi catch-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1299
|
-
catchupDone = true;
|
|
1300
|
-
updatePiUi(ctx, state);
|
|
1301
|
-
}
|
|
1302
|
-
await closePromise;
|
|
1303
|
-
}
|
|
1304
|
-
function createRemoteBashOperations(options, state, excludeFromContext) {
|
|
1305
|
-
return {
|
|
1306
|
-
exec(command, _cwd, execOptions) {
|
|
1307
|
-
return new Promise((resolve3, reject) => {
|
|
1308
|
-
const pending = {
|
|
1309
|
-
command,
|
|
1310
|
-
onData: execOptions.onData,
|
|
1311
|
-
resolve: resolve3,
|
|
1312
|
-
reject,
|
|
1313
|
-
sawChunk: false
|
|
1314
|
-
};
|
|
1315
|
-
const cleanup = () => {
|
|
1316
|
-
execOptions.signal?.removeEventListener("abort", onAbort);
|
|
1317
|
-
if (timer)
|
|
1318
|
-
clearTimeout(timer);
|
|
1319
|
-
};
|
|
1320
|
-
const onAbort = () => {
|
|
1321
|
-
cleanup();
|
|
1322
|
-
failPendingShell(state, pending, new Error("Remote worker shell command aborted locally."));
|
|
1323
|
-
};
|
|
1324
|
-
const timeoutMs = typeof execOptions.timeout === "number" && execOptions.timeout > 0 ? execOptions.timeout : 0;
|
|
1325
|
-
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
1326
|
-
cleanup();
|
|
1327
|
-
failPendingShell(state, pending, new Error(`Remote worker shell command timed out after ${timeoutMs}ms.`));
|
|
1328
|
-
}, timeoutMs) : null;
|
|
1329
|
-
const wrappedResolve = pending.resolve;
|
|
1330
|
-
const wrappedReject = pending.reject;
|
|
1331
|
-
pending.resolve = (result) => {
|
|
1332
|
-
cleanup();
|
|
1333
|
-
wrappedResolve(result);
|
|
1334
|
-
};
|
|
1335
|
-
pending.reject = (error) => {
|
|
1336
|
-
cleanup();
|
|
1337
|
-
wrappedReject(error);
|
|
1338
|
-
};
|
|
1339
|
-
execOptions.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1340
|
-
state.pendingShells.push(pending);
|
|
1341
|
-
sendRunPiShellViaServer(options.context, options.runId, `${excludeFromContext ? "!!" : "!"}${command}`).catch((error) => {
|
|
1342
|
-
cleanup();
|
|
1343
|
-
failPendingShell(state, pending, error instanceof Error ? error : new Error(String(error)));
|
|
1344
|
-
});
|
|
1345
|
-
});
|
|
1346
|
-
}
|
|
1347
|
-
};
|
|
1348
|
-
}
|
|
1349
|
-
async function answerPendingUi(options, state, line) {
|
|
1350
|
-
const pending = state.pendingUi;
|
|
1351
|
-
if (!pending)
|
|
1352
|
-
return false;
|
|
1353
|
-
if (line === "/cancel") {
|
|
1354
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { cancelled: true });
|
|
1355
|
-
} else if (pending.method === "confirm") {
|
|
1356
|
-
const confirmed = /^(y|yes|true|1)$/i.test(line);
|
|
1357
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: confirmed, confirmed });
|
|
1358
|
-
} else if (pending.options.length > 0 && /^\d+$/.test(line)) {
|
|
1359
|
-
const selected = pending.options[Math.max(0, Number(line) - 1)] ?? line;
|
|
1360
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: selected });
|
|
1361
|
-
} else {
|
|
1362
|
-
await respondRunPiExtensionUiViaServer(options.context, options.runId, pending.requestId, { value: line });
|
|
1363
|
-
}
|
|
1364
|
-
appendTranscript(state, "System", `Responded to extension UI request ${pending.requestId}.`);
|
|
1365
|
-
state.pendingUi = null;
|
|
1366
|
-
return true;
|
|
1367
|
-
}
|
|
1368
|
-
async function routeInput(options, ctx, state, line) {
|
|
1369
|
-
const text = line.trim();
|
|
1370
|
-
if (!text)
|
|
1371
|
-
return;
|
|
1372
|
-
if (await answerPendingUi(options, state, text)) {
|
|
1373
|
-
updatePiUi(ctx, state);
|
|
1374
|
-
return;
|
|
1375
|
-
}
|
|
1376
|
-
if (text === "/detach" || text === "/quit" || text === "/q") {
|
|
1377
|
-
appendTranscript(state, "System", "Detached locally; worker Pi daemon continues.");
|
|
1378
|
-
updatePiUi(ctx, state);
|
|
1379
|
-
ctx.shutdown();
|
|
1380
|
-
return;
|
|
1381
|
-
}
|
|
1382
|
-
if (text === "/stop") {
|
|
1383
|
-
await abortRunPiViaServer(options.context, options.runId);
|
|
1384
|
-
appendTranscript(state, "System", "Stop requested for worker Pi daemon.");
|
|
1385
|
-
updatePiUi(ctx, state);
|
|
1386
|
-
ctx.shutdown();
|
|
1387
|
-
return;
|
|
1388
|
-
}
|
|
1389
|
-
if (text.startsWith("!")) {
|
|
1390
|
-
appendTranscript(state, "You", text);
|
|
1391
|
-
await sendRunPiShellViaServer(options.context, options.runId, text);
|
|
1392
|
-
} else if (text.startsWith("/")) {
|
|
1393
|
-
appendTranscript(state, "You", text);
|
|
1394
|
-
const result = await runRunPiCommandViaServer(options.context, options.runId, text);
|
|
1395
|
-
const message2 = typeof result.message === "string" ? result.message : "worker command accepted";
|
|
1396
|
-
appendTranscript(state, "System", message2);
|
|
1397
|
-
} else {
|
|
1398
|
-
appendTranscript(state, "You", text);
|
|
1399
|
-
await sendRunPiPromptViaServer(options.context, options.runId, text, state.streaming ? "steer" : undefined);
|
|
1400
|
-
}
|
|
1401
|
-
updatePiUi(ctx, state);
|
|
1402
|
-
}
|
|
1403
|
-
function createRigWorkerPiBridgeExtension(options) {
|
|
1404
|
-
return (pi) => {
|
|
1405
|
-
const state = {
|
|
1406
|
-
transcript: [],
|
|
1407
|
-
status: "starting worker Pi daemon bridge",
|
|
1408
|
-
activity: "",
|
|
1409
|
-
cwd: "",
|
|
1410
|
-
model: "",
|
|
1411
|
-
commands: [],
|
|
1412
|
-
streaming: false,
|
|
1413
|
-
pendingUi: null,
|
|
1414
|
-
pendingShells: [],
|
|
1415
|
-
wsConnected: false,
|
|
1416
|
-
nativeStream: false
|
|
1417
|
-
};
|
|
1418
|
-
if (options.initialMessageSent)
|
|
1419
|
-
appendTranscript(state, "System", "Initial message sent to worker Pi daemon.");
|
|
1420
|
-
let nativePiUiContextAvailable = false;
|
|
1421
|
-
pi.on("user_bash", (event) => {
|
|
1422
|
-
state.nativeStream = Boolean(state.nativeStream || nativePiUiContextAvailable);
|
|
1423
|
-
return { operations: createRemoteBashOperations(options, state, event.excludeFromContext === true) };
|
|
1424
|
-
});
|
|
1425
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
1426
|
-
nativePiUiContextAvailable = Boolean(nativePiUi(ctx));
|
|
1427
|
-
state.nativeStream = nativePiUiContextAvailable;
|
|
1428
|
-
updatePiUi(ctx, state);
|
|
1429
|
-
ctx.ui.notify(nativePiUiContextAvailable ? "Rig worker Pi native stream bridge loaded" : "Rig worker Pi bridge extension loaded (degraded widget fallback)", "info");
|
|
1430
|
-
ctx.ui.onTerminalInput((data) => {
|
|
1431
|
-
if (data.includes("\x04")) {
|
|
1432
|
-
ctx.shutdown();
|
|
1433
|
-
return { consume: true };
|
|
1434
|
-
}
|
|
1435
|
-
if (!data.includes("\r") && !data.includes(`
|
|
1436
|
-
`))
|
|
1437
|
-
return;
|
|
1438
|
-
const inlineText = data.replace(/[\r\n]+/g, "").trim();
|
|
1439
|
-
const editorText = ctx.ui.getEditorText().trim();
|
|
1440
|
-
const text = [editorText, inlineText].filter(Boolean).join(" ").trim();
|
|
1441
|
-
if (!text)
|
|
1442
|
-
return;
|
|
1443
|
-
if (text.startsWith("!"))
|
|
1444
|
-
return;
|
|
1445
|
-
ctx.ui.setEditorText("");
|
|
1446
|
-
routeInput(options, ctx, state, text).catch((error) => {
|
|
1447
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1448
|
-
updatePiUi(ctx, state);
|
|
1449
|
-
});
|
|
1450
|
-
return { consume: true };
|
|
1451
|
-
});
|
|
1452
|
-
connectWorkerStream(options, ctx, state).catch((error) => {
|
|
1453
|
-
appendTranscript(state, "Error", error instanceof Error ? error.message : String(error));
|
|
1454
|
-
updatePiUi(ctx, state);
|
|
1455
|
-
});
|
|
1456
|
-
});
|
|
1457
|
-
pi.on("session_shutdown", () => {});
|
|
1458
|
-
};
|
|
1459
|
-
}
|
|
1460
|
-
|
|
1461
|
-
// packages/cli/src/commands/_pi-frontend.ts
|
|
1462
|
-
function setTemporaryEnv(updates) {
|
|
1463
|
-
const previous = new Map;
|
|
1464
|
-
for (const [key, value] of Object.entries(updates)) {
|
|
1465
|
-
previous.set(key, process.env[key]);
|
|
1466
|
-
process.env[key] = value;
|
|
1467
|
-
}
|
|
1468
|
-
return () => {
|
|
1469
|
-
for (const [key, value] of previous) {
|
|
1470
|
-
if (value === undefined)
|
|
1471
|
-
delete process.env[key];
|
|
1472
|
-
else
|
|
1473
|
-
process.env[key] = value;
|
|
1474
|
-
}
|
|
1475
|
-
};
|
|
1476
|
-
}
|
|
1477
|
-
async function attachRunBundledPiFrontend(context, input) {
|
|
1478
|
-
const tempRoot = mkdtempSync(join(tmpdir(), "rig-pi-frontend-"));
|
|
1479
|
-
const cwd = join(tempRoot, "workspace");
|
|
1480
|
-
const agentDir = join(tempRoot, "agent");
|
|
1481
|
-
const sessionDir = join(tempRoot, "sessions");
|
|
1482
|
-
const previousCwd = process.cwd();
|
|
1483
|
-
const restoreEnv = setTemporaryEnv({
|
|
1484
|
-
PI_CODING_AGENT_DIR: agentDir,
|
|
1485
|
-
PI_CODING_AGENT_SESSION_DIR: sessionDir,
|
|
1486
|
-
PI_OFFLINE: "1",
|
|
1487
|
-
PI_SKIP_VERSION_CHECK: "1"
|
|
1488
|
-
});
|
|
1489
|
-
let detached = false;
|
|
1490
|
-
try {
|
|
1491
|
-
await Bun.$`mkdir -p ${cwd} ${agentDir} ${sessionDir}`.quiet();
|
|
1492
|
-
process.chdir(cwd);
|
|
1493
|
-
await runPiMain([
|
|
1494
|
-
"--offline",
|
|
1495
|
-
"--no-session",
|
|
1496
|
-
"--no-tools",
|
|
1497
|
-
"--no-builtin-tools",
|
|
1498
|
-
"--no-skills",
|
|
1499
|
-
"--no-prompt-templates",
|
|
1500
|
-
"--no-themes",
|
|
1501
|
-
"--no-context-files",
|
|
1502
|
-
"--no-approve"
|
|
1503
|
-
], {
|
|
1504
|
-
extensionFactories: [
|
|
1505
|
-
createRigWorkerPiBridgeExtension({
|
|
1506
|
-
context,
|
|
1507
|
-
runId: input.runId,
|
|
1508
|
-
initialMessageSent: input.steered === true
|
|
1509
|
-
})
|
|
1510
|
-
]
|
|
1511
|
-
});
|
|
1512
|
-
detached = true;
|
|
1513
|
-
} finally {
|
|
1514
|
-
process.chdir(previousCwd);
|
|
1515
|
-
restoreEnv();
|
|
1516
|
-
rmSync(tempRoot, { recursive: true, force: true });
|
|
1517
|
-
}
|
|
1518
|
-
let run = { runId: input.runId, status: "unknown" };
|
|
1519
|
-
try {
|
|
1520
|
-
run = await getRunDetailsViaServer(context, input.runId);
|
|
1521
|
-
} catch {}
|
|
1522
|
-
return {
|
|
1523
|
-
run,
|
|
1524
|
-
logs: [],
|
|
1525
|
-
timeline: [],
|
|
1526
|
-
timelineCursor: null,
|
|
1527
|
-
steered: input.steered === true,
|
|
1528
|
-
detached,
|
|
1529
|
-
rendered: "actual bundled Pi frontend hosted Rig worker Pi bridge extension"
|
|
1530
|
-
};
|
|
1531
|
-
}
|
|
1532
|
-
|
|
1533
|
-
// packages/cli/src/commands/_operator-view.ts
|
|
1534
|
-
var TERMINAL_RUN_STATUSES2 = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
|
|
1535
|
-
function runStatusFromPayload(payload) {
|
|
1536
|
-
const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
|
|
1537
|
-
return String(run.status ?? "unknown").toLowerCase();
|
|
1538
|
-
}
|
|
1539
|
-
async function applyOperatorCommand(context, input, deps = {}) {
|
|
1540
|
-
const line = input.line.trim();
|
|
1541
|
-
if (!line)
|
|
1542
|
-
return { action: "ignored" };
|
|
1543
|
-
if (line === "/detach" || line === "/quit" || line === "/q") {
|
|
1544
|
-
return { action: "detach", message: "Detached from run." };
|
|
1545
|
-
}
|
|
1546
|
-
if (line === "/stop") {
|
|
1547
|
-
await (deps.stop ?? stopRunViaServer)(context, input.runId);
|
|
1548
|
-
return { action: "stopped", message: "Stop requested." };
|
|
1549
|
-
}
|
|
1550
|
-
const userMessage = line.startsWith("/user ") ? line.slice("/user ".length).trim() : line;
|
|
1551
|
-
if (!userMessage)
|
|
1552
|
-
return { action: "ignored" };
|
|
1553
|
-
await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
|
|
1554
|
-
return { action: "continue", message: "Steering message queued." };
|
|
1555
|
-
}
|
|
1556
|
-
async function readOperatorSnapshot(context, runId, options = {}) {
|
|
1557
|
-
const run = await getRunDetailsViaServer(context, runId);
|
|
1558
|
-
const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
|
|
1559
|
-
const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
|
|
1560
|
-
entries: [{
|
|
1561
|
-
id: `timeline-unavailable:${runId}`,
|
|
1562
|
-
type: "timeline_warning",
|
|
1563
|
-
detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
|
|
1564
|
-
createdAt: new Date().toISOString()
|
|
1565
|
-
}],
|
|
1566
|
-
nextCursor: options.timelineCursor ?? null
|
|
1567
|
-
}));
|
|
1568
|
-
const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
|
|
1569
|
-
const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
|
|
1570
|
-
const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
|
|
1571
|
-
return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
|
|
1572
|
-
}
|
|
1573
|
-
async function attachRunOperatorView(context, input) {
|
|
1574
|
-
let steered = false;
|
|
1575
|
-
if (input.message?.trim()) {
|
|
1576
|
-
await sendRunPiPromptViaServer(context, input.runId, input.message.trim(), "steer").catch(() => steerRunViaServer(context, input.runId, input.message.trim()));
|
|
1577
|
-
steered = true;
|
|
1578
|
-
}
|
|
1579
|
-
if (input.follow && !input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
|
|
1580
|
-
return attachRunBundledPiFrontend(context, {
|
|
1581
|
-
runId: input.runId,
|
|
1582
|
-
steered
|
|
1583
|
-
});
|
|
1584
|
-
}
|
|
1585
|
-
const surface = createOperatorSurface({ interactive: input.interactive !== false });
|
|
1586
|
-
let snapshot = await readOperatorSnapshot(context, input.runId);
|
|
1587
|
-
if (context.outputMode === "text") {
|
|
1588
|
-
surface.renderSnapshot(snapshot);
|
|
1589
|
-
surface.renderTimeline(snapshot.timeline);
|
|
1590
|
-
surface.renderLogs(snapshot.logs);
|
|
1591
|
-
if (steered)
|
|
1592
|
-
surface.info("Message submitted to worker Pi.");
|
|
1593
|
-
}
|
|
1594
|
-
let detached = false;
|
|
1595
|
-
let commandInput = null;
|
|
1596
|
-
if (input.follow && !input.once && context.outputMode === "text") {
|
|
1597
|
-
if (input.interactive !== false && process.stdin.isTTY) {
|
|
1598
|
-
surface.info("Controls: /user <message>, /stop, /detach");
|
|
1599
|
-
commandInput = surface.attachCommandInput(async (line) => {
|
|
1600
|
-
const result = await applyOperatorCommand(context, { runId: input.runId, line });
|
|
1601
|
-
if (result.message)
|
|
1602
|
-
surface.info(result.message);
|
|
1603
|
-
if (result.action === "detach" || result.action === "stopped") {
|
|
1604
|
-
detached = true;
|
|
1605
|
-
commandInput?.close();
|
|
1606
|
-
}
|
|
1607
|
-
});
|
|
1608
|
-
}
|
|
1609
|
-
const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
|
|
1610
|
-
let timelineCursor = snapshot.timelineCursor;
|
|
1611
|
-
while (!detached && !TERMINAL_RUN_STATUSES2.has(runStatusFromPayload(snapshot.run))) {
|
|
1612
|
-
await Bun.sleep(pollMs);
|
|
1613
|
-
snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
|
|
1614
|
-
timelineCursor = snapshot.timelineCursor;
|
|
1615
|
-
surface.renderSnapshot(snapshot);
|
|
1616
|
-
surface.renderTimeline(snapshot.timeline);
|
|
1617
|
-
surface.renderLogs(snapshot.logs);
|
|
1618
|
-
}
|
|
1619
|
-
commandInput?.close();
|
|
1620
|
-
}
|
|
1621
|
-
return { ...snapshot, steered, detached };
|
|
1622
|
-
}
|
|
1623
|
-
|
|
1624
|
-
// packages/cli/src/commands/_cli-format.ts
|
|
1625
|
-
import { log, note } from "@clack/prompts";
|
|
1626
|
-
import pc from "picocolors";
|
|
1627
|
-
function stringField(record, key, fallback = "") {
|
|
1628
|
-
const value = record[key];
|
|
1629
|
-
return typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
1630
|
-
}
|
|
1631
|
-
function numberField(record, key) {
|
|
1632
|
-
const value = record[key];
|
|
1633
|
-
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1634
|
-
}
|
|
1635
|
-
function arrayField(record, key) {
|
|
1636
|
-
const value = record[key];
|
|
1637
|
-
return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
|
|
1638
|
-
}
|
|
1639
|
-
function rawObject(record) {
|
|
1640
|
-
const raw = record.raw;
|
|
1641
|
-
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
1642
|
-
}
|
|
1643
|
-
function truncate(value, width) {
|
|
1644
|
-
if (value.length <= width)
|
|
1645
|
-
return value;
|
|
1646
|
-
if (width <= 1)
|
|
1647
|
-
return "\u2026";
|
|
1648
|
-
return `${value.slice(0, width - 1)}\u2026`;
|
|
1649
|
-
}
|
|
1650
|
-
function pad(value, width) {
|
|
1651
|
-
return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
|
|
1652
|
-
}
|
|
1653
|
-
function statusColor(status) {
|
|
1654
|
-
const normalized = status.toLowerCase();
|
|
1655
|
-
if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved"].includes(normalized))
|
|
1656
|
-
return pc.green;
|
|
1657
|
-
if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
|
|
1658
|
-
return pc.red;
|
|
1659
|
-
if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
|
|
1660
|
-
return pc.cyan;
|
|
1661
|
-
if (["ready", "open", "queued", "created", "preparing", "local", "pending"].includes(normalized))
|
|
1662
|
-
return pc.yellow;
|
|
1663
|
-
return pc.dim;
|
|
1664
|
-
}
|
|
1665
|
-
function compactValue(value) {
|
|
1666
|
-
if (value === null || value === undefined)
|
|
1667
|
-
return "";
|
|
1668
|
-
if (typeof value === "string")
|
|
1669
|
-
return value;
|
|
1670
|
-
if (typeof value === "number" || typeof value === "boolean")
|
|
1671
|
-
return String(value);
|
|
1672
|
-
if (Array.isArray(value))
|
|
1673
|
-
return value.map(compactValue).filter(Boolean).join(", ");
|
|
1674
|
-
return JSON.stringify(value);
|
|
1675
|
-
}
|
|
1676
|
-
function shouldUseClackOutput() {
|
|
1677
|
-
return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
|
|
1678
|
-
}
|
|
1679
|
-
function printFormattedOutput(message2, options = {}) {
|
|
1680
|
-
if (!shouldUseClackOutput()) {
|
|
1681
|
-
console.log(message2);
|
|
1682
|
-
return;
|
|
1683
|
-
}
|
|
1684
|
-
if (options.title)
|
|
1685
|
-
note(message2, options.title);
|
|
1686
|
-
else
|
|
1687
|
-
log.message(message2);
|
|
1688
|
-
}
|
|
1689
|
-
function formatStatusPill(status) {
|
|
1690
|
-
const label = status || "unknown";
|
|
1691
|
-
return statusColor(label)(`\u25CF ${label}`);
|
|
1692
|
-
}
|
|
1693
|
-
function formatSection(title, subtitle) {
|
|
1694
|
-
return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
|
|
1695
|
-
}
|
|
1696
|
-
function formatSuccessCard(title, rows = []) {
|
|
1697
|
-
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}`);
|
|
1698
|
-
return [formatSection(title), ...body].join(`
|
|
1699
|
-
`);
|
|
1700
|
-
}
|
|
1701
|
-
function formatNextSteps(steps) {
|
|
1702
|
-
if (steps.length === 0)
|
|
1703
|
-
return [];
|
|
1704
|
-
return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
|
|
1705
|
-
}
|
|
1706
|
-
function formatTaskList(tasks, options = {}) {
|
|
1707
|
-
if (options.raw)
|
|
1708
|
-
return tasks.map((task) => JSON.stringify(task)).join(`
|
|
1709
|
-
`);
|
|
1710
|
-
if (tasks.length === 0)
|
|
1711
|
-
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(`
|
|
1712
|
-
`);
|
|
1713
|
-
const rows = tasks.map((task) => {
|
|
1714
|
-
const raw = rawObject(task);
|
|
1715
|
-
const id = stringField(task, "id", "<unknown>");
|
|
1716
|
-
const status = stringField(task, "status", "unknown");
|
|
1717
|
-
const title = stringField(task, "title", "Untitled task");
|
|
1718
|
-
const source = stringField(task, "source", stringField(raw, "source", ""));
|
|
1719
|
-
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
1720
|
-
return { id, status, title, source, labels };
|
|
1721
|
-
});
|
|
1722
|
-
const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
|
|
1723
|
-
const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
|
|
1724
|
-
const header = `${pc.bold(pad("TASK", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
|
|
1725
|
-
const body = rows.map((row) => {
|
|
1726
|
-
const labels = row.labels.length > 0 ? pc.dim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
|
|
1727
|
-
const source = row.source ? pc.dim(` ${row.source}`) : "";
|
|
1728
|
-
return [
|
|
1729
|
-
pc.bold(pad(truncate(row.id, idWidth), idWidth)),
|
|
1730
|
-
statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
|
|
1731
|
-
`${row.title}${labels}${source}`
|
|
1732
|
-
].join(" ");
|
|
1733
|
-
});
|
|
1734
|
-
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(`
|
|
1735
|
-
`);
|
|
1736
|
-
}
|
|
1737
|
-
function formatTaskCard(task, options = {}) {
|
|
1738
|
-
const raw = rawObject(task);
|
|
1739
|
-
const id = stringField(task, "id", stringField(raw, "id", "<unknown>"));
|
|
1740
|
-
const status = stringField(task, "status", stringField(raw, "status", "unknown"));
|
|
1741
|
-
const title = stringField(task, "title", stringField(raw, "title", "Untitled task"));
|
|
1742
|
-
const source = stringField(task, "source", stringField(raw, "source", ""));
|
|
1743
|
-
const url = stringField(task, "url", stringField(raw, "url", ""));
|
|
1744
|
-
const number = numberField(task, "number") ?? numberField(raw, "number");
|
|
1745
|
-
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
1746
|
-
const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
|
|
1747
|
-
const readiness = compactValue(task.readiness ?? raw.readiness);
|
|
1748
|
-
const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
|
|
1749
|
-
const rows = [
|
|
1750
|
-
["task", pc.bold(id)],
|
|
1751
|
-
["status", formatStatusPill(status)],
|
|
1752
|
-
["title", title],
|
|
1753
|
-
["source", source],
|
|
1754
|
-
["number", number],
|
|
1755
|
-
["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
|
|
1756
|
-
["assignees", assignees.join(", ")],
|
|
1757
|
-
["readiness", readiness],
|
|
1758
|
-
["validators", validators],
|
|
1759
|
-
["url", url]
|
|
1760
|
-
];
|
|
1761
|
-
return [
|
|
1762
|
-
formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
|
|
1763
|
-
"",
|
|
1764
|
-
...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
|
|
1765
|
-
].join(`
|
|
1766
|
-
`);
|
|
1767
|
-
}
|
|
1768
|
-
function formatTaskDetails(task) {
|
|
1769
|
-
return formatTaskCard(task, { title: "Task details" });
|
|
1770
|
-
}
|
|
1771
|
-
function formatSubmittedRun(input) {
|
|
1772
|
-
const rows = [["run", pc.bold(input.runId)]];
|
|
1773
|
-
if (input.task) {
|
|
1774
|
-
const id = stringField(input.task, "id", "<unknown>");
|
|
1775
|
-
const status = stringField(input.task, "status", "unknown");
|
|
1776
|
-
const title = stringField(input.task, "title", "Untitled task");
|
|
1777
|
-
rows.push(["task", `${pc.bold(id)} ${formatStatusPill(status)} ${title}`]);
|
|
1778
|
-
}
|
|
1779
|
-
const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
|
|
1780
|
-
rows.push(["runtime", runtime]);
|
|
1781
|
-
return [
|
|
1782
|
-
formatSuccessCard("Run submitted", rows),
|
|
1783
|
-
"",
|
|
1784
|
-
...formatNextSteps([
|
|
1785
|
-
`Attach: \`rig run attach ${input.runId} --follow\``,
|
|
1786
|
-
`Inspect: \`rig run show ${input.runId}\``,
|
|
1787
|
-
input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the native bundled Pi frontend."
|
|
1788
|
-
])
|
|
1789
|
-
].join(`
|
|
1790
|
-
`);
|
|
1791
|
-
}
|
|
1792
|
-
|
|
1793
|
-
// packages/cli/src/commands/_help-catalog.ts
|
|
1794
|
-
import { intro, log as log2, note as note2, outro } from "@clack/prompts";
|
|
1795
|
-
import pc2 from "picocolors";
|
|
1796
|
-
var TOP_LEVEL_SECTIONS = [
|
|
1797
|
-
{
|
|
1798
|
-
title: "Server",
|
|
1799
|
-
subtitle: "choose the local or remote Rig server that owns this repo",
|
|
1800
|
-
commands: [
|
|
1801
|
-
{ command: "rig server status", description: "Show the selected local/remote server for this repo." },
|
|
1802
|
-
{ command: "rig server use local", description: "Switch this repo back to the local Rig server." },
|
|
1803
|
-
{ command: "rig server add <alias> <url>", description: "Save a remote Rig server alias." },
|
|
1804
|
-
{ command: "rig server use <alias>", description: "Switch this repo to a saved remote server." },
|
|
1805
|
-
{ command: "rig server list", description: "Show saved server aliases, including local." }
|
|
1806
|
-
]
|
|
1807
|
-
},
|
|
1808
|
-
{
|
|
1809
|
-
title: "Tasks",
|
|
1810
|
-
subtitle: "find work, inspect it, and submit Pi-backed workers",
|
|
1811
|
-
commands: [
|
|
1812
|
-
{ command: "rig task list", description: "List tasks from the selected task source/server." },
|
|
1813
|
-
{ command: "rig task next", description: "Show the next matching task as a selected-task card." },
|
|
1814
|
-
{ command: "rig task show <id>", description: "Show a human task summary; add --raw or --json for the full payload." },
|
|
1815
|
-
{ command: "rig task run <id|--next> [--detach]", description: "Submit a task run; interactive mode follows with bundled Pi." }
|
|
1816
|
-
]
|
|
1817
|
-
},
|
|
1818
|
-
{
|
|
1819
|
-
title: "Runs",
|
|
1820
|
-
subtitle: "observe, attach to, and stop live or recent runs",
|
|
1821
|
-
commands: [
|
|
1822
|
-
{ command: "rig run list", description: "List recent runs from the selected server or local state." },
|
|
1823
|
-
{ command: "rig run show <id>", description: "Show a human run summary; add --raw or --json for the full payload." },
|
|
1824
|
-
{ command: "rig run attach <id> --follow", description: "Open the native bundled Pi live view for a worker run." },
|
|
1825
|
-
{ command: "rig run stop <id>", description: "Request cancellation for a running worker." }
|
|
1826
|
-
]
|
|
1827
|
-
},
|
|
1828
|
-
{
|
|
1829
|
-
title: "Review / inbox",
|
|
1830
|
-
subtitle: "clear blocked runs and configure completion review",
|
|
1831
|
-
commands: [
|
|
1832
|
-
{ command: "rig inbox approvals", description: "List pending approval requests from local/server run state." },
|
|
1833
|
-
{ command: "rig inbox inputs", description: "List pending user-input requests from local/server run state." },
|
|
1834
|
-
{ command: "rig review show|set", description: "Inspect or change the review gate policy." }
|
|
1835
|
-
]
|
|
1836
|
-
},
|
|
1837
|
-
{
|
|
1838
|
-
title: "Health / setup",
|
|
1839
|
-
subtitle: "bootstrap and diagnose the repo/server/GitHub/Pi path",
|
|
1840
|
-
commands: [
|
|
1841
|
-
{ command: "rig init", description: "Interactive setup: config, GitHub auth, task source, server, checkout, Pi." },
|
|
1842
|
-
{ command: "rig doctor", description: "Diagnose project/server/GitHub/task/Pi wiring." },
|
|
1843
|
-
{ command: "rig github auth status", description: "Show GitHub auth state on the selected Rig server." }
|
|
1844
|
-
]
|
|
1845
|
-
}
|
|
1846
|
-
];
|
|
1847
|
-
var PRIMARY_GROUPS = [
|
|
1848
|
-
{
|
|
1849
|
-
name: "server",
|
|
1850
|
-
summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
|
|
1851
|
-
usage: ["rig server <status|list|add|use|start> [options]"],
|
|
1852
|
-
commands: [
|
|
1853
|
-
{ command: "status", description: "Show the selected server for this repo.", primary: true },
|
|
1854
|
-
{ command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
|
|
1855
|
-
{ command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
|
|
1856
|
-
{ command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
|
|
1857
|
-
{ command: "list", description: "List saved local/remote server aliases.", primary: true },
|
|
1858
|
-
{ command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
|
|
1859
|
-
],
|
|
1860
|
-
examples: [
|
|
1861
|
-
"rig server status",
|
|
1862
|
-
"rig server add prod https://where.rig-does.work",
|
|
1863
|
-
"rig server use prod",
|
|
1864
|
-
"rig server use local",
|
|
1865
|
-
"rig server start --port 3773"
|
|
1866
|
-
],
|
|
1867
|
-
next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."],
|
|
1868
|
-
advanced: ["Compatibility alias: `rig connect ...` remains callable."]
|
|
1869
|
-
},
|
|
1870
|
-
{
|
|
1871
|
-
name: "task",
|
|
1872
|
-
summary: "Find work, start Pi-backed runs, and validate task results.",
|
|
1873
|
-
usage: ["rig task <list|next|show|run> [options]"],
|
|
1874
|
-
commands: [
|
|
1875
|
-
{ command: "list [--assignee <login|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
|
|
1876
|
-
{ command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
|
|
1877
|
-
{ command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
|
|
1878
|
-
{ command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
|
|
1879
|
-
{ command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
|
|
1880
|
-
{ command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
|
|
1881
|
-
{ command: "report-bug", description: "Create a structured bug report/task." }
|
|
1882
|
-
],
|
|
1883
|
-
examples: [
|
|
1884
|
-
"rig task list --assignee @me --limit 20",
|
|
1885
|
-
"rig task next",
|
|
1886
|
-
"rig task show 123 --raw",
|
|
1887
|
-
"rig task run --next",
|
|
1888
|
-
"rig task run #123 --runtime-adapter pi",
|
|
1889
|
-
"rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
|
|
1890
|
-
],
|
|
1891
|
-
next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
|
|
1892
|
-
},
|
|
1893
|
-
{
|
|
1894
|
-
name: "run",
|
|
1895
|
-
summary: "Observe, attach to, and control Rig runs.",
|
|
1896
|
-
usage: ["rig run <list|status|show|attach|stop> [options]"],
|
|
1897
|
-
commands: [
|
|
1898
|
-
{ command: "list", description: "List recent runs from the selected server or local state.", primary: true },
|
|
1899
|
-
{ command: "status", description: "Render active and recent run groups.", primary: true },
|
|
1900
|
-
{ command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
|
|
1901
|
-
{ command: "attach <run-id>|--run <id> [--follow]", description: "Attach to the run; --follow launches native bundled Pi for live Pi runs.", primary: true },
|
|
1902
|
-
{ command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
|
|
1903
|
-
{ command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events." },
|
|
1904
|
-
{ command: "delete|cleanup", description: "Remove completed run records/artifacts." }
|
|
1905
|
-
],
|
|
1906
|
-
examples: [
|
|
1907
|
-
"rig run list",
|
|
1908
|
-
"rig run status",
|
|
1909
|
-
"rig run show <run-id>",
|
|
1910
|
-
"rig run attach <run-id> --follow",
|
|
1911
|
-
"rig run stop <run-id>"
|
|
1912
|
-
],
|
|
1913
|
-
next: ["Use `rig task run --next` to create a new run.", "Use `--json` when scripts need the full structured record."]
|
|
1914
|
-
},
|
|
1915
|
-
{
|
|
1916
|
-
name: "inbox",
|
|
1917
|
-
summary: "Review approval and user-input requests that block worker runs.",
|
|
1918
|
-
usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
|
|
1919
|
-
commands: [
|
|
1920
|
-
{ command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
|
|
1921
|
-
{ command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
|
|
1922
|
-
{ command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
|
|
1923
|
-
{ command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
|
|
1924
|
-
],
|
|
1925
|
-
examples: [
|
|
1926
|
-
"rig inbox approvals",
|
|
1927
|
-
"rig inbox inputs --run <run-id>",
|
|
1928
|
-
"rig inbox approve --run <run-id> --request <request-id> --decision approve"
|
|
1929
|
-
],
|
|
1930
|
-
next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
|
|
1931
|
-
},
|
|
1932
|
-
{
|
|
1933
|
-
name: "review",
|
|
1934
|
-
summary: "Inspect or change completion review gate policy.",
|
|
1935
|
-
usage: ["rig review <show|set>"],
|
|
1936
|
-
commands: [
|
|
1937
|
-
{ command: "show", description: "Show current review gate settings.", primary: true },
|
|
1938
|
-
{ command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider.", primary: true }
|
|
1939
|
-
],
|
|
1940
|
-
examples: ["rig review show", "rig review set required --provider greptile"],
|
|
1941
|
-
next: ["Use `rig inbox approvals` for blocked run handoffs."]
|
|
1942
|
-
},
|
|
1943
|
-
{
|
|
1944
|
-
name: "init",
|
|
1945
|
-
summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
|
|
1946
|
-
usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
|
|
1947
|
-
commands: [
|
|
1948
|
-
{ command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
|
|
1949
|
-
{ command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
|
|
1950
|
-
{ command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
|
|
1951
|
-
{ command: "init --repair", description: "Repair missing private state without replacing project config." }
|
|
1952
|
-
],
|
|
1953
|
-
examples: [
|
|
1954
|
-
"rig init",
|
|
1955
|
-
"rig init --yes --repo humanity-org/humanwork",
|
|
1956
|
-
"rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
|
|
1957
|
-
],
|
|
1958
|
-
next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
|
|
1959
|
-
},
|
|
1960
|
-
{
|
|
1961
|
-
name: "doctor",
|
|
1962
|
-
summary: "Diagnostics for project/server/GitHub/Pi state.",
|
|
1963
|
-
usage: ["rig doctor"],
|
|
1964
|
-
commands: [
|
|
1965
|
-
{ command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
|
|
1966
|
-
{ command: "check", description: "Compatibility spelling for diagnostics." }
|
|
1967
|
-
],
|
|
1968
|
-
examples: ["rig doctor", "rig doctor --json"],
|
|
1969
|
-
next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
|
|
1970
|
-
},
|
|
1971
|
-
{
|
|
1972
|
-
name: "github",
|
|
1973
|
-
summary: "GitHub auth helpers for the selected Rig server.",
|
|
1974
|
-
usage: ["rig github auth <status|import-gh|token>"],
|
|
1975
|
-
commands: [
|
|
1976
|
-
{ command: "auth status", description: "Show GitHub auth state.", primary: true },
|
|
1977
|
-
{ command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
|
|
1978
|
-
{ command: "auth token --token <token>", description: "Store a token on the selected server." }
|
|
1979
|
-
],
|
|
1980
|
-
examples: ["rig github auth status", "rig github auth import-gh"],
|
|
1981
|
-
next: ["After auth is valid, use `rig task run --next`."]
|
|
1982
|
-
}
|
|
1983
|
-
];
|
|
1984
|
-
var ADVANCED_GROUPS = [
|
|
1985
|
-
{ 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." }] },
|
|
1986
|
-
{ name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
|
|
1987
|
-
{ name: "inspect", summary: "Inspect logs, artifacts, graphs, failures.", usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff>"], commands: [{ command: "logs --task <id>", description: "Inspect task logs." }] },
|
|
1988
|
-
{ name: "repo", summary: "Repository sync/baseline helpers.", usage: ["rig repo <sync|reset-baseline>"], commands: [{ command: "sync", description: "Sync project repository state." }] },
|
|
1989
|
-
{ name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
|
|
1990
|
-
{ name: "browser", summary: "Browser/app diagnostics.", usage: ["rig browser <help|explain|demo|app>"], commands: [{ command: "help", description: "Browser command help." }] },
|
|
1991
|
-
{ name: "plugin", summary: "Plugin validation/listing.", usage: ["rig plugin <list|validate>"], commands: [{ command: "list", description: "List plugins." }] },
|
|
1992
|
-
{ name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
|
|
1993
|
-
{ name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
|
|
1994
|
-
{ name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
|
|
1995
|
-
{ name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
|
|
1996
|
-
{ name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
|
|
1997
|
-
{ name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
|
|
1998
|
-
{ name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
|
|
1999
|
-
{ name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
|
|
2000
|
-
{ name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
|
|
2001
|
-
];
|
|
2002
|
-
var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
|
|
2003
|
-
function heading(title) {
|
|
2004
|
-
return pc2.bold(pc2.cyan(title));
|
|
2005
|
-
}
|
|
2006
|
-
function commandLine(command, description) {
|
|
2007
|
-
const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
|
|
2008
|
-
return `${pc2.dim("\u2502")} ${pc2.bold(commandColumn)} ${description}`;
|
|
2009
|
-
}
|
|
2010
|
-
function renderCommandBlock(commands) {
|
|
2011
|
-
return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
|
|
2012
|
-
`);
|
|
2013
|
-
}
|
|
2014
|
-
function renderGroup(group) {
|
|
2015
|
-
const lines = [
|
|
2016
|
-
`${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
|
|
2017
|
-
"",
|
|
2018
|
-
pc2.bold("Usage"),
|
|
2019
|
-
...group.usage.map((line) => ` ${line}`),
|
|
2020
|
-
"",
|
|
2021
|
-
pc2.bold("Commands"),
|
|
2022
|
-
...group.commands.map((entry) => commandLine(entry.command, entry.description))
|
|
2023
|
-
];
|
|
2024
|
-
if (group.examples?.length) {
|
|
2025
|
-
lines.push("", pc2.bold("Examples"), ...group.examples.map((line) => ` ${pc2.dim("$")} ${line}`));
|
|
2026
|
-
}
|
|
2027
|
-
if (group.next?.length) {
|
|
2028
|
-
lines.push("", pc2.bold("Next steps"), ...group.next.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
|
|
2029
|
-
}
|
|
2030
|
-
if (group.advanced?.length) {
|
|
2031
|
-
lines.push("", pc2.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc2.dim("\u203A")} ${line}`));
|
|
2032
|
-
}
|
|
2033
|
-
return lines.join(`
|
|
2034
|
-
`);
|
|
2035
|
-
}
|
|
2036
|
-
function renderTopLevelHelp() {
|
|
2037
|
-
return [
|
|
2038
|
-
`${heading("rig")} ${pc2.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
|
|
2039
|
-
pc2.dim("Current path: select a server, choose a task, submit a run, attach with native Pi, clear inbox/review gates."),
|
|
2040
|
-
"",
|
|
2041
|
-
...TOP_LEVEL_SECTIONS.flatMap((section) => [
|
|
2042
|
-
`${pc2.bold(pc2.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc2.dim(section.subtitle)}`,
|
|
2043
|
-
renderCommandBlock(section.commands),
|
|
2044
|
-
""
|
|
2045
|
-
]),
|
|
2046
|
-
pc2.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
|
|
2047
|
-
"",
|
|
2048
|
-
pc2.bold("Global options"),
|
|
2049
|
-
commandLine("--project <path>", "Use a project root instead of auto-discovery."),
|
|
2050
|
-
commandLine("--json", "Emit structured output for scripts/agents."),
|
|
2051
|
-
commandLine("--dry-run", "Print the command plan without mutating state.")
|
|
2052
|
-
].join(`
|
|
2053
|
-
`).trimEnd();
|
|
2054
|
-
}
|
|
2055
|
-
function renderGroupHelp(groupName) {
|
|
2056
|
-
const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
|
|
2057
|
-
return group ? renderGroup(group) : null;
|
|
2058
|
-
}
|
|
2059
|
-
function shouldUseClackOutput2() {
|
|
2060
|
-
return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
|
|
2061
|
-
}
|
|
2062
|
-
function printTopLevelHelp() {
|
|
2063
|
-
if (!shouldUseClackOutput2()) {
|
|
2064
|
-
console.log(renderTopLevelHelp());
|
|
2065
|
-
return;
|
|
2066
|
-
}
|
|
2067
|
-
intro("rig");
|
|
2068
|
-
for (const section of TOP_LEVEL_SECTIONS) {
|
|
2069
|
-
note2(renderCommandBlock(section.commands), `${section.title} \u2014 ${section.subtitle}`);
|
|
2070
|
-
}
|
|
2071
|
-
log2.info("More: rig help --advanced \xB7 rig <group> --help \xB7 rig --version");
|
|
2072
|
-
note2([
|
|
2073
|
-
commandLine("--project <path>", "Use a project root instead of auto-discovery."),
|
|
2074
|
-
commandLine("--json", "Emit structured output for scripts/agents."),
|
|
2075
|
-
commandLine("--dry-run", "Print the command plan without mutating state.")
|
|
2076
|
-
].join(`
|
|
2077
|
-
`), "Global options");
|
|
2078
|
-
outro("Server \u2192 task \u2192 run \u2192 inbox/review.");
|
|
2079
|
-
}
|
|
2080
|
-
function printGroupHelpDocument(groupName) {
|
|
2081
|
-
const rendered = renderGroupHelp(groupName) ?? renderTopLevelHelp();
|
|
2082
|
-
if (!shouldUseClackOutput2()) {
|
|
2083
|
-
console.log(rendered);
|
|
2084
|
-
return;
|
|
2085
|
-
}
|
|
2086
|
-
const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
|
|
2087
|
-
if (!group) {
|
|
2088
|
-
printTopLevelHelp();
|
|
2089
|
-
return;
|
|
2090
|
-
}
|
|
2091
|
-
intro(`rig ${group.name}`);
|
|
2092
|
-
note2(group.summary, "Purpose");
|
|
2093
|
-
note2(group.usage.join(`
|
|
2094
|
-
`), "Usage");
|
|
2095
|
-
note2(group.commands.map((entry) => commandLine(entry.command, entry.description)).join(`
|
|
2096
|
-
`), "Commands");
|
|
2097
|
-
if (group.examples?.length)
|
|
2098
|
-
note2(group.examples.map((line) => `$ ${line}`).join(`
|
|
2099
|
-
`), "Examples");
|
|
2100
|
-
if (group.next?.length)
|
|
2101
|
-
note2(group.next.map((line) => `\u203A ${line}`).join(`
|
|
2102
|
-
`), "Next steps");
|
|
2103
|
-
if (group.advanced?.length)
|
|
2104
|
-
log2.info(group.advanced.join(`
|
|
2105
|
-
`));
|
|
2106
|
-
outro("Run with --json when scripts need structured output.");
|
|
2107
|
-
}
|
|
2108
|
-
|
|
2109
|
-
// packages/cli/src/commands/task.ts
|
|
2110
|
-
import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
|
|
2111
|
-
import { loadConfig } from "@rig/core/load-config";
|
|
2112
|
-
async function readStdin() {
|
|
2113
|
-
const chunks = [];
|
|
2114
|
-
for await (const chunk of process.stdin) {
|
|
2115
|
-
chunks.push(Buffer.from(chunk));
|
|
2116
|
-
}
|
|
2117
|
-
return Buffer.concat(chunks).toString("utf-8");
|
|
2118
|
-
}
|
|
2119
|
-
function normalizeAssignedToAlias(value) {
|
|
2120
|
-
if (!value)
|
|
2121
|
-
return;
|
|
2122
|
-
return value.trim().toLowerCase() === "me" ? "@me" : value;
|
|
2123
|
-
}
|
|
2124
|
-
function parseTaskFilters(args) {
|
|
2125
|
-
let pending = args;
|
|
2126
|
-
const assigneeResult = takeOption(pending, "--assignee");
|
|
2127
|
-
pending = assigneeResult.rest;
|
|
2128
|
-
const assignedToResult = takeOption(pending, "--assigned-to");
|
|
2129
|
-
pending = assignedToResult.rest;
|
|
2130
|
-
const stateResult = takeOption(pending, "--state");
|
|
2131
|
-
pending = stateResult.rest;
|
|
2132
|
-
const statusResult = takeOption(pending, "--status");
|
|
2133
|
-
pending = statusResult.rest;
|
|
2134
|
-
const limitResult = takeOption(pending, "--limit");
|
|
2135
|
-
pending = limitResult.rest;
|
|
2136
|
-
const normalizedAssignedTo = normalizeAssignedToAlias(assignedToResult.value);
|
|
2137
|
-
if (assigneeResult.value && normalizedAssignedTo && assigneeResult.value !== normalizedAssignedTo) {
|
|
2138
|
-
throw new CliError2("--assignee and --assigned-to cannot specify different assignees.", 2);
|
|
2139
|
-
}
|
|
2140
|
-
const assignee = normalizedAssignedTo ?? assigneeResult.value;
|
|
2141
|
-
const limit = (() => {
|
|
2142
|
-
if (!limitResult.value)
|
|
2143
|
-
return;
|
|
2144
|
-
const parsed = Number.parseInt(limitResult.value, 10);
|
|
2145
|
-
if (!Number.isFinite(parsed) || parsed < 1) {
|
|
2146
|
-
throw new CliError2("--limit must be a positive integer.", 2);
|
|
2147
|
-
}
|
|
2148
|
-
return parsed;
|
|
2149
|
-
})();
|
|
2150
|
-
const filters = {
|
|
2151
|
-
...assignee ? { assignee } : {},
|
|
2152
|
-
...stateResult.value ? { state: stateResult.value } : {},
|
|
2153
|
-
...statusResult.value ? { status: statusResult.value } : {},
|
|
2154
|
-
...limit !== undefined ? { limit } : {}
|
|
2155
|
-
};
|
|
2156
|
-
return { filters, rest: pending };
|
|
2157
|
-
}
|
|
2158
|
-
function mapConfiguredRuntimeMode(mode) {
|
|
2159
|
-
if (!mode)
|
|
2160
|
-
return;
|
|
2161
|
-
return mode === "yolo" ? "full-access" : mode;
|
|
2162
|
-
}
|
|
2163
|
-
async function loadTaskRunProjectDefaults(projectRoot) {
|
|
2164
|
-
try {
|
|
2165
|
-
const config = await loadConfig(projectRoot);
|
|
2166
|
-
return {
|
|
2167
|
-
runtimeAdapter: config.runtime?.harness,
|
|
2168
|
-
model: config.runtime?.model,
|
|
2169
|
-
runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
|
|
2170
|
-
prMode: config.pr?.mode
|
|
2171
|
-
};
|
|
2172
|
-
} catch {
|
|
2173
|
-
return {};
|
|
2174
|
-
}
|
|
2175
|
-
}
|
|
2176
|
-
function normalizePrMode(value) {
|
|
2177
|
-
if (!value)
|
|
2178
|
-
return;
|
|
2179
|
-
if (value === "auto" || value === "ask" || value === "off")
|
|
2180
|
-
return value;
|
|
2181
|
-
throw new CliError2("--pr must be auto, ask, or off.", 2);
|
|
2182
|
-
}
|
|
2183
|
-
function detectLocalDirtyState(projectRoot) {
|
|
2184
|
-
const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
|
|
2185
|
-
if (result.status !== 0)
|
|
2186
|
-
return { dirty: false, modified: 0, untracked: 0, lines: [] };
|
|
2187
|
-
const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
|
|
2188
|
-
return {
|
|
2189
|
-
dirty: lines.length > 0,
|
|
2190
|
-
modified: lines.filter((line) => !line.startsWith("?? ")).length,
|
|
2191
|
-
untracked: lines.filter((line) => line.startsWith("?? ")).length,
|
|
2192
|
-
lines
|
|
2193
|
-
};
|
|
2194
|
-
}
|
|
2195
|
-
function selectedServerKind(projectRoot) {
|
|
2196
|
-
try {
|
|
2197
|
-
return resolveSelectedConnection(projectRoot)?.connection.kind === "remote" ? "remote" : "local";
|
|
2198
|
-
} catch {
|
|
2199
|
-
return "local";
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
2202
|
-
async function resolveDirtyBaselineForTaskRun(context, explicit) {
|
|
2203
|
-
if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
|
|
2204
|
-
throw new CliError2("--dirty-baseline must be head or dirty-snapshot.", 2);
|
|
2205
|
-
}
|
|
2206
|
-
if (selectedServerKind(context.projectRoot) !== "local") {
|
|
2207
|
-
return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
|
|
2208
|
-
}
|
|
2209
|
-
const state = detectLocalDirtyState(context.projectRoot);
|
|
2210
|
-
if (!state.dirty)
|
|
2211
|
-
return { mode: "head", state };
|
|
2212
|
-
if (context.outputMode === "text") {
|
|
2213
|
-
console.log(`Repo state: dirty (${state.modified} modified, ${state.untracked} untracked).`);
|
|
2214
|
-
}
|
|
2215
|
-
if (explicit)
|
|
2216
|
-
return { mode: explicit, state };
|
|
2217
|
-
if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
|
|
2218
|
-
const answer = await confirm({
|
|
2219
|
-
message: "Include current uncommitted changes in run baseline?",
|
|
2220
|
-
initialValue: false
|
|
2221
|
-
});
|
|
2222
|
-
if (isCancel2(answer)) {
|
|
2223
|
-
cancel2("Run cancelled.");
|
|
2224
|
-
throw new CliError2("Run cancelled by user.", 1);
|
|
2225
|
-
}
|
|
2226
|
-
return { mode: answer ? "dirty-snapshot" : "head", state };
|
|
2227
|
-
}
|
|
2228
|
-
return { mode: "head", state };
|
|
2229
|
-
}
|
|
2230
|
-
function normalizeTaskRunTaskId(value) {
|
|
2231
|
-
const trimmed = value?.trim() ?? "";
|
|
2232
|
-
if (!trimmed)
|
|
2233
|
-
return null;
|
|
2234
|
-
const issueNumber = trimmed.match(/^#(\d+)$/)?.[1];
|
|
2235
|
-
return issueNumber ?? trimmed;
|
|
2236
|
-
}
|
|
2237
|
-
function readTaskId(task) {
|
|
2238
|
-
return typeof task.id === "string" && task.id.trim().length > 0 ? task.id : null;
|
|
2239
|
-
}
|
|
2240
|
-
function readTaskString(task, key) {
|
|
2241
|
-
const value = task[key];
|
|
2242
|
-
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
2243
|
-
}
|
|
2244
|
-
function summarizeTask(task, options = {}) {
|
|
2245
|
-
const raw = task.raw && typeof task.raw === "object" && !Array.isArray(task.raw) ? task.raw : null;
|
|
2246
|
-
return {
|
|
2247
|
-
id: readTaskId(task),
|
|
2248
|
-
title: readTaskString(task, "title"),
|
|
2249
|
-
status: readTaskString(task, "status"),
|
|
2250
|
-
source: typeof task.source === "string" ? task.source : undefined,
|
|
2251
|
-
url: typeof raw?.url === "string" ? raw.url : undefined,
|
|
2252
|
-
number: typeof raw?.number === "number" ? raw.number : undefined,
|
|
2253
|
-
labels: Array.isArray(task.labels) ? task.labels : Array.isArray(raw?.labels) ? raw.labels : undefined,
|
|
2254
|
-
assignees: Array.isArray(raw?.assignees) ? raw.assignees : undefined,
|
|
2255
|
-
readiness: typeof task.readiness === "string" || typeof task.readiness === "boolean" ? task.readiness : undefined,
|
|
2256
|
-
validators: Array.isArray(task.validators) ? task.validators : Array.isArray(task.validation) ? task.validation : undefined,
|
|
2257
|
-
...options.raw ? { raw: raw ?? task } : {}
|
|
2258
|
-
};
|
|
2259
|
-
}
|
|
2260
|
-
async function validatorRegistryForTaskCommands(projectRoot) {
|
|
2261
|
-
return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
|
|
2262
|
-
return;
|
|
2263
|
-
});
|
|
2264
|
-
}
|
|
2265
|
-
async function executeTask(context, args, options) {
|
|
2266
|
-
if (args.length === 0) {
|
|
2267
|
-
if (context.outputMode === "text") {
|
|
2268
|
-
printGroupHelpDocument("task");
|
|
2269
|
-
}
|
|
2270
|
-
return { ok: true, group: "task", command: "help" };
|
|
2271
|
-
}
|
|
2272
|
-
const [command = "help", ...rest] = args;
|
|
2273
|
-
switch (command) {
|
|
2274
|
-
case "list": {
|
|
2275
|
-
let pending = rest;
|
|
2276
|
-
const rawResult = takeFlag(pending, "--raw");
|
|
2277
|
-
pending = rawResult.rest;
|
|
2278
|
-
const { filters, rest: remaining } = parseTaskFilters(pending);
|
|
2279
|
-
requireNoExtraArgs(remaining, "rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
2280
|
-
const tasks = await listWorkspaceTasksViaServer(context, filters);
|
|
2281
|
-
if (context.outputMode === "text") {
|
|
2282
|
-
const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
|
|
2283
|
-
printFormattedOutput(formatTaskList(renderedTasks, { raw: rawResult.value }));
|
|
2284
|
-
}
|
|
2285
|
-
return {
|
|
2286
|
-
ok: true,
|
|
2287
|
-
group: "task",
|
|
2288
|
-
command,
|
|
2289
|
-
details: { count: tasks.length, filters, raw: rawResult.value, tasks: tasks.map((task) => summarizeTask(task, { raw: rawResult.value })) }
|
|
2290
|
-
};
|
|
2291
|
-
}
|
|
2292
|
-
case "show": {
|
|
2293
|
-
let pending = rest;
|
|
2294
|
-
const rawResult = takeFlag(pending, "--raw");
|
|
2295
|
-
pending = rawResult.rest;
|
|
2296
|
-
const taskOption = takeOption(pending, "--task");
|
|
2297
|
-
const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
|
|
2298
|
-
const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
|
|
2299
|
-
requireNoExtraArgs(remaining, "rig task show <id>|--task <id> [--raw]");
|
|
2300
|
-
const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
|
|
2301
|
-
if (!taskId3)
|
|
2302
|
-
throw new CliError2("task show requires a task id.", 2);
|
|
2303
|
-
const task = await getWorkspaceTaskViaServer(context, taskId3);
|
|
2304
|
-
if (!task)
|
|
2305
|
-
throw new CliError2(`Task not found: ${taskId3}`, 3);
|
|
2306
|
-
const summary = summarizeTask(task, { raw: true });
|
|
2307
|
-
if (context.outputMode === "text") {
|
|
2308
|
-
printFormattedOutput(rawResult.value ? JSON.stringify(summary, null, 2) : formatTaskDetails(summary));
|
|
2309
|
-
}
|
|
2310
|
-
return { ok: true, group: "task", command, details: { task: summary, raw: rawResult.value } };
|
|
2311
|
-
}
|
|
2312
|
-
case "next": {
|
|
2313
|
-
const { filters, rest: remaining } = parseTaskFilters(rest);
|
|
2314
|
-
requireNoExtraArgs(remaining, "rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
2315
|
-
const selected = await selectNextWorkspaceTaskViaServer(context, filters);
|
|
2316
|
-
if (context.outputMode === "text") {
|
|
2317
|
-
if (selected.task) {
|
|
2318
|
-
printFormattedOutput(formatTaskCard(summarizeTask(selected.task, { raw: true }), { title: "Selected task", selected: true }));
|
|
2319
|
-
} else {
|
|
2320
|
-
printFormattedOutput("No matching tasks.\n\nNext\n\u203A Try `rig task list` to inspect available work.\n\u203A Check server: `rig server status`");
|
|
2321
|
-
}
|
|
2322
|
-
}
|
|
2323
|
-
return {
|
|
2324
|
-
ok: true,
|
|
2325
|
-
group: "task",
|
|
2326
|
-
command,
|
|
2327
|
-
details: {
|
|
2328
|
-
count: selected.count,
|
|
2329
|
-
filters,
|
|
2330
|
-
task: selected.task ? summarizeTask(selected.task) : null
|
|
2331
|
-
}
|
|
2332
|
-
};
|
|
2333
|
-
}
|
|
2334
|
-
case "info": {
|
|
2335
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2336
|
-
requireNoExtraArgs(remaining, "rig task info [--task <task-id>]");
|
|
2337
|
-
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
|
|
2338
|
-
return { ok: true, group: "task", command, details: { task: task || null } };
|
|
2339
|
-
}
|
|
2340
|
-
case "scope": {
|
|
2341
|
-
const filesFlag = takeFlag(rest, "--files");
|
|
2342
|
-
const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
|
|
2343
|
-
requireNoExtraArgs(remaining, "rig task scope [--task <id>] [--files]");
|
|
2344
|
-
await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
|
|
2345
|
-
return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
|
|
2346
|
-
}
|
|
2347
|
-
case "deps":
|
|
2348
|
-
requireNoExtraArgs(rest, "rig task deps");
|
|
2349
|
-
await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
|
|
2350
|
-
return { ok: true, group: "task", command };
|
|
2351
|
-
case "status":
|
|
2352
|
-
requireNoExtraArgs(rest, "rig task status");
|
|
2353
|
-
withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
|
|
2354
|
-
return { ok: true, group: "task", command };
|
|
2355
|
-
case "artifacts":
|
|
2356
|
-
requireNoExtraArgs(rest, "rig task artifacts");
|
|
2357
|
-
withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
|
|
2358
|
-
return { ok: true, group: "task", command };
|
|
2359
|
-
case "artifact-dir": {
|
|
2360
|
-
requireNoExtraArgs(rest, "rig task artifact-dir");
|
|
2361
|
-
const path = taskArtifactDir(context.projectRoot);
|
|
2362
|
-
if (context.outputMode === "text") {
|
|
2363
|
-
console.log(path);
|
|
2364
|
-
}
|
|
2365
|
-
return { ok: true, group: "task", command, details: { path } };
|
|
2366
|
-
}
|
|
2367
|
-
case "artifact-write": {
|
|
2368
|
-
if (rest.length < 1) {
|
|
2369
|
-
throw new CliError2(`Usage: rig task artifact-write <filename> [--file <path>]
|
|
2370
|
-
` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
|
|
2371
|
-
` + " Example: echo '...' | rig task artifact-write collection-audit.md");
|
|
2372
|
-
}
|
|
2373
|
-
const artifactFilename = rest[0];
|
|
2374
|
-
const fileFlag = takeOption(rest.slice(1), "--file");
|
|
2375
|
-
let content;
|
|
2376
|
-
if (fileFlag.value) {
|
|
2377
|
-
content = readFileSync3(resolve3(context.projectRoot, fileFlag.value), "utf-8");
|
|
2378
|
-
} else {
|
|
2379
|
-
content = await readStdin();
|
|
2380
|
-
}
|
|
2381
|
-
if (!artifactFilename) {
|
|
2382
|
-
throw new CliError2("Usage: rig task artifact-write <filename> [--file path]");
|
|
2383
|
-
}
|
|
2384
|
-
withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
|
|
2385
|
-
return { ok: true, group: "task", command, details: { filename: artifactFilename } };
|
|
2386
|
-
}
|
|
2387
|
-
case "report-bug":
|
|
2388
|
-
return options.executeTaskReportBug(context, rest);
|
|
2389
|
-
case "lookup": {
|
|
2390
|
-
if (rest.length !== 1) {
|
|
2391
|
-
throw new CliError2("Usage: rig task lookup <task-id>");
|
|
2392
|
-
}
|
|
2393
|
-
const lookupId = rest[0];
|
|
2394
|
-
if (!lookupId) {
|
|
2395
|
-
throw new CliError2("Usage: rig task lookup <task-id>");
|
|
2396
|
-
}
|
|
2397
|
-
const result = taskLookup(context.projectRoot, lookupId);
|
|
2398
|
-
if (context.outputMode === "text") {
|
|
2399
|
-
console.log(result);
|
|
2400
|
-
}
|
|
2401
|
-
return { ok: true, group: "task", command, details: { id: lookupId, result } };
|
|
2402
|
-
}
|
|
2403
|
-
case "record": {
|
|
2404
|
-
if (rest.length < 2) {
|
|
2405
|
-
throw new CliError2("Usage: rig task record <decision|failure> <text>");
|
|
2406
|
-
}
|
|
2407
|
-
const type = rest[0];
|
|
2408
|
-
if (type !== "decision" && type !== "failure") {
|
|
2409
|
-
throw new CliError2("Usage: rig task record <decision|failure> <text>");
|
|
2410
|
-
}
|
|
2411
|
-
withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
|
|
2412
|
-
return { ok: true, group: "task", command, details: { type: rest[0] } };
|
|
2413
|
-
}
|
|
2414
|
-
case "ready":
|
|
2415
|
-
requireNoExtraArgs(rest, "rig task ready");
|
|
2416
|
-
await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
|
|
2417
|
-
return { ok: true, group: "task", command };
|
|
2418
|
-
case "run": {
|
|
2419
|
-
let pending = rest;
|
|
2420
|
-
const nextResult = takeFlag(pending, "--next");
|
|
2421
|
-
pending = nextResult.rest;
|
|
2422
|
-
const taskResult = takeOption(pending, "--task");
|
|
2423
|
-
pending = taskResult.rest;
|
|
2424
|
-
const titleResult = takeOption(pending, "--title");
|
|
2425
|
-
pending = titleResult.rest;
|
|
2426
|
-
const runtimeAdapterResult = takeOption(pending, "--runtime-adapter");
|
|
2427
|
-
pending = runtimeAdapterResult.rest;
|
|
2428
|
-
const modelResult = takeOption(pending, "--model");
|
|
2429
|
-
pending = modelResult.rest;
|
|
2430
|
-
const runtimeModeResult = takeOption(pending, "--runtime-mode");
|
|
2431
|
-
pending = runtimeModeResult.rest;
|
|
2432
|
-
const interactionModeResult = takeOption(pending, "--interaction-mode");
|
|
2433
|
-
pending = interactionModeResult.rest;
|
|
2434
|
-
const initialPromptResult = takeOption(pending, "--initial-prompt");
|
|
2435
|
-
pending = initialPromptResult.rest;
|
|
2436
|
-
const prResult = takeOption(pending, "--pr");
|
|
2437
|
-
pending = prResult.rest;
|
|
2438
|
-
const noPrResult = takeFlag(pending, "--no-pr");
|
|
2439
|
-
pending = noPrResult.rest;
|
|
2440
|
-
const dirtyBaselineResult = takeOption(pending, "--dirty-baseline");
|
|
2441
|
-
pending = dirtyBaselineResult.rest;
|
|
2442
|
-
const skipProjectSyncResult = takeFlag(pending, "--skip-project-sync");
|
|
2443
|
-
pending = skipProjectSyncResult.rest;
|
|
2444
|
-
const detachResult = takeFlag(pending, "--detach");
|
|
2445
|
-
pending = detachResult.rest;
|
|
2446
|
-
const filterResult = parseTaskFilters(pending);
|
|
2447
|
-
pending = filterResult.rest;
|
|
2448
|
-
const positionalTaskId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? normalizeTaskRunTaskId(pending[0]) : null;
|
|
2449
|
-
if (positionalTaskId) {
|
|
2450
|
-
pending = pending.slice(1);
|
|
2451
|
-
}
|
|
2452
|
-
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]");
|
|
2453
|
-
if (nextResult.value && (taskResult.value || positionalTaskId)) {
|
|
2454
|
-
throw new CliError2("task run cannot combine --next with an explicit task id.", 2);
|
|
2455
|
-
}
|
|
2456
|
-
if (taskResult.value && positionalTaskId) {
|
|
2457
|
-
throw new CliError2("task run cannot combine positional task id with --task <id>.", 2);
|
|
2458
|
-
}
|
|
2459
|
-
if (prResult.value && noPrResult.value) {
|
|
2460
|
-
throw new CliError2("task run cannot combine --pr with --no-pr.", 2);
|
|
2461
|
-
}
|
|
2462
|
-
let selectedTask = null;
|
|
2463
|
-
let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
|
|
2464
|
-
if (nextResult.value) {
|
|
2465
|
-
const selected = await selectNextWorkspaceTaskViaServer(context, filterResult.filters);
|
|
2466
|
-
selectedTask = selected.task;
|
|
2467
|
-
selectedTaskId = selected.task ? readTaskId(selected.task) : null;
|
|
2468
|
-
if (!selectedTaskId) {
|
|
2469
|
-
throw new CliError2("No matching task found for task run --next.", 3);
|
|
2470
|
-
}
|
|
2471
|
-
}
|
|
2472
|
-
if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
|
|
2473
|
-
if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
|
|
2474
|
-
throw new CliError2("task run requires an interactive terminal to pick a task; pass --next, --task <id>, or --initial-prompt/--title for an ad hoc run.", 2);
|
|
2475
|
-
}
|
|
2476
|
-
const tasks = await listWorkspaceTasksViaServer(context, filterResult.filters);
|
|
2477
|
-
selectedTask = await selectTaskWithTextPicker(tasks);
|
|
2478
|
-
selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
|
|
2479
|
-
if (!selectedTaskId) {
|
|
2480
|
-
throw new CliError2("No task selected.", 3);
|
|
2481
|
-
}
|
|
2482
|
-
}
|
|
2483
|
-
await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
|
|
2484
|
-
const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
|
|
2485
|
-
const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
|
|
2486
|
-
await runFastTaskRunPreflight(context, {
|
|
2487
|
-
taskId: selectedTaskId,
|
|
2488
|
-
runtimeAdapter
|
|
2489
|
-
});
|
|
2490
|
-
const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
|
|
2491
|
-
const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
|
|
2492
|
-
const submitted = await submitTaskRunViaServer(context, {
|
|
2493
|
-
runId: context.runId,
|
|
2494
|
-
taskId: selectedTaskId ?? undefined,
|
|
2495
|
-
title: titleResult.value ?? undefined,
|
|
2496
|
-
runtimeAdapter,
|
|
2497
|
-
model: modelResult.value ?? projectDefaults.model,
|
|
2498
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2499
|
-
interactionMode: interactionModeResult.value || "default",
|
|
2500
|
-
initialPrompt: initialPromptResult.value ?? undefined,
|
|
2501
|
-
baselineMode: dirtyBaseline.mode,
|
|
2502
|
-
prMode
|
|
2503
|
-
});
|
|
2504
|
-
let attachDetails = null;
|
|
2505
|
-
if (!detachResult.value && context.outputMode === "text") {
|
|
2506
|
-
printFormattedOutput(formatSubmittedRun({
|
|
2507
|
-
runId: submitted.runId,
|
|
2508
|
-
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2509
|
-
runtimeAdapter,
|
|
2510
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2511
|
-
interactionMode: interactionModeResult.value || "default",
|
|
2512
|
-
detached: false
|
|
2513
|
-
}));
|
|
2514
|
-
attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
|
|
2515
|
-
} else if (context.outputMode === "text") {
|
|
2516
|
-
printFormattedOutput(formatSubmittedRun({
|
|
2517
|
-
runId: submitted.runId,
|
|
2518
|
-
task: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2519
|
-
runtimeAdapter,
|
|
2520
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2521
|
-
interactionMode: interactionModeResult.value || "default",
|
|
2522
|
-
detached: true
|
|
2523
|
-
}));
|
|
2524
|
-
}
|
|
2525
|
-
return {
|
|
2526
|
-
ok: true,
|
|
2527
|
-
group: "task",
|
|
2528
|
-
command,
|
|
2529
|
-
details: {
|
|
2530
|
-
runId: submitted.runId,
|
|
2531
|
-
taskId: selectedTaskId,
|
|
2532
|
-
title: titleResult.value ?? null,
|
|
2533
|
-
selectedTask: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2534
|
-
filters: nextResult.value ? filterResult.filters : undefined,
|
|
2535
|
-
attached: Boolean(attachDetails),
|
|
2536
|
-
attach: attachDetails,
|
|
2537
|
-
runtimeAdapter,
|
|
2538
|
-
model: modelResult.value ?? projectDefaults.model ?? null,
|
|
2539
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2540
|
-
prMode: prMode ?? null,
|
|
2541
|
-
dirtyBaseline: { mode: dirtyBaseline.mode, dirty: dirtyBaseline.state?.dirty ?? false }
|
|
2542
|
-
}
|
|
2543
|
-
};
|
|
2544
|
-
}
|
|
2545
|
-
case "validate": {
|
|
2546
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2547
|
-
requireNoExtraArgs(remaining, "rig task validate [--task <task-id>]");
|
|
2548
|
-
if (context.dryRun) {
|
|
2549
|
-
await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
|
|
2550
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2551
|
-
}
|
|
2552
|
-
const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
|
|
2553
|
-
if (!ok) {
|
|
2554
|
-
throw new CliError2(`Validation failed for ${task || "active task"}.`, 2);
|
|
2555
|
-
}
|
|
2556
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2557
|
-
}
|
|
2558
|
-
case "verify": {
|
|
2559
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2560
|
-
requireNoExtraArgs(remaining, "rig task verify [--task <task-id>]");
|
|
2561
|
-
if (context.dryRun) {
|
|
2562
|
-
await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
|
|
2563
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2564
|
-
}
|
|
2565
|
-
const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, context.plugins, task || undefined));
|
|
2566
|
-
if (!ok) {
|
|
2567
|
-
throw new CliError2(`Verification rejected for ${task || "active task"}.`, 2);
|
|
2568
|
-
}
|
|
2569
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2570
|
-
}
|
|
2571
|
-
case "reset": {
|
|
2572
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2573
|
-
requireNoExtraArgs(remaining, "rig task reset --task <task-id>");
|
|
2574
|
-
const requiredTask = requireTask(task, "rig task reset --task <task-id>");
|
|
2575
|
-
await context.runCommand(["br", "--no-db", "update", requiredTask, "--status", "open"]);
|
|
2576
|
-
return { ok: true, group: "task", command, details: { task: requiredTask } };
|
|
2577
|
-
}
|
|
2578
|
-
case "details": {
|
|
2579
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2580
|
-
requireNoExtraArgs(remaining, "rig task details --task <task-id>");
|
|
2581
|
-
const requiredTask = requireTask(task, "rig task details --task <task-id>");
|
|
2582
|
-
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
|
|
2583
|
-
return { ok: true, group: "task", command, details: { task: requiredTask } };
|
|
2584
|
-
}
|
|
2585
|
-
case "reopen": {
|
|
2586
|
-
const { value: task, rest: rest1 } = takeOption(rest, "--task");
|
|
2587
|
-
const allFlag = takeFlag(rest1, "--all");
|
|
2588
|
-
const { rest: remaining } = takeOption(allFlag.rest, "--reason");
|
|
2589
|
-
requireNoExtraArgs(remaining, "rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
2590
|
-
if (!allFlag.value && !task) {
|
|
2591
|
-
throw new CliError2("Usage: rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
2592
|
-
}
|
|
2593
|
-
const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
|
|
2594
|
-
all: allFlag.value,
|
|
2595
|
-
taskId: task || undefined,
|
|
2596
|
-
dryRun: false
|
|
2597
|
-
}));
|
|
2598
|
-
return { ok: true, group: "task", command, details: summary };
|
|
2599
|
-
}
|
|
2600
|
-
default:
|
|
2601
|
-
throw new CliError2(`Unknown task command: ${command}`);
|
|
2602
|
-
}
|
|
2603
|
-
}
|
|
2604
|
-
export {
|
|
2605
|
-
executeTask
|
|
2606
|
-
};
|