@h-rig/cli 0.0.6-alpha.7 → 0.0.6-alpha.70

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.
Files changed (53) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/rig.js +4507 -1506
  3. package/dist/src/commands/_async-ui.js +152 -0
  4. package/dist/src/commands/_authority-runs.js +2 -3
  5. package/dist/src/commands/_cli-format.js +369 -0
  6. package/dist/src/commands/_connection-state.js +30 -11
  7. package/dist/src/commands/_doctor-checks.js +177 -43
  8. package/dist/src/commands/_help-catalog.js +485 -0
  9. package/dist/src/commands/_json-output.js +56 -0
  10. package/dist/src/commands/_operator-surface.js +220 -0
  11. package/dist/src/commands/_operator-view.js +595 -72
  12. package/dist/src/commands/_parsers.js +18 -11
  13. package/dist/src/commands/_pi-frontend.js +411 -0
  14. package/dist/src/commands/_pi-install.js +4 -3
  15. package/dist/src/commands/_policy.js +12 -5
  16. package/dist/src/commands/_preflight.js +187 -127
  17. package/dist/src/commands/_run-driver-helpers.js +75 -22
  18. package/dist/src/commands/_run-replay.js +142 -0
  19. package/dist/src/commands/_server-client.js +343 -60
  20. package/dist/src/commands/_snapshot-upload.js +160 -38
  21. package/dist/src/commands/_spinner.js +65 -0
  22. package/dist/src/commands/_task-picker.js +44 -16
  23. package/dist/src/commands/agent.js +39 -20
  24. package/dist/src/commands/browser.js +28 -21
  25. package/dist/src/commands/connect.js +146 -33
  26. package/dist/src/commands/dist.js +19 -12
  27. package/dist/src/commands/doctor.js +304 -44
  28. package/dist/src/commands/github.js +301 -52
  29. package/dist/src/commands/inbox.js +679 -72
  30. package/dist/src/commands/init.js +622 -118
  31. package/dist/src/commands/inspect.js +515 -32
  32. package/dist/src/commands/inspector.js +20 -13
  33. package/dist/src/commands/pi.js +177 -0
  34. package/dist/src/commands/plugin.js +95 -27
  35. package/dist/src/commands/profile-and-review.js +26 -19
  36. package/dist/src/commands/queue.js +32 -12
  37. package/dist/src/commands/remote.js +43 -36
  38. package/dist/src/commands/repo-git-harness.js +22 -15
  39. package/dist/src/commands/run.js +1162 -158
  40. package/dist/src/commands/server.js +373 -56
  41. package/dist/src/commands/setup.js +316 -62
  42. package/dist/src/commands/stats.js +1030 -0
  43. package/dist/src/commands/task-report-bug.js +29 -22
  44. package/dist/src/commands/task-run-driver.js +862 -129
  45. package/dist/src/commands/task.js +1423 -311
  46. package/dist/src/commands/test.js +15 -8
  47. package/dist/src/commands/workspace.js +18 -11
  48. package/dist/src/commands.js +4446 -1499
  49. package/dist/src/index.js +4502 -1504
  50. package/dist/src/launcher.js +77 -13
  51. package/dist/src/report-bug.js +3 -3
  52. package/dist/src/runner.js +16 -22
  53. package/package.json +10 -5
@@ -1,16 +1,19 @@
1
1
  // @bun
2
- // packages/cli/src/commands/inbox.ts
3
- import { writeFileSync } from "fs";
4
- import { resolve } from "path";
5
-
6
2
  // packages/cli/src/runner.ts
7
3
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
8
- import { CliError } from "@rig/runtime/control-plane/errors";
4
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
9
5
  import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
