@h-rig/cli 0.0.6-alpha.27 → 0.0.6-alpha.280
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 -11321
- package/dist/src/commands/_authority-runs.js +0 -111
- package/dist/src/commands/_cli-format.js +0 -164
- 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 -203
- 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 -288
- 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 -160
- 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 -1688
- package/dist/src/commands/server.js +0 -571
- 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 -2200
- package/dist/src/commands/test.js +0 -39
- package/dist/src/commands/workspace.js +0 -123
- package/dist/src/commands.js +0 -11000
- package/dist/src/index.js +0 -11339
- 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,2200 +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 connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect 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 connection", 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 connection", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig connect 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 pc from "picocolors";
|
|
1626
|
-
function stringField(record, key, fallback = "") {
|
|
1627
|
-
const value = record[key];
|
|
1628
|
-
return typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
1629
|
-
}
|
|
1630
|
-
function arrayField(record, key) {
|
|
1631
|
-
const value = record[key];
|
|
1632
|
-
return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
|
|
1633
|
-
}
|
|
1634
|
-
function rawObject(record) {
|
|
1635
|
-
const raw = record.raw;
|
|
1636
|
-
return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
1637
|
-
}
|
|
1638
|
-
function truncate(value, width) {
|
|
1639
|
-
if (value.length <= width)
|
|
1640
|
-
return value;
|
|
1641
|
-
if (width <= 1)
|
|
1642
|
-
return "\u2026";
|
|
1643
|
-
return `${value.slice(0, width - 1)}\u2026`;
|
|
1644
|
-
}
|
|
1645
|
-
function pad(value, width) {
|
|
1646
|
-
return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
|
|
1647
|
-
}
|
|
1648
|
-
function statusColor(status) {
|
|
1649
|
-
const normalized = status.toLowerCase();
|
|
1650
|
-
if (["completed", "merged", "closed", "done", "accepted", "pass", "selected"].includes(normalized))
|
|
1651
|
-
return pc.green;
|
|
1652
|
-
if (["failed", "needs_attention", "needs-attention", "blocked", "error"].includes(normalized))
|
|
1653
|
-
return pc.red;
|
|
1654
|
-
if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
|
|
1655
|
-
return pc.cyan;
|
|
1656
|
-
if (["ready", "open", "queued", "created", "preparing", "local"].includes(normalized))
|
|
1657
|
-
return pc.yellow;
|
|
1658
|
-
return pc.dim;
|
|
1659
|
-
}
|
|
1660
|
-
function formatStatusPill(status) {
|
|
1661
|
-
const label = status || "unknown";
|
|
1662
|
-
return statusColor(label)(`\u25CF ${label}`);
|
|
1663
|
-
}
|
|
1664
|
-
function formatSection(title, subtitle) {
|
|
1665
|
-
return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
|
|
1666
|
-
}
|
|
1667
|
-
function formatSuccessCard(title, rows = []) {
|
|
1668
|
-
const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${pc.dim("\u2502")} ${pc.dim(key.padEnd(9))} ${value}`);
|
|
1669
|
-
return [formatSection(title), ...body].join(`
|
|
1670
|
-
`);
|
|
1671
|
-
}
|
|
1672
|
-
function formatNextSteps(steps) {
|
|
1673
|
-
if (steps.length === 0)
|
|
1674
|
-
return [];
|
|
1675
|
-
return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
|
|
1676
|
-
}
|
|
1677
|
-
function formatTaskList(tasks, options = {}) {
|
|
1678
|
-
if (options.raw)
|
|
1679
|
-
return tasks.map((task) => JSON.stringify(task)).join(`
|
|
1680
|
-
`);
|
|
1681
|
-
if (tasks.length === 0)
|
|
1682
|
-
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(`
|
|
1683
|
-
`);
|
|
1684
|
-
const rows = tasks.map((task) => {
|
|
1685
|
-
const raw = rawObject(task);
|
|
1686
|
-
const id = stringField(task, "id", "<unknown>");
|
|
1687
|
-
const status = stringField(task, "status", "unknown");
|
|
1688
|
-
const title = stringField(task, "title", "Untitled task");
|
|
1689
|
-
const source = stringField(task, "source", stringField(raw, "source", ""));
|
|
1690
|
-
const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
|
|
1691
|
-
return { id, status, title, source, labels };
|
|
1692
|
-
});
|
|
1693
|
-
const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
|
|
1694
|
-
const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
|
|
1695
|
-
const header = `${pc.bold(pad("TASK", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
|
|
1696
|
-
const body = rows.map((row) => {
|
|
1697
|
-
const labels = row.labels.length > 0 ? pc.dim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
|
|
1698
|
-
const source = row.source ? pc.dim(` ${row.source}`) : "";
|
|
1699
|
-
return [
|
|
1700
|
-
pc.bold(pad(truncate(row.id, idWidth), idWidth)),
|
|
1701
|
-
statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
|
|
1702
|
-
`${row.title}${labels}${source}`
|
|
1703
|
-
].join(" ");
|
|
1704
|
-
});
|
|
1705
|
-
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(`
|
|
1706
|
-
`);
|
|
1707
|
-
}
|
|
1708
|
-
function formatSubmittedRun(input) {
|
|
1709
|
-
const rows = [["run", pc.bold(input.runId)]];
|
|
1710
|
-
if (input.task) {
|
|
1711
|
-
const id = stringField(input.task, "id", "<unknown>");
|
|
1712
|
-
const status = stringField(input.task, "status", "unknown");
|
|
1713
|
-
const title = stringField(input.task, "title", "Untitled task");
|
|
1714
|
-
rows.push(["task", `${pc.bold(id)} ${formatStatusPill(status)} ${title}`]);
|
|
1715
|
-
}
|
|
1716
|
-
return [
|
|
1717
|
-
formatSuccessCard("Run submitted", rows),
|
|
1718
|
-
"",
|
|
1719
|
-
...formatNextSteps([`Attach: \`rig run attach ${input.runId} --follow\``, `Inspect: \`rig run show --run ${input.runId}\``])
|
|
1720
|
-
].join(`
|
|
1721
|
-
`);
|
|
1722
|
-
}
|
|
1723
|
-
|
|
1724
|
-
// packages/cli/src/commands/task.ts
|
|
1725
|
-
import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
|
|
1726
|
-
import { loadConfig } from "@rig/core/load-config";
|
|
1727
|
-
async function readStdin() {
|
|
1728
|
-
const chunks = [];
|
|
1729
|
-
for await (const chunk of process.stdin) {
|
|
1730
|
-
chunks.push(Buffer.from(chunk));
|
|
1731
|
-
}
|
|
1732
|
-
return Buffer.concat(chunks).toString("utf-8");
|
|
1733
|
-
}
|
|
1734
|
-
function normalizeAssignedToAlias(value) {
|
|
1735
|
-
if (!value)
|
|
1736
|
-
return;
|
|
1737
|
-
return value.trim().toLowerCase() === "me" ? "@me" : value;
|
|
1738
|
-
}
|
|
1739
|
-
function parseTaskFilters(args) {
|
|
1740
|
-
let pending = args;
|
|
1741
|
-
const assigneeResult = takeOption(pending, "--assignee");
|
|
1742
|
-
pending = assigneeResult.rest;
|
|
1743
|
-
const assignedToResult = takeOption(pending, "--assigned-to");
|
|
1744
|
-
pending = assignedToResult.rest;
|
|
1745
|
-
const stateResult = takeOption(pending, "--state");
|
|
1746
|
-
pending = stateResult.rest;
|
|
1747
|
-
const statusResult = takeOption(pending, "--status");
|
|
1748
|
-
pending = statusResult.rest;
|
|
1749
|
-
const limitResult = takeOption(pending, "--limit");
|
|
1750
|
-
pending = limitResult.rest;
|
|
1751
|
-
const normalizedAssignedTo = normalizeAssignedToAlias(assignedToResult.value);
|
|
1752
|
-
if (assigneeResult.value && normalizedAssignedTo && assigneeResult.value !== normalizedAssignedTo) {
|
|
1753
|
-
throw new CliError2("--assignee and --assigned-to cannot specify different assignees.", 2);
|
|
1754
|
-
}
|
|
1755
|
-
const assignee = normalizedAssignedTo ?? assigneeResult.value;
|
|
1756
|
-
const limit = (() => {
|
|
1757
|
-
if (!limitResult.value)
|
|
1758
|
-
return;
|
|
1759
|
-
const parsed = Number.parseInt(limitResult.value, 10);
|
|
1760
|
-
if (!Number.isFinite(parsed) || parsed < 1) {
|
|
1761
|
-
throw new CliError2("--limit must be a positive integer.", 2);
|
|
1762
|
-
}
|
|
1763
|
-
return parsed;
|
|
1764
|
-
})();
|
|
1765
|
-
const filters = {
|
|
1766
|
-
...assignee ? { assignee } : {},
|
|
1767
|
-
...stateResult.value ? { state: stateResult.value } : {},
|
|
1768
|
-
...statusResult.value ? { status: statusResult.value } : {},
|
|
1769
|
-
...limit !== undefined ? { limit } : {}
|
|
1770
|
-
};
|
|
1771
|
-
return { filters, rest: pending };
|
|
1772
|
-
}
|
|
1773
|
-
function mapConfiguredRuntimeMode(mode) {
|
|
1774
|
-
if (!mode)
|
|
1775
|
-
return;
|
|
1776
|
-
return mode === "yolo" ? "full-access" : mode;
|
|
1777
|
-
}
|
|
1778
|
-
async function loadTaskRunProjectDefaults(projectRoot) {
|
|
1779
|
-
try {
|
|
1780
|
-
const config = await loadConfig(projectRoot);
|
|
1781
|
-
return {
|
|
1782
|
-
runtimeAdapter: config.runtime?.harness,
|
|
1783
|
-
model: config.runtime?.model,
|
|
1784
|
-
runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
|
|
1785
|
-
prMode: config.pr?.mode
|
|
1786
|
-
};
|
|
1787
|
-
} catch {
|
|
1788
|
-
return {};
|
|
1789
|
-
}
|
|
1790
|
-
}
|
|
1791
|
-
function normalizePrMode(value) {
|
|
1792
|
-
if (!value)
|
|
1793
|
-
return;
|
|
1794
|
-
if (value === "auto" || value === "ask" || value === "off")
|
|
1795
|
-
return value;
|
|
1796
|
-
throw new CliError2("--pr must be auto, ask, or off.", 2);
|
|
1797
|
-
}
|
|
1798
|
-
function detectLocalDirtyState(projectRoot) {
|
|
1799
|
-
const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
|
|
1800
|
-
if (result.status !== 0)
|
|
1801
|
-
return { dirty: false, modified: 0, untracked: 0, lines: [] };
|
|
1802
|
-
const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
|
|
1803
|
-
return {
|
|
1804
|
-
dirty: lines.length > 0,
|
|
1805
|
-
modified: lines.filter((line) => !line.startsWith("?? ")).length,
|
|
1806
|
-
untracked: lines.filter((line) => line.startsWith("?? ")).length,
|
|
1807
|
-
lines
|
|
1808
|
-
};
|
|
1809
|
-
}
|
|
1810
|
-
function selectedServerKind(projectRoot) {
|
|
1811
|
-
try {
|
|
1812
|
-
return resolveSelectedConnection(projectRoot)?.connection.kind === "remote" ? "remote" : "local";
|
|
1813
|
-
} catch {
|
|
1814
|
-
return "local";
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
async function resolveDirtyBaselineForTaskRun(context, explicit) {
|
|
1818
|
-
if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
|
|
1819
|
-
throw new CliError2("--dirty-baseline must be head or dirty-snapshot.", 2);
|
|
1820
|
-
}
|
|
1821
|
-
if (selectedServerKind(context.projectRoot) !== "local") {
|
|
1822
|
-
return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
|
|
1823
|
-
}
|
|
1824
|
-
const state = detectLocalDirtyState(context.projectRoot);
|
|
1825
|
-
if (!state.dirty)
|
|
1826
|
-
return { mode: "head", state };
|
|
1827
|
-
if (context.outputMode === "text") {
|
|
1828
|
-
console.log(`Repo state: dirty (${state.modified} modified, ${state.untracked} untracked).`);
|
|
1829
|
-
}
|
|
1830
|
-
if (explicit)
|
|
1831
|
-
return { mode: explicit, state };
|
|
1832
|
-
if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
|
|
1833
|
-
const answer = await confirm({
|
|
1834
|
-
message: "Include current uncommitted changes in run baseline?",
|
|
1835
|
-
initialValue: false
|
|
1836
|
-
});
|
|
1837
|
-
if (isCancel2(answer)) {
|
|
1838
|
-
cancel2("Run cancelled.");
|
|
1839
|
-
throw new CliError2("Run cancelled by user.", 1);
|
|
1840
|
-
}
|
|
1841
|
-
return { mode: answer ? "dirty-snapshot" : "head", state };
|
|
1842
|
-
}
|
|
1843
|
-
return { mode: "head", state };
|
|
1844
|
-
}
|
|
1845
|
-
function normalizeTaskRunTaskId(value) {
|
|
1846
|
-
const trimmed = value?.trim() ?? "";
|
|
1847
|
-
if (!trimmed)
|
|
1848
|
-
return null;
|
|
1849
|
-
const issueNumber = trimmed.match(/^#(\d+)$/)?.[1];
|
|
1850
|
-
return issueNumber ?? trimmed;
|
|
1851
|
-
}
|
|
1852
|
-
function readTaskId(task) {
|
|
1853
|
-
return typeof task.id === "string" && task.id.trim().length > 0 ? task.id : null;
|
|
1854
|
-
}
|
|
1855
|
-
function readTaskString(task, key) {
|
|
1856
|
-
const value = task[key];
|
|
1857
|
-
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
1858
|
-
}
|
|
1859
|
-
function summarizeTask(task, options = {}) {
|
|
1860
|
-
const raw = task.raw && typeof task.raw === "object" && !Array.isArray(task.raw) ? task.raw : null;
|
|
1861
|
-
return {
|
|
1862
|
-
id: readTaskId(task),
|
|
1863
|
-
title: readTaskString(task, "title"),
|
|
1864
|
-
status: readTaskString(task, "status"),
|
|
1865
|
-
source: typeof task.source === "string" ? task.source : undefined,
|
|
1866
|
-
url: typeof raw?.url === "string" ? raw.url : undefined,
|
|
1867
|
-
number: typeof raw?.number === "number" ? raw.number : undefined,
|
|
1868
|
-
labels: Array.isArray(task.labels) ? task.labels : Array.isArray(raw?.labels) ? raw.labels : undefined,
|
|
1869
|
-
assignees: Array.isArray(raw?.assignees) ? raw.assignees : undefined,
|
|
1870
|
-
readiness: typeof task.readiness === "string" || typeof task.readiness === "boolean" ? task.readiness : undefined,
|
|
1871
|
-
validators: Array.isArray(task.validators) ? task.validators : Array.isArray(task.validation) ? task.validation : undefined,
|
|
1872
|
-
...options.raw ? { raw: raw ?? task } : {}
|
|
1873
|
-
};
|
|
1874
|
-
}
|
|
1875
|
-
function printTaskSummary(task) {
|
|
1876
|
-
console.log(formatTaskList([task]));
|
|
1877
|
-
}
|
|
1878
|
-
async function validatorRegistryForTaskCommands(projectRoot) {
|
|
1879
|
-
return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
|
|
1880
|
-
return;
|
|
1881
|
-
});
|
|
1882
|
-
}
|
|
1883
|
-
async function executeTask(context, args, options) {
|
|
1884
|
-
const [command = "info", ...rest] = args;
|
|
1885
|
-
switch (command) {
|
|
1886
|
-
case "list": {
|
|
1887
|
-
let pending = rest;
|
|
1888
|
-
const rawResult = takeFlag(pending, "--raw");
|
|
1889
|
-
pending = rawResult.rest;
|
|
1890
|
-
const { filters, rest: remaining } = parseTaskFilters(pending);
|
|
1891
|
-
requireNoExtraArgs(remaining, "bun run rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
1892
|
-
const tasks = await listWorkspaceTasksViaServer(context, filters);
|
|
1893
|
-
if (context.outputMode === "text") {
|
|
1894
|
-
const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
|
|
1895
|
-
console.log(formatTaskList(renderedTasks, { raw: rawResult.value }));
|
|
1896
|
-
}
|
|
1897
|
-
return {
|
|
1898
|
-
ok: true,
|
|
1899
|
-
group: "task",
|
|
1900
|
-
command,
|
|
1901
|
-
details: { count: tasks.length, filters, raw: rawResult.value, tasks: tasks.map((task) => summarizeTask(task, { raw: rawResult.value })) }
|
|
1902
|
-
};
|
|
1903
|
-
}
|
|
1904
|
-
case "show": {
|
|
1905
|
-
const taskOption = takeOption(rest, "--task");
|
|
1906
|
-
const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
|
|
1907
|
-
const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
|
|
1908
|
-
requireNoExtraArgs(remaining, "bun run rig task show <id>|--task <id>");
|
|
1909
|
-
const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
|
|
1910
|
-
if (!taskId3)
|
|
1911
|
-
throw new CliError2("task show requires a task id.", 2);
|
|
1912
|
-
const task = await getWorkspaceTaskViaServer(context, taskId3);
|
|
1913
|
-
if (!task)
|
|
1914
|
-
throw new CliError2(`Task not found: ${taskId3}`, 3);
|
|
1915
|
-
const summary = summarizeTask(task, { raw: true });
|
|
1916
|
-
if (context.outputMode === "text")
|
|
1917
|
-
console.log(JSON.stringify(summary, null, 2));
|
|
1918
|
-
return { ok: true, group: "task", command, details: { task: summary } };
|
|
1919
|
-
}
|
|
1920
|
-
case "next": {
|
|
1921
|
-
const { filters, rest: remaining } = parseTaskFilters(rest);
|
|
1922
|
-
requireNoExtraArgs(remaining, "bun run rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
|
|
1923
|
-
const selected = await selectNextWorkspaceTaskViaServer(context, filters);
|
|
1924
|
-
if (context.outputMode === "text") {
|
|
1925
|
-
if (selected.task) {
|
|
1926
|
-
printTaskSummary(selected.task);
|
|
1927
|
-
} else {
|
|
1928
|
-
console.log("No matching tasks.");
|
|
1929
|
-
}
|
|
1930
|
-
}
|
|
1931
|
-
return {
|
|
1932
|
-
ok: true,
|
|
1933
|
-
group: "task",
|
|
1934
|
-
command,
|
|
1935
|
-
details: {
|
|
1936
|
-
count: selected.count,
|
|
1937
|
-
filters,
|
|
1938
|
-
task: selected.task ? summarizeTask(selected.task) : null
|
|
1939
|
-
}
|
|
1940
|
-
};
|
|
1941
|
-
}
|
|
1942
|
-
case "info": {
|
|
1943
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
1944
|
-
requireNoExtraArgs(remaining, "bun run rig task info [--task <beads-id>]");
|
|
1945
|
-
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
|
|
1946
|
-
return { ok: true, group: "task", command, details: { task: task || null } };
|
|
1947
|
-
}
|
|
1948
|
-
case "scope": {
|
|
1949
|
-
const filesFlag = takeFlag(rest, "--files");
|
|
1950
|
-
const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
|
|
1951
|
-
requireNoExtraArgs(remaining, "bun run rig task scope [--task <id>] [--files]");
|
|
1952
|
-
await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
|
|
1953
|
-
return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
|
|
1954
|
-
}
|
|
1955
|
-
case "deps":
|
|
1956
|
-
requireNoExtraArgs(rest, "bun run rig task deps");
|
|
1957
|
-
await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
|
|
1958
|
-
return { ok: true, group: "task", command };
|
|
1959
|
-
case "status":
|
|
1960
|
-
requireNoExtraArgs(rest, "bun run rig task status");
|
|
1961
|
-
withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
|
|
1962
|
-
return { ok: true, group: "task", command };
|
|
1963
|
-
case "artifacts":
|
|
1964
|
-
requireNoExtraArgs(rest, "bun run rig task artifacts");
|
|
1965
|
-
withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
|
|
1966
|
-
return { ok: true, group: "task", command };
|
|
1967
|
-
case "artifact-dir": {
|
|
1968
|
-
requireNoExtraArgs(rest, "bun run rig task artifact-dir");
|
|
1969
|
-
const path = taskArtifactDir(context.projectRoot);
|
|
1970
|
-
if (context.outputMode === "text") {
|
|
1971
|
-
console.log(path);
|
|
1972
|
-
}
|
|
1973
|
-
return { ok: true, group: "task", command, details: { path } };
|
|
1974
|
-
}
|
|
1975
|
-
case "artifact-write": {
|
|
1976
|
-
if (rest.length < 1) {
|
|
1977
|
-
throw new CliError2(`Usage: bun run rig task artifact-write <filename> [--file <path>]
|
|
1978
|
-
` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
|
|
1979
|
-
` + " Example: echo '...' | rig task artifact-write collection-audit.md");
|
|
1980
|
-
}
|
|
1981
|
-
const artifactFilename = rest[0];
|
|
1982
|
-
const fileFlag = takeOption(rest.slice(1), "--file");
|
|
1983
|
-
let content;
|
|
1984
|
-
if (fileFlag.value) {
|
|
1985
|
-
content = readFileSync3(resolve3(context.projectRoot, fileFlag.value), "utf-8");
|
|
1986
|
-
} else {
|
|
1987
|
-
content = await readStdin();
|
|
1988
|
-
}
|
|
1989
|
-
if (!artifactFilename) {
|
|
1990
|
-
throw new CliError2("Usage: bun run rig task artifact-write <filename> [--file path]");
|
|
1991
|
-
}
|
|
1992
|
-
withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
|
|
1993
|
-
return { ok: true, group: "task", command, details: { filename: artifactFilename } };
|
|
1994
|
-
}
|
|
1995
|
-
case "report-bug":
|
|
1996
|
-
return options.executeTaskReportBug(context, rest);
|
|
1997
|
-
case "lookup": {
|
|
1998
|
-
if (rest.length !== 1) {
|
|
1999
|
-
throw new CliError2("Usage: bun run rig task lookup <beads-id>");
|
|
2000
|
-
}
|
|
2001
|
-
const lookupId = rest[0];
|
|
2002
|
-
if (!lookupId) {
|
|
2003
|
-
throw new CliError2("Usage: bun run rig task lookup <beads-id>");
|
|
2004
|
-
}
|
|
2005
|
-
const result = taskLookup(context.projectRoot, lookupId);
|
|
2006
|
-
if (context.outputMode === "text") {
|
|
2007
|
-
console.log(result);
|
|
2008
|
-
}
|
|
2009
|
-
return { ok: true, group: "task", command, details: { id: lookupId, result } };
|
|
2010
|
-
}
|
|
2011
|
-
case "record": {
|
|
2012
|
-
if (rest.length < 2) {
|
|
2013
|
-
throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
|
|
2014
|
-
}
|
|
2015
|
-
const type = rest[0];
|
|
2016
|
-
if (type !== "decision" && type !== "failure") {
|
|
2017
|
-
throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
|
|
2018
|
-
}
|
|
2019
|
-
withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
|
|
2020
|
-
return { ok: true, group: "task", command, details: { type: rest[0] } };
|
|
2021
|
-
}
|
|
2022
|
-
case "ready":
|
|
2023
|
-
requireNoExtraArgs(rest, "bun run rig task ready");
|
|
2024
|
-
await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
|
|
2025
|
-
return { ok: true, group: "task", command };
|
|
2026
|
-
case "run": {
|
|
2027
|
-
let pending = rest;
|
|
2028
|
-
const nextResult = takeFlag(pending, "--next");
|
|
2029
|
-
pending = nextResult.rest;
|
|
2030
|
-
const taskResult = takeOption(pending, "--task");
|
|
2031
|
-
pending = taskResult.rest;
|
|
2032
|
-
const titleResult = takeOption(pending, "--title");
|
|
2033
|
-
pending = titleResult.rest;
|
|
2034
|
-
const runtimeAdapterResult = takeOption(pending, "--runtime-adapter");
|
|
2035
|
-
pending = runtimeAdapterResult.rest;
|
|
2036
|
-
const modelResult = takeOption(pending, "--model");
|
|
2037
|
-
pending = modelResult.rest;
|
|
2038
|
-
const runtimeModeResult = takeOption(pending, "--runtime-mode");
|
|
2039
|
-
pending = runtimeModeResult.rest;
|
|
2040
|
-
const interactionModeResult = takeOption(pending, "--interaction-mode");
|
|
2041
|
-
pending = interactionModeResult.rest;
|
|
2042
|
-
const initialPromptResult = takeOption(pending, "--initial-prompt");
|
|
2043
|
-
pending = initialPromptResult.rest;
|
|
2044
|
-
const prResult = takeOption(pending, "--pr");
|
|
2045
|
-
pending = prResult.rest;
|
|
2046
|
-
const noPrResult = takeFlag(pending, "--no-pr");
|
|
2047
|
-
pending = noPrResult.rest;
|
|
2048
|
-
const dirtyBaselineResult = takeOption(pending, "--dirty-baseline");
|
|
2049
|
-
pending = dirtyBaselineResult.rest;
|
|
2050
|
-
const skipProjectSyncResult = takeFlag(pending, "--skip-project-sync");
|
|
2051
|
-
pending = skipProjectSyncResult.rest;
|
|
2052
|
-
const detachResult = takeFlag(pending, "--detach");
|
|
2053
|
-
pending = detachResult.rest;
|
|
2054
|
-
const filterResult = parseTaskFilters(pending);
|
|
2055
|
-
pending = filterResult.rest;
|
|
2056
|
-
const positionalTaskId = pending.length > 0 && pending[0] && !pending[0].startsWith("-") ? normalizeTaskRunTaskId(pending[0]) : null;
|
|
2057
|
-
if (positionalTaskId) {
|
|
2058
|
-
pending = pending.slice(1);
|
|
2059
|
-
}
|
|
2060
|
-
requireNoExtraArgs(pending, "bun run 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]");
|
|
2061
|
-
if (nextResult.value && (taskResult.value || positionalTaskId)) {
|
|
2062
|
-
throw new CliError2("task run cannot combine --next with an explicit task id.", 2);
|
|
2063
|
-
}
|
|
2064
|
-
if (taskResult.value && positionalTaskId) {
|
|
2065
|
-
throw new CliError2("task run cannot combine positional task id with --task <id>.", 2);
|
|
2066
|
-
}
|
|
2067
|
-
if (prResult.value && noPrResult.value) {
|
|
2068
|
-
throw new CliError2("task run cannot combine --pr with --no-pr.", 2);
|
|
2069
|
-
}
|
|
2070
|
-
let selectedTask = null;
|
|
2071
|
-
let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
|
|
2072
|
-
if (nextResult.value) {
|
|
2073
|
-
const selected = await selectNextWorkspaceTaskViaServer(context, filterResult.filters);
|
|
2074
|
-
selectedTask = selected.task;
|
|
2075
|
-
selectedTaskId = selected.task ? readTaskId(selected.task) : null;
|
|
2076
|
-
if (!selectedTaskId) {
|
|
2077
|
-
throw new CliError2("No matching task found for task run --next.", 3);
|
|
2078
|
-
}
|
|
2079
|
-
}
|
|
2080
|
-
if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
|
|
2081
|
-
if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
|
|
2082
|
-
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);
|
|
2083
|
-
}
|
|
2084
|
-
const tasks = await listWorkspaceTasksViaServer(context, filterResult.filters);
|
|
2085
|
-
selectedTask = await selectTaskWithTextPicker(tasks);
|
|
2086
|
-
selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
|
|
2087
|
-
if (!selectedTaskId) {
|
|
2088
|
-
throw new CliError2("No task selected.", 3);
|
|
2089
|
-
}
|
|
2090
|
-
}
|
|
2091
|
-
await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
|
|
2092
|
-
const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
|
|
2093
|
-
const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
|
|
2094
|
-
await runFastTaskRunPreflight(context, {
|
|
2095
|
-
taskId: selectedTaskId,
|
|
2096
|
-
runtimeAdapter
|
|
2097
|
-
});
|
|
2098
|
-
const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
|
|
2099
|
-
const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
|
|
2100
|
-
const submitted = await submitTaskRunViaServer(context, {
|
|
2101
|
-
runId: context.runId,
|
|
2102
|
-
taskId: selectedTaskId ?? undefined,
|
|
2103
|
-
title: titleResult.value ?? undefined,
|
|
2104
|
-
runtimeAdapter,
|
|
2105
|
-
model: modelResult.value ?? projectDefaults.model,
|
|
2106
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2107
|
-
interactionMode: interactionModeResult.value || "default",
|
|
2108
|
-
initialPrompt: initialPromptResult.value ?? undefined,
|
|
2109
|
-
baselineMode: dirtyBaseline.mode,
|
|
2110
|
-
prMode
|
|
2111
|
-
});
|
|
2112
|
-
let attachDetails = null;
|
|
2113
|
-
if (!detachResult.value && context.outputMode === "text") {
|
|
2114
|
-
console.log(formatSubmittedRun({ runId: submitted.runId, task: selectedTask ? summarizeTask(selectedTask) : null }));
|
|
2115
|
-
attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
|
|
2116
|
-
} else if (context.outputMode === "text") {
|
|
2117
|
-
console.log(formatSubmittedRun({ runId: submitted.runId, task: selectedTask ? summarizeTask(selectedTask) : null }));
|
|
2118
|
-
}
|
|
2119
|
-
return {
|
|
2120
|
-
ok: true,
|
|
2121
|
-
group: "task",
|
|
2122
|
-
command,
|
|
2123
|
-
details: {
|
|
2124
|
-
runId: submitted.runId,
|
|
2125
|
-
taskId: selectedTaskId,
|
|
2126
|
-
title: titleResult.value ?? null,
|
|
2127
|
-
selectedTask: selectedTask ? summarizeTask(selectedTask) : null,
|
|
2128
|
-
filters: nextResult.value ? filterResult.filters : undefined,
|
|
2129
|
-
attached: Boolean(attachDetails),
|
|
2130
|
-
attach: attachDetails,
|
|
2131
|
-
runtimeAdapter,
|
|
2132
|
-
model: modelResult.value ?? projectDefaults.model ?? null,
|
|
2133
|
-
runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
|
|
2134
|
-
prMode: prMode ?? null,
|
|
2135
|
-
dirtyBaseline: { mode: dirtyBaseline.mode, dirty: dirtyBaseline.state?.dirty ?? false }
|
|
2136
|
-
}
|
|
2137
|
-
};
|
|
2138
|
-
}
|
|
2139
|
-
case "validate": {
|
|
2140
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2141
|
-
requireNoExtraArgs(remaining, "bun run rig task validate [--task <beads-id>]");
|
|
2142
|
-
if (context.dryRun) {
|
|
2143
|
-
await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
|
|
2144
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2145
|
-
}
|
|
2146
|
-
const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
|
|
2147
|
-
if (!ok) {
|
|
2148
|
-
throw new CliError2(`Validation failed for ${task || "active task"}.`, 2);
|
|
2149
|
-
}
|
|
2150
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2151
|
-
}
|
|
2152
|
-
case "verify": {
|
|
2153
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2154
|
-
requireNoExtraArgs(remaining, "bun run rig task verify [--task <beads-id>]");
|
|
2155
|
-
if (context.dryRun) {
|
|
2156
|
-
await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
|
|
2157
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2158
|
-
}
|
|
2159
|
-
const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, context.plugins, task || undefined));
|
|
2160
|
-
if (!ok) {
|
|
2161
|
-
throw new CliError2(`Verification rejected for ${task || "active task"}.`, 2);
|
|
2162
|
-
}
|
|
2163
|
-
return { ok: true, group: "task", command, details: { task: task || "active" } };
|
|
2164
|
-
}
|
|
2165
|
-
case "reset": {
|
|
2166
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2167
|
-
requireNoExtraArgs(remaining, "bun run rig task reset --task <beads-id>");
|
|
2168
|
-
const requiredTask = requireTask(task, "bun run rig task reset --task <beads-id>");
|
|
2169
|
-
await context.runCommand(["br", "--no-db", "update", requiredTask, "--status", "open"]);
|
|
2170
|
-
return { ok: true, group: "task", command, details: { task: requiredTask } };
|
|
2171
|
-
}
|
|
2172
|
-
case "details": {
|
|
2173
|
-
const { value: task, rest: remaining } = takeOption(rest, "--task");
|
|
2174
|
-
requireNoExtraArgs(remaining, "bun run rig task details --task <beads-id>");
|
|
2175
|
-
const requiredTask = requireTask(task, "bun run rig task details --task <beads-id>");
|
|
2176
|
-
await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
|
|
2177
|
-
return { ok: true, group: "task", command, details: { task: requiredTask } };
|
|
2178
|
-
}
|
|
2179
|
-
case "reopen": {
|
|
2180
|
-
const { value: task, rest: rest1 } = takeOption(rest, "--task");
|
|
2181
|
-
const allFlag = takeFlag(rest1, "--all");
|
|
2182
|
-
const { rest: remaining } = takeOption(allFlag.rest, "--reason");
|
|
2183
|
-
requireNoExtraArgs(remaining, "bun run rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
2184
|
-
if (!allFlag.value && !task) {
|
|
2185
|
-
throw new CliError2("Usage: bun run rig task reopen [--task <id> | --all] [--reason <text>]");
|
|
2186
|
-
}
|
|
2187
|
-
const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
|
|
2188
|
-
all: allFlag.value,
|
|
2189
|
-
taskId: task || undefined,
|
|
2190
|
-
dryRun: false
|
|
2191
|
-
}));
|
|
2192
|
-
return { ok: true, group: "task", command, details: summary };
|
|
2193
|
-
}
|
|
2194
|
-
default:
|
|
2195
|
-
throw new CliError2(`Unknown task command: ${command}`);
|
|
2196
|
-
}
|
|
2197
|
-
}
|
|
2198
|
-
export {
|
|
2199
|
-
executeTask
|
|
2200
|
-
};
|