10
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
11
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
12
6
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
13
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
7
+
8
+ class CliError extends RuntimeCliError {
9
+ hint;
10
+ constructor(message, exitCode = 1, options = {}) {
11
+ super(message, exitCode);
12
+ if (options.hint?.trim()) {
13
+ this.hint = options.hint.trim();
14
+ }
15
+ }
16
+ }
14
17
  function takeOption(args, option) {
15
18
  const rest = [];
16
19
  let value;
@@ -19,7 +22,7 @@ function takeOption(args, option) {
19
22
  if (current === option) {
20
23
  const next = args[index + 1];
21
24
  if (!next || next.startsWith("-")) {
22
- throw new CliError(`Missing value for ${option}`);
25
+ throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
23
26
  }
24
27
  value = next;
25
28
  index += 1;
@@ -38,12 +41,616 @@ Usage: ${usage}`);
38
41
  }
39
42
  }
40
43
 
44
+ // packages/cli/src/commands/_cli-format.ts
45
+ import { log, note } from "@clack/prompts";
46
+ import pc from "picocolors";
47
+ function stringField(record, key, fallback = "") {
48
+ const value = record[key];
49
+ return typeof value === "string" && value.trim() ? value.trim() : fallback;
50
+ }
51
+ function statusColor(status) {
52
+ const normalized = status.toLowerCase();
53
+ if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved"].includes(normalized))
54
+ return pc.green;
55
+ if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
56
+ return pc.red;
57
+ if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
58
+ return pc.cyan;
59
+ if (["ready", "open", "queued", "created", "preparing", "local", "pending"].includes(normalized))
60
+ return pc.yellow;
61
+ return pc.dim;
62
+ }
63
+ function firstString(record, keys, fallback = "") {
64
+ for (const key of keys) {
65
+ const value = stringField(record, key);
66
+ if (value)
67
+ return value;
68
+ }
69
+ return fallback;
70
+ }
71
+ function requestIdOf(entry) {
72
+ return firstString(entry, ["requestId", "id", "approvalId", "inputId"], "(unknown-request)");
73
+ }
74
+ function shouldUseClackOutput() {
75
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
76
+ }
77
+ function printFormattedOutput(message, options = {}) {
78
+ if (!shouldUseClackOutput()) {
79
+ console.log(message);
80
+ return;
81
+ }
82
+ if (options.title)
83
+ note(message, options.title);
84
+ else
85
+ log.message(message);
86
+ }
87
+ function formatStatusPill(status) {
88
+ const label = status || "unknown";
89
+ return statusColor(label)(`\u25CF ${label}`);
90
+ }
91
+ function formatSection(title, subtitle) {
92
+ return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
93
+ }
94
+ function formatNextSteps(steps) {
95
+ if (steps.length === 0)
96
+ return [];
97
+ return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
98
+ }
99
+ function formatInboxList(kind, entries) {
100
+ const title = kind === "approvals" ? "Approval inbox" : "Input inbox";
101
+ if (entries.length === 0) {
102
+ return [
103
+ formatSection(title, "empty"),
104
+ pc.dim(kind === "approvals" ? "No pending approvals." : "No pending user-input requests."),
105
+ "",
106
+ ...formatNextSteps(["Check runs: `rig run status`", "Start work: `rig task run --next`"])
107
+ ].join(`
108
+ `);
109
+ }
110
+ const lines = [formatSection(title, `${entries.length} pending`)];
111
+ for (const entry of entries) {
112
+ const record = entry.record && typeof entry.record === "object" && !Array.isArray(entry.record) ? entry.record : entry;
113
+ const runId = firstString(entry, ["runId"], firstString(record, ["runId"]));
114
+ const taskId = firstString(entry, ["taskId"], firstString(record, ["taskId", "task"]));
115
+ const requestId = requestIdOf(record);
116
+ const status = firstString(record, ["status", "state"], "pending");
117
+ const prompt = firstString(record, ["prompt", "message", "reason", "title", "summary"], kind === "approvals" ? "Approval requested" : "Input requested");
118
+ lines.push(`${pc.dim("\u2502")} ${pc.bold(requestId)} ${formatStatusPill(status)} ${prompt}`);
119
+ lines.push(`${pc.dim("\u2502")} ${pc.dim("run ")} ${runId || "(unknown-run)"}${taskId ? pc.dim(` task ${taskId}`) : ""}`);
120
+ }
121
+ lines.push("", ...formatNextSteps(kind === "approvals" ? ["Resolve: `rig inbox approve --run <run-id> --request <request-id> --decision approve|reject`", "Rejoin: `rig run attach <run-id> --follow`"] : ["Respond: `rig inbox respond --run <run-id> --request <request-id> --answer key=value`", "Rejoin: `rig run attach <run-id> --follow`"]));
122
+ return lines.join(`
123
+ `);
124
+ }
125
+
126
+ // packages/cli/src/commands/_server-client.ts
127
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
128
+ import { resolve as resolve2 } from "path";
129
+ import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
130
+
131
+ // packages/cli/src/commands/_connection-state.ts
132
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
133
+ import { homedir } from "os";
134
+ import { dirname, resolve } from "path";
135
+ function resolveGlobalConnectionsPath(env = process.env) {
136
+ const explicit = env.RIG_CONNECTIONS_FILE?.trim();
137
+ if (explicit)
138
+ return resolve(explicit);
139
+ const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
140
+ if (stateDir)
141
+ return resolve(stateDir, "connections.json");
142
+ return resolve(homedir(), ".rig", "connections.json");
143
+ }
144
+ function resolveRepoConnectionPath(projectRoot) {
145
+ return resolve(projectRoot, ".rig", "state", "connection.json");
146
+ }
147
+ function readJsonFile(path) {
148
+ if (!existsSync(path))
149
+ return null;
150
+ try {
151
+ return JSON.parse(readFileSync(path, "utf8"));
152
+ } catch (error) {
153
+ throw new CliError(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1, { hint: "Fix or delete that file, then re-select a server with `rig server use <alias|local>`." });
154
+ }
155
+ }
156
+ function writeJsonFile(path, value) {
157
+ mkdirSync(dirname(path), { recursive: true });
158
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
159
+ `, "utf8");
160
+ }
161
+ function normalizeConnection(value) {
162
+ if (!value || typeof value !== "object" || Array.isArray(value))
163
+ return null;
164
+ const record = value;
165
+ if (record.kind === "local")
166
+ return { kind: "local", mode: "auto" };
167
+ if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
168
+ const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
169
+ return { kind: "remote", baseUrl };
170
+ }
171
+ return null;
172
+ }
173
+ function readGlobalConnections(options = {}) {
174
+ const path = resolveGlobalConnectionsPath(options.env ?? process.env);
175
+ const payload = readJsonFile(path);
176
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
177
+ return { connections: {} };
178
+ }
179
+ const rawConnections = payload.connections;
180
+ const connections = {};
181
+ if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
182
+ for (const [alias, raw] of Object.entries(rawConnections)) {
183
+ const connection = normalizeConnection(raw);
184
+ if (connection)
185
+ connections[alias] = connection;
186
+ }
187
+ }
188
+ return { connections };
189
+ }
190
+ function readRepoConnection(projectRoot) {
191
+ const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
192
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
193
+ return null;
194
+ const record = payload;
195
+ const selected = typeof record.selected === "string" ? record.selected.trim() : "";
196
+ if (!selected)
197
+ return null;
198
+ return {
199
+ selected,
200
+ project: typeof record.project === "string" ? record.project : undefined,
201
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
202
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
203
+ };
204
+ }
205
+ function writeRepoConnection(projectRoot, state) {
206
+ writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
207
+ }
208
+ function resolveSelectedConnection(projectRoot, options = {}) {
209
+ const repo = readRepoConnection(projectRoot);
210
+ if (!repo)
211
+ return null;
212
+ if (repo.selected === "local")
213
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
214
+ const global = readGlobalConnections(options);
215
+ const connection = global.connections[repo.selected];
216
+ if (!connection) {
217
+ throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
218
+ }
219
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
220
+ }
221
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
222
+ const repo = readRepoConnection(projectRoot);
223
+ if (!repo)
224
+ return;
225
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
226
+ }
227
+
228
+ // packages/cli/src/commands/_server-client.ts
229
+ var scopedGitHubBearerTokens = new Map;
230
+ var serverPhaseListener = null;
231
+ function setServerPhaseListener(listener) {
232
+ const previous = serverPhaseListener;
233
+ serverPhaseListener = listener;
234
+ return previous;
235
+ }
236
+ function reportServerPhase(label) {
237
+ serverPhaseListener?.(label);
238
+ }
239
+ function cleanToken(value) {
240
+ const trimmed = value?.trim();
241
+ return trimmed ? trimmed : null;
242
+ }
243
+ function readPrivateRemoteSessionToken(projectRoot) {
244
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
245
+ if (!existsSync2(path))
246
+ return null;
247
+ try {
248
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
249
+ return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
250
+ } catch {
251
+ return null;
252
+ }
253
+ }
254
+ function readGitHubBearerTokenForRemote(projectRoot) {
255
+ const scopedKey = resolve2(projectRoot);
256
+ if (scopedGitHubBearerTokens.has(scopedKey))
257
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
258
+ const privateSession = readPrivateRemoteSessionToken(projectRoot);
259
+ if (privateSession)
260
+ return privateSession;
261
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
262
+ }
263
+ function readStoredGitHubAuthToken(projectRoot) {
264
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
265
+ if (!existsSync2(path))
266
+ return null;
267
+ try {
268
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
269
+ return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
270
+ } catch {
271
+ return null;
272
+ }
273
+ }
274
+ function readLocalConnectionFallbackToken(projectRoot) {
275
+ return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
276
+ }
277
+ async function ensureServerForCli(projectRoot) {
278
+ try {
279
+ const selected = resolveSelectedConnection(projectRoot);
280
+ if (selected?.connection.kind === "remote") {
281
+ reportServerPhase(`Connecting to ${selected.alias}\u2026`);
282
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
283
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
284
+ return {
285
+ baseUrl: selected.connection.baseUrl,
286
+ authToken,
287
+ connectionKind: "remote",
288
+ serverProjectRoot
289
+ };
290
+ }
291
+ reportServerPhase("Starting local Rig server\u2026");
292
+ const connection = await ensureLocalRigServerConnection(projectRoot);
293
+ return {
294
+ baseUrl: connection.baseUrl,
295
+ authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
296
+ connectionKind: "local",
297
+ serverProjectRoot: resolve2(projectRoot)
298
+ };
299
+ } catch (error) {
300
+ if (error instanceof Error) {
301
+ throw new CliError(error.message, 1);
302
+ }
303
+ throw error;
304
+ }
305
+ }
306
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
307
+ const repo = readRepoConnection(projectRoot);
308
+ const slug = repo?.project?.trim();
309
+ if (!slug)
310
+ return null;
311
+ try {
312
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
313
+ headers: mergeHeaders(undefined, authToken)
314
+ });
315
+ if (!response.ok)
316
+ return null;
317
+ const payload = await response.json();
318
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
319
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
320
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
321
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
322
+ if (path)
323
+ writeRepoServerProjectRoot(projectRoot, path);
324
+ return path;
325
+ } catch {
326
+ return null;
327
+ }
328
+ }
329
+ function mergeHeaders(headers, authToken) {
330
+ const merged = new Headers(headers);
331
+ if (authToken) {
332
+ merged.set("authorization", `Bearer ${authToken}`);
333
+ }
334
+ return merged;
335
+ }
336
+ function diagnosticMessage(payload) {
337
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
338
+ return null;
339
+ const record = payload;
340
+ const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
341
+ const messages = diagnostics.flatMap((entry) => {
342
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
343
+ return [];
344
+ const diagnostic = entry;
345
+ const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
346
+ const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
347
+ return message ? [`${kind}: ${message}`] : [];
348
+ });
349
+ return messages.length > 0 ? messages.join("; ") : null;
350
+ }
351
+ var serverReachabilityCache = new Map;
352
+ async function probeServerReachability(baseUrl, authToken) {
353
+ try {
354
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
355
+ headers: mergeHeaders(undefined, authToken),
356
+ signal: AbortSignal.timeout(1500)
357
+ });
358
+ return response.ok;
359
+ } catch {
360
+ return false;
361
+ }
362
+ }
363
+ function cachedServerReachability(projectRoot, baseUrl, authToken) {
364
+ const key = resolve2(projectRoot);
365
+ const cached = serverReachabilityCache.get(key);
366
+ if (cached)
367
+ return cached;
368
+ const probe = probeServerReachability(baseUrl, authToken);
369
+ serverReachabilityCache.set(key, probe);
370
+ return probe;
371
+ }
372
+ function describeSelectedServer(projectRoot, server) {
373
+ try {
374
+ const selected = resolveSelectedConnection(projectRoot);
375
+ if (selected) {
376
+ return {
377
+ alias: selected.alias,
378
+ target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
379
+ };
380
+ }
381
+ } catch {}
382
+ return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
383
+ }
384
+ async function buildServerFailureContext(projectRoot, server) {
385
+ const { alias, target } = describeSelectedServer(projectRoot, server);
386
+ const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
387
+ const reachability = reachable ? "server is reachable" : "server is unreachable";
388
+ return {
389
+ contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
390
+ hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
391
+ };
392
+ }
393
+ async function requestServerJson(context, pathname, init = {}) {
394
+ const server = await ensureServerForCli(context.projectRoot);
395
+ const headers = mergeHeaders(init.headers, server.authToken);
396
+ if (server.serverProjectRoot)
397
+ headers.set("x-rig-project-root", server.serverProjectRoot);
398
+ reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
399
+ let response;
400
+ try {
401
+ response = await fetch(`${server.baseUrl}${pathname}`, {
402
+ ...init,
403
+ headers
404
+ });
405
+ } catch (error) {
406
+ const failure = await buildServerFailureContext(context.projectRoot, server);
407
+ throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
408
+ ${failure.contextLine}`, 1, { hint: failure.hint });
409
+ }
410
+ const text = await response.text();
411
+ const payload = text.trim().length > 0 ? (() => {
412
+ try {
413
+ return JSON.parse(text);
414
+ } catch {
415
+ return null;
416
+ }
417
+ })() : null;
418
+ if (!response.ok) {
419
+ const diagnostics = diagnosticMessage(payload);
420
+ const detail = diagnostics ?? (text || response.statusText);
421
+ const failure = await buildServerFailureContext(context.projectRoot, server);
422
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
423
+ ${failure.contextLine}`, 1, { hint: failure.hint });
424
+ }
425
+ return payload;
426
+ }
427
+ var RESUMABLE_RUN_STATUSES = new Set([
428
+ "created",
429
+ "preparing",
430
+ "running",
431
+ "validating",
432
+ "reviewing",
433
+ "stopped",
434
+ "failed",
435
+ "needs-attention",
436
+ "needs_attention"
437
+ ]);
438
+
439
+ // packages/cli/src/commands/_async-ui.ts
440
+ import pc2 from "picocolors";
441
+
442
+ // packages/cli/src/commands/_spinner.ts
443
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
444
+ function createTtySpinner(input) {
445
+ const output = input.output ?? process.stdout;
446
+ const isTty = output.isTTY === true;
447
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
448
+ let label = input.label;
449
+ let frame = 0;
450
+ let paused = false;
451
+ let stopped = false;
452
+ let lastPrintedLabel = "";
453
+ const render = () => {
454
+ if (stopped || paused)
455
+ return;
456
+ if (!isTty) {
457
+ if (label !== lastPrintedLabel) {
458
+ output.write(`${label}
459
+ `);
460
+ lastPrintedLabel = label;
461
+ }
462
+ return;
463
+ }
464
+ frame = (frame + 1) % frames.length;
465
+ const glyph = frames[frame] ?? frames[0] ?? "";
466
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
467
+ };
468
+ const clearLine = () => {
469
+ if (isTty)
470
+ output.write("\r\x1B[2K");
471
+ };
472
+ render();
473
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
474
+ return {
475
+ setLabel(next) {
476
+ label = next;
477
+ render();
478
+ },
479
+ pause() {
480
+ paused = true;
481
+ clearLine();
482
+ },
483
+ resume() {
484
+ if (stopped)
485
+ return;
486
+ paused = false;
487
+ render();
488
+ },
489
+ stop(finalLine) {
490
+ if (stopped)
491
+ return;
492
+ stopped = true;
493
+ if (timer)
494
+ clearInterval(timer);
495
+ clearLine();
496
+ if (finalLine)
497
+ output.write(`${finalLine}
498
+ `);
499
+ }
500
+ };
501
+ }
502
+
503
+ // packages/cli/src/commands/_async-ui.ts
504
+ var CLACK_SPINNER_FRAMES = ["\u25D2", "\u25D0", "\u25D3", "\u25D1"];
505
+ var DONE_SYMBOL = pc2.green("\u25C7");
506
+ var FAIL_SYMBOL = pc2.red("\u25A0");
507
+ var activeUpdate = null;
508
+ async function withSpinner(label, work, options = {}) {
509
+ if (options.outputMode === "json") {
510
+ return work(() => {});
511
+ }
512
+ if (activeUpdate) {
513
+ const outer = activeUpdate;
514
+ outer(label);
515
+ return work(outer);
516
+ }
517
+ const output = options.output ?? process.stderr;
518
+ const isTty = output.isTTY === true;
519
+ let lastLabel = label;
520
+ if (!isTty) {
521
+ output.write(`${label}
522
+ `);
523
+ const update2 = (next) => {
524
+ lastLabel = next;
525
+ };
526
+ activeUpdate = update2;
527
+ const previousListener2 = setServerPhaseListener(update2);
528
+ try {
529
+ return await work(update2);
530
+ } finally {
531
+ activeUpdate = null;
532
+ setServerPhaseListener(previousListener2);
533
+ }
534
+ }
535
+ const spinner = createTtySpinner({
536
+ label,
537
+ output,
538
+ frames: CLACK_SPINNER_FRAMES,
539
+ styleFrame: (frame) => pc2.magenta(frame)
540
+ });
541
+ const update = (next) => {
542
+ lastLabel = next;
543
+ spinner.setLabel(next);
544
+ };
545
+ activeUpdate = update;
546
+ const previousListener = setServerPhaseListener(update);
547
+ try {
548
+ const result = await work(update);
549
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
550
+ return result;
551
+ } catch (error) {
552
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
553
+ throw error;
554
+ } finally {
555
+ activeUpdate = null;
556
+ setServerPhaseListener(previousListener);
557
+ }
558
+ }
559
+
41
560
  // packages/cli/src/commands/inbox.ts
42
- import {
43
- listAuthorityRuns,
44
- readJsonlFile,
45
- resolveAuthorityRunDir
46
- } from "@rig/runtime/control-plane/authority-files";
561
+ async function listInboxRecords(context, kind, filters) {
562
+ const params = new URLSearchParams;
563
+ if (filters.run)
564
+ params.set("runId", filters.run);
565
+ if (filters.task)
566
+ params.set("taskId", filters.task);
567
+ const query = params.size > 0 ? `?${params.toString()}` : "";
568
+ const payload = await requestServerJson(context, `/api/inbox/${kind}${query}`);
569
+ const records = Array.isArray(payload) ? payload : [];
570
+ return filters.pendingOnly ? records.filter((entry) => (entry.status ?? "pending") !== "resolved") : records;
571
+ }
572
+ async function readPendingInboxCounts(context) {
573
+ try {
574
+ const [approvals, inputs] = await Promise.all([
575
+ listInboxRecords(context, "approvals", { pendingOnly: true }),
576
+ listInboxRecords(context, "inputs", { pendingOnly: true })
577
+ ]);
578
+ return { approvals: approvals.length, inputs: inputs.length };
579
+ } catch {
580
+ return null;
581
+ }
582
+ }
583
+ async function printPendingInboxFooter(context) {
584
+ if (context.outputMode !== "text")
585
+ return;
586
+ const counts = await readPendingInboxCounts(context);
587
+ if (!counts || counts.approvals === 0 && counts.inputs === 0)
588
+ return;
589
+ const parts = [];
590
+ if (counts.approvals > 0)
591
+ parts.push(`${counts.approvals} approval${counts.approvals === 1 ? "" : "s"}`);
592
+ if (counts.inputs > 0)
593
+ parts.push(`${counts.inputs} input request${counts.inputs === 1 ? "" : "s"}`);
594
+ console.log(`
595
+ \u26A0 ${parts.join(" and ")} pending \u2014 run \`rig inbox\` to review.`);
596
+ }
597
+ function renderList(context, kind, records) {
598
+ if (context.outputMode === "text") {
599
+ printFormattedOutput(formatInboxList(kind, records));
600
+ }
601
+ }
602
+ async function watchInbox(context, filters) {
603
+ const render = async () => {
604
+ const [approvals, inputs] = await Promise.all([
605
+ listInboxRecords(context, "approvals", { ...filters, pendingOnly: true }),
606
+ listInboxRecords(context, "inputs", { ...filters, pendingOnly: true })
607
+ ]);
608
+ console.clear();
609
+ console.log(`rig inbox \u2014 watching (Ctrl-C to stop) \u2014 ${new Date().toLocaleTimeString()}`);
610
+ renderList(context, "approvals", approvals);
611
+ renderList(context, "inputs", inputs);
612
+ if (approvals.length === 0 && inputs.length === 0) {
613
+ console.log("Nothing pending.");
614
+ } else {
615
+ console.log(`
616
+ Resolve with: rig inbox approve --run <id> --request <id> --decision approve|reject`);
617
+ }
618
+ };
619
+ await render();
620
+ const server = await ensureServerForCli(context.projectRoot);
621
+ const relevant = /"type":"rig\.(approval|user-input)\./;
622
+ const fallbackTimer = setInterval(() => {
623
+ render();
624
+ }, 30000);
625
+ fallbackTimer.unref?.();
626
+ for (;; ) {
627
+ try {
628
+ const response = await fetch(`${server.baseUrl}/api/server/events`, {
629
+ headers: {
630
+ ...server.authToken ? { authorization: `Bearer ${server.authToken}` } : {},
631
+ ...server.serverProjectRoot ? { "x-rig-project-root": server.serverProjectRoot } : {},
632
+ accept: "text/event-stream"
633
+ }
634
+ });
635
+ if (!response.ok || !response.body)
636
+ throw new Error(`SSE ${response.status}`);
637
+ const reader = response.body.getReader();
638
+ const decoder = new TextDecoder;
639
+ for (;; ) {
640
+ const { done, value } = await reader.read();
641
+ if (done)
642
+ break;
643
+ const chunk = decoder.decode(value, { stream: true });
644
+ if (relevant.test(chunk)) {
645
+ await render();
646
+ }
647
+ }
648
+ } catch {
649
+ await render();
650
+ await new Promise((resolveSleep) => setTimeout(resolveSleep, 2000));
651
+ }
652
+ }
653
+ }
47
654
  async function executeInbox(context, args) {
48
655
  const [command = "approvals", ...rest] = args;
49
656
  switch (command) {
@@ -53,19 +660,22 @@ async function executeInbox(context, args) {
53
660
  pending = run.rest;
54
661
  const task = takeOption(pending, "--task");
55
662
  pending = task.rest;
56
- requireNoExtraArgs(pending, "bun run rig inbox approvals [--run <id>] [--task <id>]");
57
- const runs = listAuthorityRuns(context.projectRoot).filter((entry) => (!run.value || entry.runId === run.value) && (!task.value || entry.taskId === task.value));
58
- const approvals = runs.flatMap((entry) => readJsonlFile(resolve(resolveAuthorityRunDir(context.projectRoot, entry.runId), "approvals.jsonl")).map((record) => ({
59
- runId: entry.runId,
60
- record
61
- })));
62
- if (context.outputMode === "text") {
63
- for (const approval of approvals) {
64
- console.log(JSON.stringify(approval));
65
- }
66
- }
663
+ requireNoExtraArgs(pending, "rig inbox approvals [--run <id>] [--task <id>]");
664
+ const approvals = await withSpinner("Reading approvals from server\u2026", () => listInboxRecords(context, "approvals", { run: run.value, task: task.value }), { outputMode: context.outputMode });
665
+ renderList(context, "approvals", approvals);
67
666
  return { ok: true, group: "inbox", command, details: { approvals } };
68
667
  }
668
+ case "inputs": {
669
+ let pending = rest;
670
+ const run = takeOption(pending, "--run");
671
+ pending = run.rest;
672
+ const task = takeOption(pending, "--task");
673
+ pending = task.rest;
674
+ requireNoExtraArgs(pending, "rig inbox inputs [--run <id>] [--task <id>]");
675
+ const requests = await withSpinner("Reading input requests from server\u2026", () => listInboxRecords(context, "inputs", { run: run.value, task: task.value }), { outputMode: context.outputMode });
676
+ renderList(context, "inputs", requests);
677
+ return { ok: true, group: "inbox", command, details: { requests } };
678
+ }
69
679
  case "approve": {
70
680
  let pending = rest;
71
681
  const run = takeOption(pending, "--run");
@@ -74,42 +684,26 @@ async function executeInbox(context, args) {
74
684
  pending = request.rest;
75
685
  const decision = takeOption(pending, "--decision");
76
686
  pending = decision.rest;
77
- const note = takeOption(pending, "--note");
78
- pending = note.rest;
79
- requireNoExtraArgs(pending, "bun run rig inbox approve --run <id> --request <id> --decision approve|reject [--note <text>]");
687
+ const note2 = takeOption(pending, "--note");
688
+ pending = note2.rest;
689
+ requireNoExtraArgs(pending, "rig inbox approve --run <id> --request <id> --decision approve|reject [--note <text>]");
80
690
  if (!run.value || !request.value || !decision.value) {
81
- throw new CliError2("approve requires --run, --request, and --decision.");
691
+ throw new CliError("approve requires --run, --request, and --decision. List pending requests with `rig inbox approvals`.");
82
692
  }
83
693
  if (decision.value !== "approve" && decision.value !== "reject") {
84
- throw new CliError2("decision must be approve or reject.");
85
- }
86
- const approvalsPath = resolve(resolveAuthorityRunDir(context.projectRoot, run.value), "approvals.jsonl");
87
- const approvals = readJsonlFile(approvalsPath);
88
- const resolvedAt = new Date().toISOString();
89
- const next = approvals.map((entry) => entry.requestId === request.value || entry.id === request.value ? { ...entry, status: "resolved", decision: decision.value, note: note.value ?? null, resolvedAt } : entry);
90
- writeFileSync(approvalsPath, `${next.map((entry) => JSON.stringify(entry)).join(`
91
- `)}
92
- `, "utf8");
93
- return { ok: true, group: "inbox", command, details: { runId: run.value, requestId: request.value, decision: decision.value } };
94
- }
95
- case "inputs": {
96
- let pending = rest;
97
- const run = takeOption(pending, "--run");
98
- pending = run.rest;
99
- const task = takeOption(pending, "--task");
100
- pending = task.rest;
101
- requireNoExtraArgs(pending, "bun run rig inbox inputs [--run <id>] [--task <id>]");
102
- const runs = listAuthorityRuns(context.projectRoot).filter((entry) => (!run.value || entry.runId === run.value) && (!task.value || entry.taskId === task.value));
103
- const requests = runs.flatMap((entry) => readJsonlFile(resolve(resolveAuthorityRunDir(context.projectRoot, entry.runId), "user-input.jsonl")).map((record) => ({
104
- runId: entry.runId,
105
- record
106
- })));
107
- if (context.outputMode === "text") {
108
- for (const request of requests) {
109
- console.log(JSON.stringify(request));
110
- }
694
+ throw new CliError("decision must be approve or reject.", 1, { hint: "Re-run as `rig inbox approve --run <id> --request <id> --decision approve|reject`." });
111
695
  }
112
- return { ok: true, group: "inbox", command, details: { requests } };
696
+ const result = await withSpinner(`Resolving approval ${request.value}\u2026`, () => requestServerJson(context, "/api/inbox/approvals/resolve", {
697
+ method: "POST",
698
+ headers: { "content-type": "application/json" },
699
+ body: JSON.stringify({
700
+ runId: run.value,
701
+ requestId: request.value,
702
+ decision: decision.value,
703
+ note: note2.value ?? null
704
+ })
705
+ }), { outputMode: context.outputMode });
706
+ return { ok: true, group: "inbox", command, details: { result } };
113
707
  }
114
708
  case "respond": {
115
709
  let pending = rest;
@@ -122,11 +716,11 @@ async function executeInbox(context, args) {
122
716
  for (let index = 0;index < pending.length; index += 1) {
123
717
  const current = pending[index];
124
718
  if (current === "--answer") {
125
- const next2 = pending[index + 1];
126
- if (!next2 || next2.startsWith("-")) {
127
- throw new CliError2("Missing value for --answer");
719
+ const next = pending[index + 1];
720
+ if (!next || next.startsWith("-")) {
721
+ throw new CliError("Missing value for --answer", 1, { hint: "Pass key=value pairs, e.g. `rig inbox respond --run <id> --request <id> --answer key=value`." });
128
722
  }
129
- answers.push(next2);
723
+ answers.push(next);
130
724
  index += 1;
131
725
  continue;
132
726
  }
@@ -134,27 +728,40 @@ async function executeInbox(context, args) {
134
728
  remaining.push(current);
135
729
  }
136
730
  }
137
- requireNoExtraArgs(remaining, "bun run rig inbox respond --run <id> --request <id> --answer key=value [--answer key=value]");
731
+ requireNoExtraArgs(remaining, "rig inbox respond --run <id> --request <id> --answer key=value [--answer key=value]");
138
732
  if (!run.value || !request.value || answers.length === 0) {
139
- throw new CliError2("respond requires --run, --request, and at least one --answer.");
733
+ throw new CliError("respond requires --run, --request, and at least one --answer. List pending requests with `rig inbox inputs`.");
140
734
  }
141
735
  const parsedAnswers = Object.fromEntries(answers.map((entry) => {
142
736
  const [key, ...restValue] = entry.split("=");
143
737
  return [key, restValue.join("=")];
144
738
  }));
145
- const requestsPath = resolve(resolveAuthorityRunDir(context.projectRoot, run.value), "user-input.jsonl");
146
- const requests = readJsonlFile(requestsPath);
147
- const resolvedAt = new Date().toISOString();
148
- const next = requests.map((entry) => entry.requestId === request.value || entry.id === request.value ? { ...entry, status: "resolved", answers: parsedAnswers, respondedAt: resolvedAt, resolvedAt } : entry);
149
- writeFileSync(requestsPath, `${next.map((entry) => JSON.stringify(entry)).join(`
150
- `)}
151
- `, "utf8");
152
- return { ok: true, group: "inbox", command, details: { runId: run.value, requestId: request.value, answers: parsedAnswers } };
739
+ const result = await withSpinner(`Sending response for ${request.value}\u2026`, () => requestServerJson(context, "/api/inbox/inputs/respond", {
740
+ method: "POST",
741
+ headers: { "content-type": "application/json" },
742
+ body: JSON.stringify({
743
+ runId: run.value,
744
+ requestId: request.value,
745
+ answers: parsedAnswers
746
+ })
747
+ }), { outputMode: context.outputMode });
748
+ return { ok: true, group: "inbox", command, details: { result } };
749
+ }
750
+ case "watch": {
751
+ let pending = rest;
752
+ const run = takeOption(pending, "--run");
753
+ pending = run.rest;
754
+ const task = takeOption(pending, "--task");
755
+ pending = task.rest;
756
+ requireNoExtraArgs(pending, "rig inbox watch [--run <id>] [--task <id>]");
757
+ return await watchInbox(context, { run: run.value, task: task.value });
153
758
  }
154
759
  default:
155
- throw new CliError2(`Unknown inbox command: ${command}`);
760
+ throw new CliError(`Unknown inbox command: ${command}. Use approvals|inputs|approve|respond|watch.`);
156
761
  }
157
762
  }
158
763
  export {
764
+ readPendingInboxCounts,
765
+ printPendingInboxFooter,
159
766
  executeInbox
160
767
  };