@h-rig/cli 0.0.6-alpha.9 → 0.0.6-alpha.90

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 (114) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/build-rig-binaries.d.ts +2 -0
  3. package/dist/bin/rig.d.ts +2 -0
  4. package/dist/bin/rig.js +11052 -6668
  5. package/dist/src/app/board.d.ts +23 -0
  6. package/dist/src/app/board.js +1786 -0
  7. package/dist/src/app/drone-ui.d.ts +37 -0
  8. package/dist/src/app/drone-ui.js +294 -0
  9. package/dist/src/app/theme.d.ts +47 -0
  10. package/dist/src/app/theme.js +150 -0
  11. package/dist/src/commands/_async-ui.d.ts +13 -0
  12. package/dist/src/commands/_async-ui.js +223 -0
  13. package/dist/src/commands/_authority-runs.d.ts +22 -0
  14. package/dist/src/commands/_authority-runs.js +2 -3
  15. package/dist/src/commands/_cli-format.d.ts +49 -0
  16. package/dist/src/commands/_cli-format.js +447 -0
  17. package/dist/src/commands/_connection-state.d.ts +44 -0
  18. package/dist/src/commands/_connection-state.js +30 -11
  19. package/dist/src/commands/_doctor-checks.d.ts +52 -0
  20. package/dist/src/commands/_doctor-checks.js +180 -44
  21. package/dist/src/commands/_help-catalog.d.ts +51 -0
  22. package/dist/src/commands/_help-catalog.js +442 -0
  23. package/dist/src/commands/_json-output.d.ts +11 -0
  24. package/dist/src/commands/_json-output.js +56 -0
  25. package/dist/src/commands/_operator-surface.d.ts +34 -0
  26. package/dist/src/commands/_operator-surface.js +220 -0
  27. package/dist/src/commands/_operator-view.d.ts +30 -0
  28. package/dist/src/commands/_operator-view.js +803 -73
  29. package/dist/src/commands/_parsers.d.ts +15 -0
  30. package/dist/src/commands/_parsers.js +18 -11
  31. package/dist/src/commands/_paths.d.ts +11 -0
  32. package/dist/src/commands/_pi-frontend.d.ts +27 -0
  33. package/dist/src/commands/_pi-frontend.js +742 -0
  34. package/dist/src/commands/_pi-install.d.ts +42 -0
  35. package/dist/src/commands/_pi-install.js +5 -4
  36. package/dist/src/commands/_policy.d.ts +8 -0
  37. package/dist/src/commands/_policy.js +12 -5
  38. package/dist/src/commands/_preflight.d.ts +22 -0
  39. package/dist/src/commands/_preflight.js +190 -128
  40. package/dist/src/commands/_probes.d.ts +1 -0
  41. package/dist/src/commands/_run-driver-helpers.d.ts +99 -0
  42. package/dist/src/commands/_run-driver-helpers.js +75 -22
  43. package/dist/src/commands/_run-replay.d.ts +24 -0
  44. package/dist/src/commands/_run-replay.js +142 -0
  45. package/dist/src/commands/_server-client.d.ts +186 -0
  46. package/dist/src/commands/_server-client.js +360 -61
  47. package/dist/src/commands/_snapshot-upload.d.ts +39 -0
  48. package/dist/src/commands/_snapshot-upload.js +163 -39
  49. package/dist/src/commands/_spinner.d.ts +25 -0
  50. package/dist/src/commands/_spinner.js +65 -0
  51. package/dist/src/commands/_task-picker.d.ts +9 -0
  52. package/dist/src/commands/_task-picker.js +172 -19
  53. package/dist/src/commands/agent.d.ts +3 -0
  54. package/dist/src/commands/agent.js +39 -20
  55. package/dist/src/commands/browser.d.ts +65 -0
  56. package/dist/src/commands/browser.js +334 -51
  57. package/dist/src/commands/connect.d.ts +7 -0
  58. package/dist/src/commands/connect.js +272 -33
  59. package/dist/src/commands/dist.d.ts +28 -0
  60. package/dist/src/commands/dist.js +19 -12
  61. package/dist/src/commands/doctor.d.ts +3 -0
  62. package/dist/src/commands/doctor.js +378 -45
  63. package/dist/src/commands/github.d.ts +3 -0
  64. package/dist/src/commands/github.js +375 -53
  65. package/dist/src/commands/inbox.d.ts +30 -0
  66. package/dist/src/commands/inbox.js +760 -70
  67. package/dist/src/commands/init.d.ts +74 -0
  68. package/dist/src/commands/init.js +963 -119
  69. package/dist/src/commands/inspect.d.ts +3 -0
  70. package/dist/src/commands/inspect.js +588 -32
  71. package/dist/src/commands/inspector.d.ts +3 -0
  72. package/dist/src/commands/inspector.js +20 -13
  73. package/dist/src/commands/pi.d.ts +3 -0
  74. package/dist/src/commands/pi.js +177 -0
  75. package/dist/src/commands/plugin.d.ts +16 -0
  76. package/dist/src/commands/plugin.js +95 -27
  77. package/dist/src/commands/profile-and-review.d.ts +4 -0
  78. package/dist/src/commands/profile-and-review.js +26 -19
  79. package/dist/src/commands/queue.d.ts +3 -0
  80. package/dist/src/commands/queue.js +32 -12
  81. package/dist/src/commands/remote.d.ts +3 -0
  82. package/dist/src/commands/remote.js +43 -36
  83. package/dist/src/commands/repo-git-harness.d.ts +5 -0
  84. package/dist/src/commands/repo-git-harness.js +22 -15
  85. package/dist/src/commands/run.d.ts +3 -0
  86. package/dist/src/commands/run.js +1379 -159
  87. package/dist/src/commands/server.d.ts +7 -0
  88. package/dist/src/commands/server.js +502 -57
  89. package/dist/src/commands/setup.d.ts +16 -0
  90. package/dist/src/commands/setup.js +390 -63
  91. package/dist/src/commands/stats.d.ts +12 -0
  92. package/dist/src/commands/stats.js +1051 -0
  93. package/dist/src/commands/task-report-bug.d.ts +19 -0
  94. package/dist/src/commands/task-report-bug.js +260 -62
  95. package/dist/src/commands/task-run-driver.d.ts +132 -0
  96. package/dist/src/commands/task-run-driver.js +886 -130
  97. package/dist/src/commands/task.d.ts +14 -0
  98. package/dist/src/commands/task.js +1644 -314
  99. package/dist/src/commands/test.d.ts +3 -0
  100. package/dist/src/commands/test.js +15 -8
  101. package/dist/src/commands/workspace.d.ts +3 -0
  102. package/dist/src/commands/workspace.js +18 -11
  103. package/dist/src/commands.d.ts +29 -0
  104. package/dist/src/commands.js +10967 -6637
  105. package/dist/src/index.d.ts +4 -0
  106. package/dist/src/index.js +10168 -5787
  107. package/dist/src/launcher.d.ts +61 -0
  108. package/dist/src/launcher.js +77 -13
  109. package/dist/src/report-bug.d.ts +44 -0
  110. package/dist/src/report-bug.js +3 -3
  111. package/dist/src/runner.d.ts +47 -0
  112. package/dist/src/runner.js +16 -22
  113. package/dist/src/withMutedConsole.d.ts +2 -0
  114. package/package.json +13 -6
@@ -1,18 +1,237 @@
1
1
  // @bun
2
2
  // packages/cli/src/commands/task.ts
3
3
  import { readFileSync as readFileSync4 } from "fs";
4
- import { spawnSync as spawnSync2 } from "child_process";
5
- import { createInterface as createInterface3 } from "readline/promises";
6
- import { resolve as resolve4 } from "path";
4
+ import { spawnSync } from "child_process";
5
+ import { resolve as resolve3 } from "path";
6
+
7
+ // packages/cli/src/app/drone-ui.ts
8
+ import { ProcessTerminal, TUI, Text, Input, SelectList, matchesKey } from "@earendil-works/pi-tui";
9
+
10
+ // packages/cli/src/app/theme.ts
11
+ var RIG_PALETTE = {
12
+ ink: "#f2f3f6",
13
+ ink2: "#aeb0ba",
14
+ ink3: "#6c6e79",
15
+ ink4: "#44464f",
16
+ accent: "#ccff4d",
17
+ accentDim: "#a9d63f",
18
+ cyan: "#56d8ff",
19
+ red: "#ff5d5d",
20
+ yellow: "#ffd24d"
21
+ };
22
+ function hexToRgb(hex) {
23
+ const value = hex.replace("#", "");
24
+ return [
25
+ Number.parseInt(value.slice(0, 2), 16),
26
+ Number.parseInt(value.slice(2, 4), 16),
27
+ Number.parseInt(value.slice(4, 6), 16)
28
+ ];
29
+ }
30
+ function fg(hex) {
31
+ const [r, g, b] = hexToRgb(hex);
32
+ return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
33
+ }
34
+ var ink = fg(RIG_PALETTE.ink);
35
+ var ink2 = fg(RIG_PALETTE.ink2);
36
+ var ink3 = fg(RIG_PALETTE.ink3);
37
+ var ink4 = fg(RIG_PALETTE.ink4);
38
+ var accent = fg(RIG_PALETTE.accent);
39
+ var accentDim = fg(RIG_PALETTE.accentDim);
40
+ var cyan = fg(RIG_PALETTE.cyan);
41
+ var red = fg(RIG_PALETTE.red);
42
+ var yellow = fg(RIG_PALETTE.yellow);
43
+ function bold(text) {
44
+ return `\x1B[1m${text}\x1B[22m`;
45
+ }
46
+ var DRONE_ART = [
47
+ " .-=-. .-=-. ",
48
+ " ( !!! ) ( !!! ) ",
49
+ " '-=-'._ _.'-=-' ",
50
+ " '._ _.' ",
51
+ " '=$$$$$$$=.' ",
52
+ " =$$$$$$$$$$$= ",
53
+ " $$$@@@@@@@@@@$$$ ",
54
+ " $$$@@ @@$$$ ",
55
+ " $$@ ? @$$$ ",
56
+ " $$$@ '-' @$$$ ",
57
+ " $$$@@ @@$$$ ",
58
+ " $$$@@@@@@@@@@$$$ ",
59
+ " =$$$$$$$$$$$= ",
60
+ " '=$$$$$$$=.' ",
61
+ " _.' '._ ",
62
+ " .-=-.' '.-=-. ",
63
+ " ( !!! ) ( !!! ) ",
64
+ " '-=-' '-=-' "
65
+ ];
66
+ var EYE_FRAMES = ["@", "o", "."];
67
+ var DRONE_WIDTH = DRONE_ART[0].length;
68
+ var DRONE_HEIGHT = DRONE_ART.length;
69
+ var MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
70
+ function microDroneFrame(tick) {
71
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
72
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
73
+ return `(${blade})${eye}(${blade})`;
74
+ }
75
+ var MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
76
+ function renderMicroDroneFrame(tick) {
77
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
78
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
79
+ return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
80
+ }
81
+
82
+ // packages/cli/src/commands/_spinner.ts
83
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
84
+ function createTtySpinner(input) {
85
+ const output = input.output ?? process.stdout;
86
+ const isTty = output.isTTY === true;
87
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
88
+ let label = input.label;
89
+ let frame = 0;
90
+ let paused = false;
91
+ let stopped = false;
92
+ let lastPrintedLabel = "";
93
+ const render = () => {
94
+ if (stopped || paused)
95
+ return;
96
+ if (!isTty) {
97
+ if (label !== lastPrintedLabel) {
98
+ output.write(`${label}
99
+ `);
100
+ lastPrintedLabel = label;
101
+ }
102
+ return;
103
+ }
104
+ frame = (frame + 1) % frames.length;
105
+ const glyph = frames[frame] ?? frames[0] ?? "";
106
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
107
+ };
108
+ const clearLine = () => {
109
+ if (isTty)
110
+ output.write("\r\x1B[2K");
111
+ };
112
+ render();
113
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
114
+ return {
115
+ setLabel(next) {
116
+ label = next;
117
+ render();
118
+ },
119
+ pause() {
120
+ paused = true;
121
+ clearLine();
122
+ },
123
+ resume() {
124
+ if (stopped)
125
+ return;
126
+ paused = false;
127
+ render();
128
+ },
129
+ stop(finalLine) {
130
+ if (stopped)
131
+ return;
132
+ stopped = true;
133
+ if (timer)
134
+ clearInterval(timer);
135
+ clearLine();
136
+ if (finalLine)
137
+ output.write(`${finalLine}
138
+ `);
139
+ }
140
+ };
141
+ }
142
+
143
+ // packages/cli/src/app/drone-ui.ts
144
+ var isTty = () => Boolean(process.stdout.isTTY);
145
+ function droneNote(message, title) {
146
+ if (title)
147
+ console.log(` ${accentDim("\u25C7")} ${bold(ink2(title))}`);
148
+ for (const line of message.split(`
149
+ `)) {
150
+ console.log(` ${ink4("\u2502")} ${line}`);
151
+ }
152
+ }
153
+ function droneCancel(text) {
154
+ console.log(` ${red("\u2716")} ${ink3(text)}`);
155
+ }
156
+ var SELECT_THEME = {
157
+ selectedPrefix: (text) => accent(text),
158
+ selectedText: (text) => bold(ink(text)),
159
+ description: (text) => ink3(text),
160
+ scrollInfo: (text) => ink4(text),
161
+ noMatch: (text) => ink3(text)
162
+ };
163
+ async function runMiniTui(build) {
164
+ const terminal = new ProcessTerminal;
165
+ const tui = new TUI(terminal);
166
+ let settled = false;
167
+ return await new Promise((resolve) => {
168
+ const finish = (result) => {
169
+ if (settled)
170
+ return;
171
+ settled = true;
172
+ tui.stop();
173
+ resolve(result);
174
+ };
175
+ build(tui, finish);
176
+ tui.start();
177
+ });
178
+ }
179
+ async function droneSelect(input) {
180
+ if (!isTty() || input.options.length === 0) {
181
+ return input.initialValue ?? input.options[0]?.value ?? null;
182
+ }
183
+ return runMiniTui((tui, finish) => {
184
+ tui.addChild(new Text(` ${accent("\u258D")}${bold(ink(input.message))}`));
185
+ const items = input.options.map((option) => ({
186
+ value: option.value,
187
+ label: option.label,
188
+ ...option.hint ? { description: option.hint } : {}
189
+ }));
190
+ const list = new SelectList(items, Math.min(items.length, 12), SELECT_THEME);
191
+ const initialIndex = input.initialValue ? items.findIndex((item) => item.value === input.initialValue) : -1;
192
+ if (initialIndex > 0)
193
+ list.setSelectedIndex(initialIndex);
194
+ list.onSelect = (item) => finish(item.value);
195
+ list.onCancel = () => finish(null);
196
+ tui.addChild(list);
197
+ tui.addChild(new Text(ink4(" \u2191\u2193 navigate \xB7 enter select \xB7 esc cancel")));
198
+ tui.setFocus(list);
199
+ tui.addInputListener((data) => {
200
+ if (matchesKey(data, "ctrl+c") || matchesKey(data, "escape")) {
201
+ finish(null);
202
+ return { consume: true };
203
+ }
204
+ return;
205
+ });
206
+ });
207
+ }
208
+ async function droneConfirm(input) {
209
+ const answer = await droneSelect({
210
+ message: input.message,
211
+ options: [
212
+ { value: "yes", label: "Yes" },
213
+ { value: "no", label: "No" }
214
+ ],
215
+ initialValue: input.initialValue === false ? "no" : "yes"
216
+ });
217
+ return answer === null ? null : answer === "yes";
218
+ }
7
219
 
8
220
  // packages/cli/src/runner.ts
9
221
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
10
- import { CliError } from "@rig/runtime/control-plane/errors";
222
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
11
223
  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
224
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
15
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
225
+
226
+ class CliError extends RuntimeCliError {
227
+ hint;
228
+ constructor(message, exitCode = 1, options = {}) {
229
+ super(message, exitCode);
230
+ if (options.hint?.trim()) {
231
+ this.hint = options.hint.trim();
232
+ }
233
+ }
234
+ }
16
235
  function takeFlag(args, flag) {
17
236
  const rest = [];
18
237
  let value = false;
@@ -33,7 +252,7 @@ function takeOption(args, option) {
33
252
  if (current === option) {
34
253
  const next = args[index + 1];
35
254
  if (!next || next.startsWith("-")) {
36
- throw new CliError(`Missing value for ${option}`);
255
+ throw new CliError(`Missing value for ${option}`, 1, { hint: `Provide a value after ${option}, e.g. \`${option} <value>\`.` });
37
256
  }
38
257
  value = next;
39
258
  index += 1;
@@ -80,8 +299,7 @@ import {
80
299
  import {
81
300
  readAuthorityRun,
82
301
  readJsonlFile,
83
- resolveAuthorityRunDir,
84
- writeJsonFile
302
+ writeAuthorityRunRecord
85
303
  } from "@rig/runtime/control-plane/authority-files";
86
304
 
87
305
  // packages/cli/src/commands/_paths.ts
@@ -127,9 +345,14 @@ function readJsonFile(path) {
127
345
  try {
128
346
  return JSON.parse(readFileSync(path, "utf8"));
129
347
  } catch (error) {
130
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
348
+ 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>`." });
131
349
  }
132
350
  }
351
+ function writeJsonFile(path, value) {
352
+ mkdirSync(dirname(path), { recursive: true });
353
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
354
+ `, "utf8");
355
+ }
133
356
  function normalizeConnection(value) {
134
357
  if (!value || typeof value !== "object" || Array.isArray(value))
135
358
  return null;
@@ -170,29 +393,47 @@ function readRepoConnection(projectRoot) {
170
393
  return {
171
394
  selected,
172
395
  project: typeof record.project === "string" ? record.project : undefined,
173
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
396
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
397
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
174
398
  };
175
399
  }
400
+ function writeRepoConnection(projectRoot, state) {
401
+ writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
402
+ }
176
403
  function resolveSelectedConnection(projectRoot, options = {}) {
177
404
  const repo = readRepoConnection(projectRoot);
178
405
  if (!repo)
179
406
  return null;
180
407
  if (repo.selected === "local")
181
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
408
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
182
409
  const global = readGlobalConnections(options);
183
410
  const connection = global.connections[repo.selected];
184
411
  if (!connection) {
185
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
412
+ throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
186
413
  }
187
- return { alias: repo.selected, connection };
414
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
415
+ }
416
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
417
+ const repo = readRepoConnection(projectRoot);
418
+ if (!repo)
419
+ return;
420
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
188
421
  }
189
422
 
190
423
  // packages/cli/src/commands/_server-client.ts
191
- import { spawnSync } from "child_process";
192
424
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
193
425
  import { resolve as resolve2 } from "path";
194
426
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
195
- var cachedGitHubBearerToken;
427
+ var scopedGitHubBearerTokens = new Map;
428
+ var serverPhaseListener = null;
429
+ function setServerPhaseListener(listener) {
430
+ const previous = serverPhaseListener;
431
+ serverPhaseListener = listener;
432
+ return previous;
433
+ }
434
+ function reportServerPhase(label) {
435
+ serverPhaseListener?.(label);
436
+ }
196
437
  function cleanToken(value) {
197
438
  const trimmed = value?.trim();
198
439
  return trimmed ? trimmed : null;
@@ -209,49 +450,80 @@ function readPrivateRemoteSessionToken(projectRoot) {
209
450
  }
210
451
  }
211
452
  function readGitHubBearerTokenForRemote(projectRoot) {
212
- if (cachedGitHubBearerToken !== undefined)
213
- return cachedGitHubBearerToken;
453
+ const scopedKey = resolve2(projectRoot);
454
+ if (scopedGitHubBearerTokens.has(scopedKey))
455
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
214
456
  const privateSession = readPrivateRemoteSessionToken(projectRoot);
215
- if (privateSession) {
216
- cachedGitHubBearerToken = privateSession;
217
- return cachedGitHubBearerToken;
218
- }
219
- const envToken = cleanToken(process.env.RIG_GITHUB_TOKEN) ?? cleanToken(process.env.GITHUB_TOKEN) ?? cleanToken(process.env.GH_TOKEN);
220
- if (envToken) {
221
- cachedGitHubBearerToken = envToken;
222
- return cachedGitHubBearerToken;
223
- }
224
- const result = spawnSync("gh", ["auth", "token"], {
225
- encoding: "utf8",
226
- timeout: 5000,
227
- stdio: ["ignore", "pipe", "ignore"]
228
- });
229
- cachedGitHubBearerToken = result.status === 0 ? cleanToken(result.stdout) : null;
230
- return cachedGitHubBearerToken;
457
+ if (privateSession)
458
+ return privateSession;
459
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
460
+ }
461
+ function readStoredGitHubAuthToken(projectRoot) {
462
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
463
+ if (!existsSync2(path))
464
+ return null;
465
+ try {
466
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
467
+ return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
468
+ } catch {
469
+ return null;
470
+ }
471
+ }
472
+ function readLocalConnectionFallbackToken(projectRoot) {
473
+ return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
231
474
  }
232
475
  async function ensureServerForCli(projectRoot) {
233
476
  try {
234
477
  const selected = resolveSelectedConnection(projectRoot);
235
478
  if (selected?.connection.kind === "remote") {
479
+ reportServerPhase(`Connecting to ${selected.alias}\u2026`);
480
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
481
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
236
482
  return {
237
483
  baseUrl: selected.connection.baseUrl,
238
- authToken: readGitHubBearerTokenForRemote(projectRoot),
239
- connectionKind: "remote"
484
+ authToken,
485
+ connectionKind: "remote",
486
+ serverProjectRoot
240
487
  };
241
488
  }
489
+ reportServerPhase("Starting local Rig server\u2026");
242
490
  const connection = await ensureLocalRigServerConnection(projectRoot);
243
491
  return {
244
492
  baseUrl: connection.baseUrl,
245
- authToken: connection.authToken,
246
- connectionKind: "local"
493
+ authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
494
+ connectionKind: "local",
495
+ serverProjectRoot: resolve2(projectRoot)
247
496
  };
248
497
  } catch (error) {
249
498
  if (error instanceof Error) {
250
- throw new CliError2(error.message, 1);
499
+ throw new CliError(error.message, 1);
251
500
  }
252
501
  throw error;
253
502
  }
254
503
  }
504
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
505
+ const repo = readRepoConnection(projectRoot);
506
+ const slug = repo?.project?.trim();
507
+ if (!slug)
508
+ return null;
509
+ try {
510
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
511
+ headers: mergeHeaders(undefined, authToken)
512
+ });
513
+ if (!response.ok)
514
+ return null;
515
+ const payload = await response.json();
516
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
517
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
518
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
519
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
520
+ if (path)
521
+ writeRepoServerProjectRoot(projectRoot, path);
522
+ return path;
523
+ } catch {
524
+ return null;
525
+ }
526
+ }
255
527
  function appendTaskFilterParams(url, filters) {
256
528
  if (filters.assignee)
257
529
  url.searchParams.set("assignee", filters.assignee);
@@ -284,12 +556,65 @@ function diagnosticMessage(payload) {
284
556
  });
285
557
  return messages.length > 0 ? messages.join("; ") : null;
286
558
  }
559
+ var serverReachabilityCache = new Map;
560
+ async function probeServerReachability(baseUrl, authToken) {
561
+ try {
562
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
563
+ headers: mergeHeaders(undefined, authToken),
564
+ signal: AbortSignal.timeout(1500)
565
+ });
566
+ return response.ok;
567
+ } catch {
568
+ return false;
569
+ }
570
+ }
571
+ function cachedServerReachability(projectRoot, baseUrl, authToken) {
572
+ const key = resolve2(projectRoot);
573
+ const cached = serverReachabilityCache.get(key);
574
+ if (cached)
575
+ return cached;
576
+ const probe = probeServerReachability(baseUrl, authToken);
577
+ serverReachabilityCache.set(key, probe);
578
+ return probe;
579
+ }
580
+ function describeSelectedServer(projectRoot, server) {
581
+ try {
582
+ const selected = resolveSelectedConnection(projectRoot);
583
+ if (selected) {
584
+ return {
585
+ alias: selected.alias,
586
+ target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
587
+ };
588
+ }
589
+ } catch {}
590
+ return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
591
+ }
592
+ async function buildServerFailureContext(projectRoot, server) {
593
+ const { alias, target } = describeSelectedServer(projectRoot, server);
594
+ const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
595
+ const reachability = reachable ? "server is reachable" : "server is unreachable";
596
+ return {
597
+ contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
598
+ hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
599
+ };
600
+ }
287
601
  async function requestServerJson(context, pathname, init = {}) {
288
602
  const server = await ensureServerForCli(context.projectRoot);
289
- const response = await fetch(`${server.baseUrl}${pathname}`, {
290
- ...init,
291
- headers: mergeHeaders(init.headers, server.authToken)
292
- });
603
+ const headers = mergeHeaders(init.headers, server.authToken);
604
+ if (server.serverProjectRoot)
605
+ headers.set("x-rig-project-root", server.serverProjectRoot);
606
+ reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
607
+ let response;
608
+ try {
609
+ response = await fetch(`${server.baseUrl}${pathname}`, {
610
+ ...init,
611
+ headers
612
+ });
613
+ } catch (error) {
614
+ const failure = await buildServerFailureContext(context.projectRoot, server);
615
+ throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
616
+ ${failure.contextLine}`, 1, { hint: failure.hint });
617
+ }
293
618
  const text = await response.text();
294
619
  const payload = text.trim().length > 0 ? (() => {
295
620
  try {
@@ -300,8 +625,12 @@ async function requestServerJson(context, pathname, init = {}) {
300
625
  })() : null;
301
626
  if (!response.ok) {
302
627
  const diagnostics = diagnosticMessage(payload);
303
- const detail = diagnostics ?? (text || response.statusText);
304
- throw new CliError2(`Rig server request failed (${response.status}): ${detail}`, 1);
628
+ const rawDetail = diagnostics ?? (text || response.statusText);
629
+ const detail = diagnostics ? rawDetail : rawDetail.split(`
630
+ `).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
631
+ const failure = await buildServerFailureContext(context.projectRoot, server);
632
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
633
+ ${failure.contextLine}`, 1, { hint: failure.hint });
305
634
  }
306
635
  return payload;
307
636
  }
@@ -310,7 +639,7 @@ async function listWorkspaceTasksViaServer(context, filters = {}) {
310
639
  appendTaskFilterParams(url, filters);
311
640
  const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
312
641
  if (!Array.isArray(payload)) {
313
- throw new CliError2("Rig server returned an invalid task list payload.", 1);
642
+ throw new CliError("Rig server returned an invalid task list payload.", 1, { hint: "Check the selected server with `rig server status`; mixed CLI/server versions can mismatch \u2014 try `rig doctor`." });
314
643
  }
315
644
  return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
316
645
  }
@@ -326,7 +655,7 @@ async function selectNextWorkspaceTaskViaServer(context, filters = {}) {
326
655
  appendTaskFilterParams(url, filters);
327
656
  const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
328
657
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
329
- throw new CliError2("Rig server returned an invalid next-task payload.", 1);
658
+ throw new CliError("Rig server returned an invalid next-task payload.", 1, { hint: "Check the selected server with `rig server status`; try `rig task list` to see the raw task set." });
330
659
  }
331
660
  const record = payload;
332
661
  const rawTask = record.task;
@@ -347,6 +676,26 @@ async function getRunLogsViaServer(context, runId, options = {}) {
347
676
  const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
348
677
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
349
678
  }
679
+ async function getRunTimelineViaServer(context, runId, options = {}) {
680
+ const url = new URL(`http://rig.local/api/runs/${encodeURIComponent(runId)}/timeline`);
681
+ if (options.limit !== undefined)
682
+ url.searchParams.set("limit", String(options.limit));
683
+ if (options.cursor)
684
+ url.searchParams.set("cursor", options.cursor);
685
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
686
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { entries: [] };
687
+ }
688
+ var RESUMABLE_RUN_STATUSES = new Set([
689
+ "created",
690
+ "preparing",
691
+ "running",
692
+ "validating",
693
+ "reviewing",
694
+ "stopped",
695
+ "failed",
696
+ "needs-attention",
697
+ "needs_attention"
698
+ ]);
350
699
  async function stopRunViaServer(context, runId) {
351
700
  const payload = await requestServerJson(context, "/api/runs/stop", {
352
701
  method: "POST",
@@ -363,6 +712,14 @@ async function steerRunViaServer(context, runId, message) {
363
712
  });
364
713
  return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true };
365
714
  }
715
+ async function sendRunPiPromptViaServer(context, runId, text, streamingBehavior) {
716
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/pi/prompt`, {
717
+ method: "POST",
718
+ headers: { "content-type": "application/json" },
719
+ body: JSON.stringify({ text, streamingBehavior })
720
+ });
721
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { accepted: true };
722
+ }
366
723
  async function submitTaskRunViaServer(context, input) {
367
724
  const isTaskRun = Boolean(input.taskId);
368
725
  const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
@@ -386,87 +743,15 @@ async function submitTaskRunViaServer(context, input) {
386
743
  })
387
744
  });
388
745
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
389
- throw new CliError2("Rig server returned an invalid run submission payload.", 1);
746
+ throw new CliError("Rig server returned an invalid run submission payload.", 1, { hint: "Check `rig server status` and retry; `rig run list` shows whether the run was created anyway." });
390
747
  }
391
748
  const runId = payload.runId;
392
749
  if (typeof runId !== "string" || runId.trim().length === 0) {
393
- throw new CliError2("Rig server returned no runId for the submitted run.", 1);
750
+ throw new CliError("Rig server returned no runId for the submitted run.", 1, { hint: "Check `rig run list` \u2014 the run may still have been created; otherwise retry the submission." });
394
751
  }
395
752
  return { runId };
396
753
  }
397
754
 
398
- // packages/cli/src/commands/_pi-install.ts
399
- import { existsSync as existsSync3, readFileSync as readFileSync3, rmSync } from "fs";
400
- import { homedir as homedir2 } from "os";
401
- import { resolve as resolve3 } from "path";
402
- var PI_RIG_PACKAGE_NAME = "@rig/pi-rig";
403
- async function defaultCommandRunner(command, options = {}) {
404
- const proc = Bun.spawn(command, { cwd: options.cwd, stdout: "pipe", stderr: "pipe" });
405
- const [stdout, stderr, exitCode] = await Promise.all([
406
- new Response(proc.stdout).text(),
407
- new Response(proc.stderr).text(),
408
- proc.exited
409
- ]);
410
- return { exitCode, stdout, stderr };
411
- }
412
- function resolvePiRigExtensionPath(homeDir) {
413
- return resolve3(homeDir, ".pi", "agent", "extensions", "pi-rig");
414
- }
415
- function resolvePiHomeDir(inputHomeDir) {
416
- return inputHomeDir ?? process.env.RIG_PI_HOME_DIR?.trim() ?? homedir2();
417
- }
418
- function piListContainsPiRig(output) {
419
- return output.split(/\r?\n/).some((line) => {
420
- const normalized = line.trim();
421
- return normalized.includes(PI_RIG_PACKAGE_NAME) || /(?:^|[\\/])packages[\\/]pi-rig(?:$|\s)/.test(normalized);
422
- });
423
- }
424
- async function safeRun(runner, command, options) {
425
- try {
426
- return await runner(command, options);
427
- } catch (error) {
428
- return { exitCode: 1, stdout: "", stderr: error instanceof Error ? error.message : String(error) };
429
- }
430
- }
431
- async function checkPiRigInstall(input = {}) {
432
- const home = resolvePiHomeDir(input.homeDir);
433
- const extensionPath = resolvePiRigExtensionPath(home);
434
- if (process.env.RIG_TEST_FAKE_PI_INSTALL === "1") {
435
- return {
436
- extensionPath,
437
- pi: { ok: true, label: "pi", detail: "fake-pi" },
438
- piRig: { ok: true, label: "pi-rig global extension", detail: extensionPath }
439
- };
440
- }
441
- const exists = input.exists ?? existsSync3;
442
- const runner = input.commandRunner ?? defaultCommandRunner;
443
- const piResult = await safeRun(runner, ["pi", "--version"]);
444
- const piListResult = piResult.exitCode === 0 ? await safeRun(runner, ["pi", "list"]) : { exitCode: 1, stdout: "", stderr: "" };
445
- const listedPiRig = piListResult.exitCode === 0 && piListContainsPiRig(`${piListResult.stdout}
446
- ${piListResult.stderr}`);
447
- const legacyBridge = exists(resolve3(extensionPath, "index.ts"));
448
- const hasPiRig = listedPiRig;
449
- return {
450
- extensionPath,
451
- pi: {
452
- ok: piResult.exitCode === 0,
453
- label: "pi",
454
- detail: (piResult.stdout || piResult.stderr).trim() || undefined,
455
- hint: piResult.exitCode === 0 ? undefined : "Install Pi or run `rig init --yes` to install/update the Pi runtime."
456
- },
457
- piRig: {
458
- ok: hasPiRig,
459
- label: "pi-rig global extension",
460
- detail: hasPiRig ? piListResult.stdout.trim() || PI_RIG_PACKAGE_NAME : legacyBridge ? `${extensionPath} (legacy bridge; reinstall required)` : undefined,
461
- hint: hasPiRig ? undefined : "Run `rig init --yes` to install/enable the global pi-rig package with `pi install`."
462
- }
463
- };
464
- }
465
- async function buildPiSetupChecks(input = {}) {
466
- const status = await checkPiRigInstall(input);
467
- return [status.pi, status.piRig];
468
- }
469
-
470
755
  // packages/cli/src/commands/_preflight.ts
471
756
  function preflightCheck(id, label, status, detail, remediation) {
472
757
  return {
@@ -522,6 +807,9 @@ function permissionAllowsPr(payload) {
522
807
  }
523
808
  return null;
524
809
  }
810
+ function isNotFoundError(error) {
811
+ return /\b(404|not found)\b/i.test(message(error));
812
+ }
525
813
  function projectCheckoutReady(payload) {
526
814
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
527
815
  return null;
@@ -554,19 +842,33 @@ async function runFastTaskRunPreflight(context, options = {}) {
554
842
  const checks = [];
555
843
  const request = options.requestJson ?? ((pathname, init) => requestServerJson(context, pathname, init));
556
844
  const taskId = options.taskId?.trim() || null;
845
+ const requiresCurrentRunApi = Boolean(taskId);
846
+ const selectedServer = options.requestJson ? null : await ensureServerForCli(context.projectRoot).catch(() => null);
847
+ const allowLocalLegacyTaskRunCompatibility = selectedServer?.connectionKind === "local";
848
+ let legacyServerCompatibility = false;
557
849
  try {
558
850
  await request("/api/server/status");
559
851
  checks.push(preflightCheck("server", "Rig server reachable", "pass"));
560
852
  } catch (error) {
561
- checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
853
+ if (isNotFoundError(error)) {
854
+ try {
855
+ await request("/health");
856
+ legacyServerCompatibility = !requiresCurrentRunApi || allowLocalLegacyTaskRunCompatibility;
857
+ 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"));
858
+ } catch (healthError) {
859
+ checks.push(preflightCheck("server", "Rig server reachable", "fail", message(healthError), "Start or select a reachable Rig server."));
860
+ }
861
+ } else {
862
+ checks.push(preflightCheck("server", "Rig server reachable", "fail", message(error), "Start or select a reachable Rig server."));
863
+ }
562
864
  }
563
865
  const repo = readRepoConnection(context.projectRoot);
564
- 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", "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig connect use <alias|local>`."));
866
+ checks.push(repo ? preflightCheck("project-link", "project linked to Rig server", repo.project ? "pass" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : ""}`, "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to Rig server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
565
867
  try {
566
868
  const auth = await request("/api/github/auth/status");
567
- checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
869
+ checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
568
870
  } catch (error) {
569
- checks.push(preflightCheck("github-auth", "GitHub auth valid", "fail", message(error), "Fix GitHub auth on the selected Rig server."));
871
+ checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
570
872
  }
571
873
  try {
572
874
  const projection = await request("/api/workspace/task-projection");
@@ -594,9 +896,9 @@ async function runFastTaskRunPreflight(context, options = {}) {
594
896
  try {
595
897
  const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
596
898
  const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
597
- checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
899
+ checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
598
900
  } catch (error) {
599
- checks.push(preflightCheck("issue", "task/issue accessible", "fail", message(error), "Fix the task source before launching a run."));
901
+ checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
600
902
  }
601
903
  try {
602
904
  const runs = await request("/api/runs?limit=200");
@@ -607,14 +909,7 @@ async function runFastTaskRunPreflight(context, options = {}) {
607
909
  }
608
910
  }
609
911
  if ((options.runtimeAdapter ?? "pi") === "pi") {
610
- const piChecks = await (options.piChecks ?? (() => buildPiSetupChecks()))().catch((error) => [{
611
- ok: false,
612
- label: "pi/pi-rig checks",
613
- hint: message(error)
614
- }]);
615
- for (const pi of piChecks) {
616
- checks.push(preflightCheck(pi.label === "pi" ? "pi" : "pi-rig", pi.label, pi.ok ? "pass" : "fail", pi.detail, pi.hint ?? (pi.ok ? undefined : "Run `rig init --yes` to install/update Pi and enable pi-rig.")));
617
- }
912
+ checks.push(preflightCheck("runtime", "worker Pi SDK session daemon", "pass", selectedServer?.connectionKind === "remote" ? "remote worker-owned runtime" : "bundled server-owned runtime"));
618
913
  } else {
619
914
  checks.push(preflightCheck("runtime", "runtime adapter", "pass", options.runtimeAdapter));
620
915
  }
@@ -622,9 +917,9 @@ async function runFastTaskRunPreflight(context, options = {}) {
622
917
  if (failures.length > 0) {
623
918
  const summary = failures.map((check) => `${check.label}${check.detail ? `: ${check.detail}` : ""}`).join("; ");
624
919
  if (failures.some((check) => check.id === "duplicate-active-run") && taskId) {
625
- throw new CliError2(`Task ${taskId} already has an active Rig run. ${summary}`, 1);
920
+ throw new CliError(`Task ${taskId} already has an active Rig run. ${summary}`, 1, { hint: `Attach to it with \`rig run attach <run-id> --follow\`, or stop it first with \`rig run stop <run-id>\`.` });
626
921
  }
627
- throw new CliError2(`Task run preflight failed: ${summary}`, 1);
922
+ throw new CliError(`Task run preflight failed: ${summary}`, 1, { hint: "Run `rig doctor` to diagnose, then retry `rig task run`." });
628
923
  }
629
924
  return { ok: true, checks };
630
925
  }
@@ -641,7 +936,7 @@ async function runProjectMainSyncPreflight(context, options) {
641
936
  runBootstrap: async () => {
642
937
  const bootstrap = await context.runCommand(["bun", "run", "bootstrap"]);
643
938
  if (bootstrap.exitCode !== 0) {
644
- throw new CliError2(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
939
+ throw new CliError(bootstrap.stderr || bootstrap.stdout || "bun run bootstrap failed during project pre-run sync", bootstrap.exitCode || 1);
645
940
  }
646
941
  }
647
942
  });
@@ -705,8 +1000,198 @@ function withMutedConsole(mute, fn) {
705
1000
  }
706
1001
  }
707
1002
 
708
- // packages/cli/src/commands/_task-picker.ts
709
- import { createInterface } from "readline/promises";
1003
+ // packages/cli/src/commands/_operator-surface.ts
1004
+ import { createInterface } from "readline";
1005
+ import { createInterface as createPromptInterface } from "readline/promises";
1006
+ var CANONICAL_STAGES = [
1007
+ "Connect",
1008
+ "GitHub/task sync",
1009
+ "Prepare workspace",
1010
+ "Launch Pi",
1011
+ "Plan",
1012
+ "Implement",
1013
+ "Validate",
1014
+ "Commit",
1015
+ "Open PR",
1016
+ "Review/CI",
1017
+ "Merge",
1018
+ "Complete"
1019
+ ];
1020
+ function logDetail(log) {
1021
+ return typeof log.detail === "string" ? log.detail.trim() : "";
1022
+ }
1023
+ function parseProviderProtocolLog(title, detail) {
1024
+ if (title.trim().toLowerCase() !== "agent output")
1025
+ return null;
1026
+ if (!detail.startsWith("{") || !detail.endsWith("}"))
1027
+ return null;
1028
+ try {
1029
+ const record = JSON.parse(detail);
1030
+ if (!record || typeof record !== "object" || Array.isArray(record))
1031
+ return null;
1032
+ const type = record.type;
1033
+ return typeof type === "string" && [
1034
+ "assistant",
1035
+ "message_start",
1036
+ "message_update",
1037
+ "message_end",
1038
+ "stream_event",
1039
+ "tool_result",
1040
+ "tool_execution_start",
1041
+ "tool_execution_update",
1042
+ "tool_execution_end",
1043
+ "turn_start",
1044
+ "turn_end"
1045
+ ].includes(type) ? record : null;
1046
+ } catch {
1047
+ return null;
1048
+ }
1049
+ }
1050
+ function renderProviderProtocolLog(record) {
1051
+ const type = typeof record.type === "string" ? record.type : "";
1052
+ if (type === "tool_execution_start" || type === "tool_execution_update" || type === "tool_execution_end") {
1053
+ const toolName = String(record.toolName ?? record.name ?? "tool");
1054
+ 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";
1055
+ return `[Pi tool] ${toolName} ${status}`;
1056
+ }
1057
+ return null;
1058
+ }
1059
+ function entryId(entry, fallback) {
1060
+ return typeof entry.id === "string" && entry.id.trim() ? entry.id : fallback;
1061
+ }
1062
+ function renderOperatorSnapshot(snapshot) {
1063
+ const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
1064
+ const runId = String(run.runId ?? run.id ?? "run");
1065
+ const status = String(run.status ?? "unknown");
1066
+ const logs = snapshot.logs ?? [];
1067
+ const latestByStage = new Map;
1068
+ for (const log of logs) {
1069
+ const title = String(log.title ?? "").toLowerCase();
1070
+ const stageName = String(log.stage ?? "").toLowerCase();
1071
+ const stage = CANONICAL_STAGES.find((candidate) => candidate.toLowerCase() === title || candidate.toLowerCase() === stageName);
1072
+ if (stage)
1073
+ latestByStage.set(stage, log);
1074
+ }
1075
+ const stageLines = CANONICAL_STAGES.flatMap((stage) => {
1076
+ const match = latestByStage.get(stage);
1077
+ return match ? [`${stage}: ${String(match.status ?? status)}${logDetail(match) ? ` \u2014 ${logDetail(match)}` : ""}`] : [];
1078
+ });
1079
+ return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
1080
+ `);
1081
+ }
1082
+ function createPiRunStreamRenderer(output = process.stdout) {
1083
+ let lastSnapshot = "";
1084
+ const assistantTextById = new Map;
1085
+ const seenTimeline = new Set;
1086
+ const seenLogs = new Set;
1087
+ const writeLine = (line) => output.write(`${line}
1088
+ `);
1089
+ return {
1090
+ renderSnapshot(snapshot) {
1091
+ const rendered = renderOperatorSnapshot(snapshot);
1092
+ if (rendered && rendered !== lastSnapshot) {
1093
+ writeLine(rendered);
1094
+ lastSnapshot = rendered;
1095
+ }
1096
+ },
1097
+ renderTimeline(entries) {
1098
+ for (const [index, entry] of entries.entries()) {
1099
+ const id = entryId(entry, `timeline:${index}:${String(entry.cursor ?? "")}`);
1100
+ if (entry.type === "assistant_message" && typeof entry.text === "string") {
1101
+ const text = entry.text;
1102
+ const previousText = assistantTextById.get(id) ?? "";
1103
+ if (!previousText && text.trim()) {
1104
+ writeLine("[Pi assistant]");
1105
+ }
1106
+ if (text.startsWith(previousText)) {
1107
+ const delta = text.slice(previousText.length);
1108
+ if (delta)
1109
+ output.write(delta);
1110
+ } else if (text.trim() && text !== previousText) {
1111
+ if (previousText)
1112
+ writeLine(`
1113
+ [Pi assistant]`);
1114
+ output.write(text);
1115
+ }
1116
+ assistantTextById.set(id, text);
1117
+ continue;
1118
+ }
1119
+ if (seenTimeline.has(id))
1120
+ continue;
1121
+ seenTimeline.add(id);
1122
+ if (entry.type === "tool_execution_start" || entry.type === "tool_execution_update" || entry.type === "tool_execution_end" || entry.type === "mcp_tool_call") {
1123
+ writeLine(`[Pi tool] ${String(entry.toolName ?? entry.name ?? entry.title ?? entry.type)} ${String(entry.status ?? entry.state ?? "")}`.trim());
1124
+ continue;
1125
+ }
1126
+ if (entry.type === "timeline_warning") {
1127
+ writeLine(`[Rig timeline] ${String(entry.detail ?? entry.message ?? "timeline unavailable")}`);
1128
+ continue;
1129
+ }
1130
+ if (entry.type === "action") {
1131
+ const text = String(entry.detail ?? entry.message ?? entry.title ?? "").trim();
1132
+ if (text)
1133
+ writeLine(`[Rig action] ${text}`);
1134
+ continue;
1135
+ }
1136
+ if (entry.type === "user_message") {
1137
+ const text = String(entry.text ?? entry.message ?? entry.detail ?? "").trim();
1138
+ if (text)
1139
+ writeLine(`[Operator] ${text}`);
1140
+ continue;
1141
+ }
1142
+ const fallback = String(entry.detail ?? entry.message ?? entry.text ?? entry.title ?? "").trim();
1143
+ if (fallback)
1144
+ writeLine(`[${String(entry.type ?? "timeline")}] ${fallback}`);
1145
+ }
1146
+ },
1147
+ renderLogs(entries) {
1148
+ for (const [index, entry] of entries.entries()) {
1149
+ const id = entryId(entry, `log:${index}:${String(entry.createdAt ?? "")}:${String(entry.title ?? "")}`);
1150
+ if (seenLogs.has(id))
1151
+ continue;
1152
+ seenLogs.add(id);
1153
+ const title = String(entry.title ?? "");
1154
+ if (CANONICAL_STAGES.some((stage) => stage.toLowerCase() === title.toLowerCase()))
1155
+ continue;
1156
+ const detail = logDetail(entry);
1157
+ if (!detail)
1158
+ continue;
1159
+ const protocolRecord = parseProviderProtocolLog(title, detail);
1160
+ if (protocolRecord) {
1161
+ const protocolLine = renderProviderProtocolLog(protocolRecord);
1162
+ if (protocolLine)
1163
+ writeLine(protocolLine);
1164
+ continue;
1165
+ }
1166
+ writeLine(`[${title || "Rig log"}] ${detail}`);
1167
+ }
1168
+ }
1169
+ };
1170
+ }
1171
+ function createOperatorSurface(options = {}) {
1172
+ const input = options.input ?? process.stdin;
1173
+ const output = options.output ?? process.stdout;
1174
+ const errorOutput = options.errorOutput ?? process.stderr;
1175
+ const renderer = createPiRunStreamRenderer(output);
1176
+ const writeLine = (line) => output.write(`${line}
1177
+ `);
1178
+ return {
1179
+ mode: "pi-compatible-text",
1180
+ ...renderer,
1181
+ info: writeLine,
1182
+ error: (message2) => errorOutput.write(`${message2}
1183
+ `),
1184
+ attachCommandInput(handler) {
1185
+ if (options.interactive === false || !input.isTTY)
1186
+ return null;
1187
+ const rl = createInterface({ input, output: process.stdout, terminal: false });
1188
+ rl.on("line", (line) => {
1189
+ Promise.resolve(handler(line)).catch((error) => writeLine(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
1190
+ });
1191
+ return { close: () => rl.close() };
1192
+ }
1193
+ };
1194
+ }
710
1195
  function taskId(task) {
711
1196
  return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
712
1197
  }
@@ -719,65 +1204,327 @@ function taskStatus(task) {
719
1204
  function renderTaskPickerRows(tasks) {
720
1205
  return tasks.map((task, index) => `${index + 1}. ${taskId(task)} \xB7 ${taskStatus(task)} \xB7 ${taskTitle(task)}`);
721
1206
  }
1207
+ async function promptForTaskSelection(question) {
1208
+ const rl = createPromptInterface({ input: process.stdin, output: process.stdout });
1209
+ try {
1210
+ return await rl.question(question);
1211
+ } finally {
1212
+ rl.close();
1213
+ }
1214
+ }
1215
+
1216
+ // packages/cli/src/commands/_task-picker.ts
1217
+ function taskId2(task) {
1218
+ return typeof task.id === "string" && task.id.trim() ? task.id : "<unknown>";
1219
+ }
722
1220
  async function selectTaskWithTextPicker(tasks, io = {}) {
723
1221
  if (tasks.length === 0)
724
1222
  return null;
725
1223
  if (tasks.length === 1)
726
1224
  return tasks[0];
727
- const isTty = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
728
- if (!isTty) {
1225
+ const isTty2 = io.isTty ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
1226
+ if (!isTty2) {
729
1227
  throw new Error("task run requires an interactive terminal to pick a task; pass --task <id>, --next, or --detach with a task id.");
730
1228
  }
731
- const prompt = io.prompt ?? (async (question) => {
732
- const rl = createInterface({ input: process.stdin, output: process.stdout });
733
- try {
734
- return await rl.question(question);
735
- } finally {
736
- rl.close();
1229
+ if (io.prompt || io.renderer) {
1230
+ const prompt = io.prompt ?? promptForTaskSelection;
1231
+ const renderer = io.renderer ?? { writeLine: (line) => process.stdout.write(`${line}
1232
+ `) };
1233
+ renderer.writeLine("Select Rig task:");
1234
+ for (const row of renderTaskPickerRows(tasks))
1235
+ renderer.writeLine(` ${row}`);
1236
+ const answer2 = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
1237
+ if (!answer2)
1238
+ return null;
1239
+ if (/^\d+$/.test(answer2)) {
1240
+ const index2 = Number.parseInt(answer2, 10) - 1;
1241
+ return tasks[index2] ?? null;
737
1242
  }
1243
+ return tasks.find((task) => taskId2(task) === answer2) ?? null;
1244
+ }
1245
+ const options = tasks.map((task, index2) => ({
1246
+ value: `${index2}`,
1247
+ label: `${taskId2(task)} \xB7 ${typeof task.title === "string" && task.title.trim() ? task.title.trim() : "Untitled task"}`,
1248
+ hint: typeof task.status === "string" && task.status.trim() ? task.status.trim() : undefined
1249
+ }));
1250
+ const answer = await droneSelect({
1251
+ message: "Select Rig task",
1252
+ options
738
1253
  });
739
- console.log("Select Rig task:");
740
- for (const row of renderTaskPickerRows(tasks))
741
- console.log(` ${row}`);
742
- const answer = (await prompt(`Task [1-${tasks.length}] or id: `)).trim();
743
- if (!answer)
1254
+ if (answer === null) {
1255
+ droneCancel("No task selected.");
744
1256
  return null;
745
- if (/^\d+$/.test(answer)) {
746
- const index = Number.parseInt(answer, 10) - 1;
747
- return tasks[index] ?? null;
748
1257
  }
749
- return tasks.find((task) => taskId(task) === answer) ?? null;
1258
+ const index = Number.parseInt(String(answer), 10);
1259
+ return Number.isFinite(index) ? tasks[index] ?? null : null;
750
1260
  }
751
1261
 
752
- // packages/cli/src/commands/_operator-view.ts
753
- import { createInterface as createInterface2 } from "readline";
754
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
755
- var CANONICAL_STAGES = [
756
- "Connect",
757
- "GitHub/task sync",
758
- "Prepare workspace",
759
- "Launch Pi",
760
- "Plan",
761
- "Implement",
762
- "Validate",
763
- "Commit",
764
- "Open PR",
765
- "Review/CI",
766
- "Merge",
767
- "Complete"
768
- ];
769
- function renderOperatorSnapshot(snapshot) {
770
- const run = snapshot.run.run && typeof snapshot.run.run === "object" ? snapshot.run.run : snapshot.run;
771
- const runId = String(run.runId ?? run.id ?? "run");
772
- const status = String(run.status ?? "unknown");
773
- const logs = snapshot.logs ?? [];
774
- const stageLines = CANONICAL_STAGES.flatMap((stage) => {
775
- const match = logs.find((log) => String(log.title ?? "").toLowerCase() === stage.toLowerCase() || String(log.stage ?? "").toLowerCase() === stage.toLowerCase());
776
- return match ? [`${stage}: ${String(match.status ?? status)}`] : [];
1262
+ // packages/cli/src/commands/_async-ui.ts
1263
+ import pc from "picocolors";
1264
+ var DONE_SYMBOL = pc.green("\u25C7");
1265
+ var FAIL_SYMBOL = pc.red("\u25A0");
1266
+ var activeUpdate = null;
1267
+ async function withSpinner(label, work, options = {}) {
1268
+ if (options.outputMode === "json") {
1269
+ return work(() => {});
1270
+ }
1271
+ if (activeUpdate) {
1272
+ const outer = activeUpdate;
1273
+ outer(label);
1274
+ return work(outer);
1275
+ }
1276
+ const output = options.output ?? process.stderr;
1277
+ const isTty2 = output.isTTY === true;
1278
+ let lastLabel = label;
1279
+ if (!isTty2) {
1280
+ output.write(`${label}
1281
+ `);
1282
+ const update2 = (next) => {
1283
+ lastLabel = next;
1284
+ };
1285
+ activeUpdate = update2;
1286
+ const previousListener2 = setServerPhaseListener(update2);
1287
+ try {
1288
+ return await work(update2);
1289
+ } finally {
1290
+ activeUpdate = null;
1291
+ setServerPhaseListener(previousListener2);
1292
+ }
1293
+ }
1294
+ const spinner = createTtySpinner({
1295
+ label,
1296
+ output,
1297
+ frames: MICRO_DRONE_FRAMES,
1298
+ styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
777
1299
  });
778
- return [`Rig run ${runId}: ${status}`, ...stageLines].join(`
1300
+ const update = (next) => {
1301
+ lastLabel = next;
1302
+ spinner.setLabel(next);
1303
+ };
1304
+ activeUpdate = update;
1305
+ const previousListener = setServerPhaseListener(update);
1306
+ try {
1307
+ const result = await work(update);
1308
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
1309
+ return result;
1310
+ } catch (error) {
1311
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
1312
+ throw error;
1313
+ } finally {
1314
+ activeUpdate = null;
1315
+ setServerPhaseListener(previousListener);
1316
+ }
1317
+ }
1318
+
1319
+ // packages/cli/src/commands/_pi-frontend.ts
1320
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
1321
+ import { homedir as homedir2, tmpdir } from "os";
1322
+ import { join } from "path";
1323
+ import { main as runPiMain } from "@earendil-works/pi-coding-agent";
1324
+ import createPiRigExtension from "@rig/pi-rig";
1325
+ function setTemporaryEnv(updates) {
1326
+ const previous = new Map;
1327
+ for (const [key, value] of Object.entries(updates)) {
1328
+ previous.set(key, process.env[key]);
1329
+ process.env[key] = value;
1330
+ }
1331
+ return () => {
1332
+ for (const [key, value] of previous) {
1333
+ if (value === undefined)
1334
+ delete process.env[key];
1335
+ else
1336
+ process.env[key] = value;
1337
+ }
1338
+ };
1339
+ }
1340
+ function buildOperatorPiEnv(input) {
1341
+ return {
1342
+ PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
1343
+ PI_SKIP_VERSION_CHECK: "1",
1344
+ PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
1345
+ RIG_PI_OPERATOR_SESSION: "1",
1346
+ RIG_RUN_ID: input.runId,
1347
+ RIG_SERVER_URL: input.serverUrl,
1348
+ ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
1349
+ ...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
1350
+ };
1351
+ }
1352
+ async function prepareOperatorConsole(context, runId, tempSessionDir) {
1353
+ const server = await ensureServerForCli(context.projectRoot);
1354
+ const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
1355
+ mkdirSync2(localCwd, { recursive: true });
1356
+ trustDroneCwd(localCwd);
1357
+ installRigPiTheme();
1358
+ let sessionFileArg = [];
1359
+ try {
1360
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
1361
+ if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
1362
+ const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
1363
+ const localSessionPath = join(tempSessionDir, fileName);
1364
+ const content = payload.content.split(`
1365
+ `).map((line, index) => {
1366
+ if (index > 0 || !line.trim())
1367
+ return line;
1368
+ try {
1369
+ const header = JSON.parse(line);
1370
+ if (header.type === "session" && typeof header.cwd === "string") {
1371
+ return JSON.stringify({ ...header, cwd: localCwd });
1372
+ }
1373
+ } catch {}
1374
+ return line;
1375
+ }).join(`
779
1376
  `);
1377
+ writeFileSync2(localSessionPath, content);
1378
+ sessionFileArg = ["--session", localSessionPath];
1379
+ }
1380
+ } catch {}
1381
+ return { server, sessionFileArg };
1382
+ }
1383
+ var RIG_PI_THEME = {
1384
+ $schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
1385
+ name: "rig",
1386
+ vars: {
1387
+ acid: "#ccff4d",
1388
+ acidDim: "#a9d63f",
1389
+ cyan: "#56d8ff",
1390
+ red: "#ff5d5d",
1391
+ yellow: "#ffd24d",
1392
+ ink: "#f2f3f6",
1393
+ ink2: "#aeb0ba",
1394
+ ink3: "#6c6e79",
1395
+ ink4: "#44464f",
1396
+ panel: "#101115",
1397
+ panelUser: "#14161b",
1398
+ toolPending: "#0e1013",
1399
+ toolSuccess: "#10150c",
1400
+ toolError: "#1a0f0f",
1401
+ customMsg: "#0f1410"
1402
+ },
1403
+ colors: {
1404
+ accent: "acid",
1405
+ border: "ink4",
1406
+ borderAccent: "acid",
1407
+ borderMuted: "ink4",
1408
+ success: "acid",
1409
+ error: "red",
1410
+ warning: "yellow",
1411
+ muted: "ink3",
1412
+ dim: "ink4",
1413
+ text: "ink",
1414
+ thinkingText: "ink3",
1415
+ selectedBg: "panel",
1416
+ userMessageBg: "panelUser",
1417
+ userMessageText: "ink",
1418
+ customMessageBg: "customMsg",
1419
+ customMessageText: "ink2",
1420
+ customMessageLabel: "acidDim",
1421
+ toolPendingBg: "toolPending",
1422
+ toolSuccessBg: "toolSuccess",
1423
+ toolErrorBg: "toolError",
1424
+ toolTitle: "ink",
1425
+ toolOutput: "ink3",
1426
+ mdHeading: "acid",
1427
+ mdLink: "cyan",
1428
+ mdLinkUrl: "ink4",
1429
+ mdCode: "acidDim",
1430
+ mdCodeBlock: "ink2",
1431
+ mdCodeBlockBorder: "ink4",
1432
+ mdQuote: "ink3",
1433
+ mdQuoteBorder: "ink4",
1434
+ mdHr: "ink4",
1435
+ mdListBullet: "acid",
1436
+ toolDiffAdded: "acid",
1437
+ toolDiffRemoved: "red",
1438
+ toolDiffContext: "ink3",
1439
+ syntaxComment: "ink3",
1440
+ syntaxKeyword: "cyan",
1441
+ syntaxFunction: "acid",
1442
+ syntaxVariable: "ink",
1443
+ syntaxString: "acidDim",
1444
+ syntaxNumber: "yellow",
1445
+ syntaxType: "cyan",
1446
+ syntaxOperator: "ink2",
1447
+ syntaxPunctuation: "ink3",
1448
+ thinkingOff: "ink4",
1449
+ thinkingMinimal: "ink3",
1450
+ thinkingLow: "ink2",
1451
+ thinkingMedium: "cyan",
1452
+ thinkingHigh: "acidDim",
1453
+ thinkingXhigh: "acid",
1454
+ bashMode: "cyan"
1455
+ }
1456
+ };
1457
+ function trustDroneCwd(localCwd) {
1458
+ try {
1459
+ const agentDir = join(homedir2(), ".pi", "agent");
1460
+ mkdirSync2(agentDir, { recursive: true });
1461
+ const trustPath = join(agentDir, "trust.json");
1462
+ const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
1463
+ if (store[localCwd] !== true) {
1464
+ store[localCwd] = true;
1465
+ writeFileSync2(trustPath, `${JSON.stringify(store, null, "\t")}
1466
+ `);
1467
+ }
1468
+ } catch {}
1469
+ }
1470
+ function installRigPiTheme() {
1471
+ try {
1472
+ const themesDir = join(homedir2(), ".pi", "agent", "themes");
1473
+ mkdirSync2(themesDir, { recursive: true });
1474
+ const themePath = join(themesDir, "rig.json");
1475
+ const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
1476
+ `;
1477
+ if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
1478
+ writeFileSync2(themePath, next);
1479
+ }
1480
+ } catch {}
1481
+ }
1482
+ async function attachRunBundledPiFrontend(context, input) {
1483
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1484
+ const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
1485
+ const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
1486
+ runId: input.runId,
1487
+ serverUrl: server.baseUrl,
1488
+ authToken: server.authToken,
1489
+ serverProjectRoot: server.serverProjectRoot,
1490
+ sessionDir: tempSessionDir
1491
+ }));
1492
+ const piRigExtensionFactory = (pi) => {
1493
+ createPiRigExtension(pi);
1494
+ };
1495
+ let detached = false;
1496
+ try {
1497
+ await runPiMain([
1498
+ "--no-extensions",
1499
+ "--no-skills",
1500
+ "--no-prompt-templates",
1501
+ "--no-context-files",
1502
+ ...sessionFileArg
1503
+ ], {
1504
+ extensionFactories: [piRigExtensionFactory]
1505
+ });
1506
+ detached = true;
1507
+ } finally {
1508
+ restoreEnv();
1509
+ rmSync(tempSessionDir, { recursive: true, force: true });
1510
+ }
1511
+ let run = { runId: input.runId, status: "unknown" };
1512
+ try {
1513
+ run = await getRunDetailsViaServer(context, input.runId);
1514
+ } catch {}
1515
+ return {
1516
+ run,
1517
+ logs: [],
1518
+ timeline: [],
1519
+ timelineCursor: null,
1520
+ steered: input.steered === true,
1521
+ detached,
1522
+ rendered: "stock Pi operator console with the pi-rig extension"
1523
+ };
780
1524
  }
1525
+
1526
+ // packages/cli/src/commands/_operator-view.ts
1527
+ var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
781
1528
  function runStatusFromPayload(payload) {
782
1529
  const run = payload.run && typeof payload.run === "object" && !Array.isArray(payload.run) ? payload.run : payload;
783
1530
  return String(run.status ?? "unknown").toLowerCase();
@@ -799,56 +1546,641 @@ async function applyOperatorCommand(context, input, deps = {}) {
799
1546
  await (deps.steer ?? steerRunViaServer)(context, input.runId, userMessage);
800
1547
  return { action: "continue", message: "Steering message queued." };
801
1548
  }
802
- async function readOperatorSnapshot(context, runId) {
1549
+ async function readOperatorSnapshot(context, runId, options = {}) {
803
1550
  const run = await getRunDetailsViaServer(context, runId);
804
1551
  const logsPage = await getRunLogsViaServer(context, runId, { limit: 100 });
805
- const entries = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
806
- return { run, logs: entries, rendered: renderOperatorSnapshot({ run, logs: entries }) };
1552
+ const timelinePage = await getRunTimelineViaServer(context, runId, { limit: 200, ...options.timelineCursor ? { cursor: options.timelineCursor } : {} }).catch((error) => ({
1553
+ entries: [{
1554
+ id: `timeline-unavailable:${runId}`,
1555
+ type: "timeline_warning",
1556
+ detail: `Selected Rig server did not provide run timeline events: ${error instanceof Error ? error.message : String(error)}`,
1557
+ createdAt: new Date().toISOString()
1558
+ }],
1559
+ nextCursor: options.timelineCursor ?? null
1560
+ }));
1561
+ const logs = Array.isArray(logsPage.entries) ? logsPage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))).toReversed() : [];
1562
+ const timeline = Array.isArray(timelinePage.entries) ? timelinePage.entries.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry))) : [];
1563
+ const timelineCursor = typeof timelinePage.nextCursor === "string" ? timelinePage.nextCursor : options.timelineCursor ?? null;
1564
+ return { run, logs, timeline, timelineCursor, rendered: renderOperatorSnapshot({ run, logs, timeline }) };
807
1565
  }
808
1566
  async function attachRunOperatorView(context, input) {
809
1567
  let steered = false;
810
- if (input.message?.trim()) {
811
- await steerRunViaServer(context, input.runId, input.message.trim());
1568
+ const attachMessage = input.message?.trim();
1569
+ if (attachMessage) {
1570
+ await withSpinner("Queueing steering message\u2026", () => sendRunPiPromptViaServer(context, input.runId, attachMessage, "steer").catch(() => steerRunViaServer(context, input.runId, attachMessage)), { outputMode: context.outputMode });
812
1571
  steered = true;
813
1572
  }
814
- let snapshot = await readOperatorSnapshot(context, input.runId);
1573
+ if (!input.once && input.interactive !== false && context.outputMode === "text" && Boolean(process.stdin.isTTY && process.stdout.isTTY)) {
1574
+ return attachRunBundledPiFrontend(context, {
1575
+ runId: input.runId,
1576
+ steered
1577
+ });
1578
+ }
1579
+ const surface = createOperatorSurface({ interactive: input.interactive !== false });
1580
+ let snapshot = await withSpinner(`Connecting to run ${input.runId}\u2026`, () => readOperatorSnapshot(context, input.runId), { outputMode: context.outputMode });
815
1581
  if (context.outputMode === "text") {
816
- console.log(snapshot.rendered);
1582
+ surface.renderSnapshot(snapshot);
1583
+ surface.renderTimeline(snapshot.timeline);
1584
+ surface.renderLogs(snapshot.logs);
817
1585
  if (steered)
818
- console.log("Steering message queued.");
1586
+ surface.info("Message submitted to worker Pi.");
819
1587
  }
820
1588
  let detached = false;
821
- let rl = null;
1589
+ let commandInput = null;
822
1590
  if (input.follow && !input.once && context.outputMode === "text") {
823
1591
  if (input.interactive !== false && process.stdin.isTTY) {
824
- console.log("Controls: /user <message>, /stop, /detach");
825
- rl = createInterface2({ input: process.stdin, output: process.stdout, terminal: false });
826
- rl.on("line", (line) => {
827
- applyOperatorCommand(context, { runId: input.runId, line }).then((result) => {
828
- if (result.message)
829
- console.log(result.message);
830
- if (result.action === "detach" || result.action === "stopped") {
831
- detached = true;
832
- rl?.close();
833
- }
834
- }).catch((error) => console.log(`Operator command failed: ${error instanceof Error ? error.message : String(error)}`));
1592
+ surface.info("Controls: /user <message>, /stop, /detach");
1593
+ commandInput = surface.attachCommandInput(async (line) => {
1594
+ const result = await applyOperatorCommand(context, { runId: input.runId, line });
1595
+ if (result.message)
1596
+ surface.info(result.message);
1597
+ if (result.action === "detach" || result.action === "stopped") {
1598
+ detached = true;
1599
+ commandInput?.close();
1600
+ }
835
1601
  });
836
1602
  }
837
- let lastRendered = snapshot.rendered;
838
1603
  const pollMs = Math.max(250, Math.trunc(input.pollMs ?? 2000));
1604
+ let timelineCursor = snapshot.timelineCursor;
839
1605
  while (!detached && !TERMINAL_RUN_STATUSES.has(runStatusFromPayload(snapshot.run))) {
840
1606
  await Bun.sleep(pollMs);
841
- snapshot = await readOperatorSnapshot(context, input.runId);
842
- if (snapshot.rendered !== lastRendered) {
843
- console.log(snapshot.rendered);
844
- lastRendered = snapshot.rendered;
845
- }
1607
+ snapshot = await readOperatorSnapshot(context, input.runId, { timelineCursor });
1608
+ timelineCursor = snapshot.timelineCursor;
1609
+ surface.renderSnapshot(snapshot);
1610
+ surface.renderTimeline(snapshot.timeline);
1611
+ surface.renderLogs(snapshot.logs);
846
1612
  }
847
- rl?.close();
1613
+ commandInput?.close();
848
1614
  }
849
1615
  return { ...snapshot, steered, detached };
850
1616
  }
851
1617
 
1618
+ // packages/cli/src/commands/_cli-format.ts
1619
+ import pc2 from "picocolors";
1620
+ var themeDim = (value) => ink3(value);
1621
+ var themeFaint = (value) => ink4(value);
1622
+ function stringField(record, key, fallback = "") {
1623
+ const value = record[key];
1624
+ return typeof value === "string" && value.trim() ? value.trim() : fallback;
1625
+ }
1626
+ function numberField(record, key) {
1627
+ const value = record[key];
1628
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
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", "approved", "running"].includes(normalized))
1651
+ return accent;
1652
+ if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
1653
+ return red;
1654
+ if (["reviewing", "validating", "in_progress", "in-progress", "remote", "preparing", "closing-out"].includes(normalized))
1655
+ return cyan;
1656
+ if (["ready", "open", "queued", "created", "local", "pending"].includes(normalized))
1657
+ return yellow;
1658
+ return themeDim;
1659
+ }
1660
+ function compactValue(value) {
1661
+ if (value === null || value === undefined)
1662
+ return "";
1663
+ if (typeof value === "string")
1664
+ return value;
1665
+ if (typeof value === "number" || typeof value === "boolean")
1666
+ return String(value);
1667
+ if (Array.isArray(value))
1668
+ return value.map(compactValue).filter(Boolean).join(", ");
1669
+ return JSON.stringify(value);
1670
+ }
1671
+ function shouldUseClackOutput() {
1672
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
1673
+ }
1674
+ function printFormattedOutput(message2, options = {}) {
1675
+ if (!shouldUseClackOutput()) {
1676
+ console.log(message2);
1677
+ return;
1678
+ }
1679
+ droneNote(message2, options.title);
1680
+ }
1681
+ function formatStatusPill(status) {
1682
+ const label = status || "unknown";
1683
+ return statusColor(label)(`\u25CF ${label}`);
1684
+ }
1685
+ function formatSection(title, subtitle) {
1686
+ return `${pc2.bold(accent("\u25C6"))} ${pc2.bold(title)}${subtitle ? themeDim(` \u2014 ${subtitle}`) : ""}`;
1687
+ }
1688
+ function formatSuccessCard(title, rows = []) {
1689
+ const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${themeFaint("\u2502")} ${themeDim(key.padEnd(12))} ${value}`);
1690
+ return [formatSection(title), ...body].join(`
1691
+ `);
1692
+ }
1693
+ function formatNextSteps(steps) {
1694
+ if (steps.length === 0)
1695
+ return [];
1696
+ return [pc2.bold("Next"), ...steps.map((step) => `${accent("\u203A")} ${step}`)];
1697
+ }
1698
+ function formatTaskList(tasks, options = {}) {
1699
+ if (options.raw)
1700
+ return tasks.map((task) => JSON.stringify(task)).join(`
1701
+ `);
1702
+ if (tasks.length === 0)
1703
+ 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(`
1704
+ `);
1705
+ const rows = tasks.map((task) => {
1706
+ const raw = rawObject(task);
1707
+ const id = stringField(task, "id", "<unknown>");
1708
+ const status = stringField(task, "status", "unknown");
1709
+ const title = stringField(task, "title", "Untitled task");
1710
+ const source = stringField(task, "source", stringField(raw, "source", ""));
1711
+ const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
1712
+ return { id, status, title, source, labels };
1713
+ });
1714
+ const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
1715
+ const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
1716
+ const header = `${pc2.bold(pad("TASK", idWidth))} ${pc2.bold(pad("STATUS", statusWidth))} ${pc2.bold("TITLE")}`;
1717
+ const body = rows.map((row) => {
1718
+ const labels = row.labels.length > 0 ? themeDim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
1719
+ const source = row.source ? themeDim(` ${row.source}`) : "";
1720
+ return [
1721
+ pc2.bold(pad(truncate(row.id, idWidth), idWidth)),
1722
+ statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
1723
+ `${row.title}${labels}${source}`
1724
+ ].join(" ");
1725
+ });
1726
+ 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(`
1727
+ `);
1728
+ }
1729
+ function formatTaskCard(task, options = {}) {
1730
+ const raw = rawObject(task);
1731
+ const id = stringField(task, "id", stringField(raw, "id", "<unknown>"));
1732
+ const status = stringField(task, "status", stringField(raw, "status", "unknown"));
1733
+ const title = stringField(task, "title", stringField(raw, "title", "Untitled task"));
1734
+ const source = stringField(task, "source", stringField(raw, "source", ""));
1735
+ const url = stringField(task, "url", stringField(raw, "url", ""));
1736
+ const number = numberField(task, "number") ?? numberField(raw, "number");
1737
+ const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
1738
+ const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
1739
+ const readiness = compactValue(task.readiness ?? raw.readiness);
1740
+ const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
1741
+ const rows = [
1742
+ ["task", pc2.bold(id)],
1743
+ ["status", formatStatusPill(status)],
1744
+ ["title", title],
1745
+ ["source", source],
1746
+ ["number", number],
1747
+ ["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
1748
+ ["assignees", assignees.join(", ")],
1749
+ ["readiness", readiness],
1750
+ ["validators", validators],
1751
+ ["url", url]
1752
+ ];
1753
+ return [
1754
+ formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
1755
+ "",
1756
+ ...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
1757
+ ].join(`
1758
+ `);
1759
+ }
1760
+ function formatTaskDetails(task) {
1761
+ return formatTaskCard(task, { title: "Task details" });
1762
+ }
1763
+ function formatSubmittedRun(input) {
1764
+ const rows = [["run", pc2.bold(input.runId)]];
1765
+ if (input.task) {
1766
+ const id = stringField(input.task, "id", "<unknown>");
1767
+ const status = stringField(input.task, "status", "unknown");
1768
+ const title = stringField(input.task, "title", "Untitled task");
1769
+ rows.push(["task", `${pc2.bold(id)} ${formatStatusPill(status)} ${title}`]);
1770
+ }
1771
+ const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
1772
+ rows.push(["runtime", runtime]);
1773
+ return [
1774
+ formatSuccessCard("Run submitted", rows),
1775
+ "",
1776
+ ...formatNextSteps([
1777
+ `Attach: \`rig run attach ${input.runId} --follow\``,
1778
+ `Inspect: \`rig run show ${input.runId}\``,
1779
+ input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the enriched bundled Pi (native UI + Rig layers, worker brain)."
1780
+ ])
1781
+ ].join(`
1782
+ `);
1783
+ }
1784
+
1785
+ // packages/cli/src/commands/inbox.ts
1786
+ async function listInboxRecords(context, kind, filters) {
1787
+ const params = new URLSearchParams;
1788
+ if (filters.run)
1789
+ params.set("runId", filters.run);
1790
+ if (filters.task)
1791
+ params.set("taskId", filters.task);
1792
+ const query = params.size > 0 ? `?${params.toString()}` : "";
1793
+ const payload = await requestServerJson(context, `/api/inbox/${kind}${query}`);
1794
+ const records = Array.isArray(payload) ? payload : [];
1795
+ return filters.pendingOnly ? records.filter((entry) => (entry.status ?? "pending") !== "resolved") : records;
1796
+ }
1797
+ async function readPendingInboxCounts(context) {
1798
+ try {
1799
+ const [approvals, inputs] = await Promise.all([
1800
+ listInboxRecords(context, "approvals", { pendingOnly: true }),
1801
+ listInboxRecords(context, "inputs", { pendingOnly: true })
1802
+ ]);
1803
+ return { approvals: approvals.length, inputs: inputs.length };
1804
+ } catch {
1805
+ return null;
1806
+ }
1807
+ }
1808
+ async function printPendingInboxFooter(context) {
1809
+ if (context.outputMode !== "text")
1810
+ return;
1811
+ const counts = await readPendingInboxCounts(context);
1812
+ if (!counts || counts.approvals === 0 && counts.inputs === 0)
1813
+ return;
1814
+ const parts = [];
1815
+ if (counts.approvals > 0)
1816
+ parts.push(`${counts.approvals} approval${counts.approvals === 1 ? "" : "s"}`);
1817
+ if (counts.inputs > 0)
1818
+ parts.push(`${counts.inputs} input request${counts.inputs === 1 ? "" : "s"}`);
1819
+ console.log(`
1820
+ \u26A0 ${parts.join(" and ")} pending \u2014 run \`rig inbox\` to review.`);
1821
+ }
1822
+
1823
+ // packages/cli/src/commands/_help-catalog.ts
1824
+ import pc3 from "picocolors";
1825
+ var TOP_LEVEL_SECTIONS = [
1826
+ {
1827
+ title: "Pi console",
1828
+ subtitle: "the operator surface \u2014 every attach opens the run's FULL Pi session",
1829
+ commands: [
1830
+ { command: "rig run attach <run-id>", description: "Open the run's Pi console: complete transcript (live AND finished runs), worker turns streaming in live." },
1831
+ { command: "type a message", description: "Inside the console, plain text steers the worker mid-turn \u2014 it lands in the agent's context, not a local model." },
1832
+ { command: "!<command>", description: "Inside the console, runs shell in the WORKER's workspace; output streams back into the transcript." },
1833
+ { command: "/<command>", description: "The palette includes the WORKER session's slash commands ([worker]-tagged) next to /rig." },
1834
+ { command: "/rig abort | /rig stop", description: "Abort the worker's current turn, or stop the whole run, from inside the console." },
1835
+ { command: "rig run steer <id> --message <text>", description: "Steer without attaching \u2014 queue a message; the worker picks it up within seconds." }
1836
+ ]
1837
+ },
1838
+ {
1839
+ title: "Start here",
1840
+ subtitle: "one-time setup, pick a server",
1841
+ commands: [
1842
+ { command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
1843
+ { command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." },
1844
+ { command: "rig server status", description: "Show the selected server for this repo." }
1845
+ ]
1846
+ },
1847
+ {
1848
+ title: "Work",
1849
+ subtitle: "find a task, put an agent on it, answer what it asks",
1850
+ commands: [
1851
+ { command: "rig task list", description: "What's on the board (from the selected source/server)." },
1852
+ { command: "rig task run --next", description: "Dispatch an agent on the next ready task; interactive mode drops you into its Pi console." },
1853
+ { command: "rig run status", description: "Active and recent runs at a glance." },
1854
+ { command: "rig run attach <id> --follow", description: "Same as plain attach \u2014 the Pi console is always the interactive surface." },
1855
+ { command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." }
1856
+ ]
1857
+ },
1858
+ {
1859
+ title: "Watch",
1860
+ subtitle: "fleet metrics and per-task forensics",
1861
+ commands: [
1862
+ { command: "rig stats [--since 7d]", description: "Fleet metrics: completion/failure rates, median run time, steering, stalls." },
1863
+ { command: "rig inspect logs --task <id>", description: "Latest run log for a task." },
1864
+ { command: "rig inspect diff --task <id>", description: "Changed files for a task." }
1865
+ ]
1866
+ },
1867
+ {
1868
+ title: "Unblock",
1869
+ subtitle: "diagnose wiring, fix auth",
1870
+ commands: [
1871
+ { command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
1872
+ { command: "rig github auth status", description: "GitHub auth state on the selected server." }
1873
+ ]
1874
+ },
1875
+ {
1876
+ title: "Extend",
1877
+ subtitle: "plugins contribute validators, hooks, task sources, commands",
1878
+ commands: [
1879
+ { command: "rig plugin list", description: "What the rig.config.ts plugins contribute." },
1880
+ { command: "rig plugin run <command-id>", description: "Execute a plugin-contributed CLI command." }
1881
+ ]
1882
+ }
1883
+ ];
1884
+ var PRIMARY_GROUPS = [
1885
+ {
1886
+ name: "server",
1887
+ summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
1888
+ usage: ["rig server <status|list|add|use|start> [options]"],
1889
+ commands: [
1890
+ { command: "status", description: "Show the selected server for this repo.", primary: true },
1891
+ { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
1892
+ { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
1893
+ { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
1894
+ { command: "list", description: "List saved local/remote server aliases.", primary: true },
1895
+ { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
1896
+ ],
1897
+ examples: [
1898
+ "rig server status",
1899
+ "rig server add prod https://where.rig-does.work",
1900
+ "rig server use prod",
1901
+ "rig server use local",
1902
+ "rig server start --port 3773"
1903
+ ],
1904
+ next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."]
1905
+ },
1906
+ {
1907
+ name: "task",
1908
+ summary: "Find work, start Pi-backed runs, and validate task results.",
1909
+ usage: ["rig task <list|next|show|run> [options]"],
1910
+ commands: [
1911
+ { command: "list [--assignee <login|me|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
1912
+ { command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
1913
+ { command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
1914
+ { command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
1915
+ { command: "ready", description: "List task IDs that are runnable now." },
1916
+ { command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
1917
+ { command: "details --task <id>", description: "Show full task info from the configured source." },
1918
+ { command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
1919
+ { command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
1920
+ { command: "report-bug", description: "Create a structured bug report/task." }
1921
+ ],
1922
+ examples: [
1923
+ "rig task list --assignee @me --limit 20",
1924
+ "rig task next",
1925
+ "rig task show 123 --raw",
1926
+ "rig task run --next",
1927
+ "rig task run #123 --runtime-adapter pi",
1928
+ "rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
1929
+ ],
1930
+ next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
1931
+ },
1932
+ {
1933
+ name: "run",
1934
+ summary: "Observe, attach to, and control Rig runs. `attach` opens the Pi console \u2014 the full worker session, live.",
1935
+ usage: ["rig run <list|status|show|attach|steer|stop|resume|restart> [options]"],
1936
+ commands: [
1937
+ { command: "list", description: "List recent runs from the selected server or local state.", primary: true },
1938
+ { command: "status", description: "Render active and recent run groups.", primary: true },
1939
+ { command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
1940
+ { command: "attach <run-id>|--run <id>", description: "Open the run's Pi console \u2014 see 'Inside the console' below. Works on live AND finished runs.", primary: true },
1941
+ { command: "steer <run-id> --message <text>", description: "Queue a steering message into a live worker without attaching \u2014 delivered into the agent's context within seconds.", primary: true },
1942
+ { command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
1943
+ { command: "resume [<run-id>]", description: "Resume an interrupted run on the selected server (defaults to the most recent resumable)." },
1944
+ { command: "restart [<run-id>]", description: "Re-dispatch a run from a clean runtime, reopening its Pi session where possible." },
1945
+ { command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events (scripts; humans should attach)." },
1946
+ { command: "replay <run-id>|--run <id> [--with-session]", description: "Print the run's consolidated run.jsonl as a merged timeline; --with-session interleaves the Pi session log." },
1947
+ { command: "delete|cleanup", description: "Remove completed run records/artifacts." }
1948
+ ],
1949
+ examples: [
1950
+ "rig run attach <run-id> # full session console \u2014 live mirror, steering, worker shell",
1951
+ "rig run steer <run-id> --message 'focus on the failing test first'",
1952
+ "rig run list",
1953
+ "rig run show <run-id>",
1954
+ "rig run stop <run-id>"
1955
+ ],
1956
+ next: [
1957
+ "Inside the console: the run's COMPLETE transcript loads on open (finished runs too), and new worker turns stream in live.",
1958
+ "Inside the console: plain text = steering into the worker's context \xB7 !<cmd> = shell in the WORKER workspace \xB7 /<cmd> includes the worker session's commands \xB7 /rig abort stops the current turn.",
1959
+ "The console is read-write but remote-only: nothing runs on your machine; the worker keeps running when you exit.",
1960
+ "Use `rig task run --next` to create a new run; interactive mode drops you straight into its console.",
1961
+ "Use `--json` when scripts need the full structured record."
1962
+ ]
1963
+ },
1964
+ {
1965
+ name: "inbox",
1966
+ summary: "Review approval and user-input requests that block worker runs.",
1967
+ usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
1968
+ commands: [
1969
+ { command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
1970
+ { command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
1971
+ { command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
1972
+ { command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
1973
+ ],
1974
+ examples: [
1975
+ "rig inbox approvals",
1976
+ "rig inbox inputs --run <run-id>",
1977
+ "rig inbox approve --run <run-id> --request <request-id> --decision approve"
1978
+ ],
1979
+ next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
1980
+ },
1981
+ {
1982
+ name: "stats",
1983
+ summary: "Fleet metrics computed from on-disk run journals (no server required).",
1984
+ usage: ["rig stats [show] [--since <7d|30d|ISO date>]"],
1985
+ commands: [
1986
+ { command: "show [--since <window>]", description: "Total runs, completion/failure/needs-attention rates, median run time, steering, stalls, approvals.", primary: true }
1987
+ ],
1988
+ examples: [
1989
+ "rig stats",
1990
+ "rig stats --since 7d",
1991
+ "rig stats --since 2026-06-01 --json"
1992
+ ],
1993
+ next: ["Inspect outliers with `rig run list` and `rig run show <run-id>`.", "Use `--json` for the schema'd envelope (see docs/cli-json.md)."]
1994
+ },
1995
+ {
1996
+ name: "inspect",
1997
+ summary: "Inspect logs, artifacts, graphs, failures for a task.",
1998
+ usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
1999
+ commands: [
2000
+ { command: "logs --task <id>", description: "Latest run log for a task (local or selected server).", primary: true },
2001
+ { command: "artifacts --task <id>", description: "List the task's completion artifacts.", primary: true },
2002
+ { command: "failures --task <id>", description: "Recorded failures for a task.", primary: true },
2003
+ { command: "diff --task <id>", description: "Changed files for a task.", primary: true },
2004
+ { command: "graph", description: "Task dependency graph." },
2005
+ { command: "audit", description: "Controlled-command audit trail." }
2006
+ ],
2007
+ examples: ["rig inspect logs --task <id>", "rig inspect diff --task <id>"],
2008
+ next: ["Use `rig stats` for fleet-level metrics across runs."]
2009
+ },
2010
+ {
2011
+ name: "repo",
2012
+ summary: "Repository sync/baseline helpers for the Rig-managed checkout.",
2013
+ usage: ["rig repo <sync|reset-baseline>"],
2014
+ commands: [
2015
+ { command: "sync", description: "Sync project repository state.", primary: true },
2016
+ { command: "reset-baseline", description: "Reset the managed baseline for the repo." }
2017
+ ],
2018
+ examples: ["rig repo sync"]
2019
+ },
2020
+ {
2021
+ name: "plugin",
2022
+ summary: "Plugin listing, validation, and plugin-contributed commands.",
2023
+ usage: ["rig plugin <list|validate|run> [options]"],
2024
+ commands: [
2025
+ { command: "list", description: "List plugins declared in rig.config.ts and their contributions.", primary: true },
2026
+ { command: "validate --task <id>", description: "Run plugin-contributed validators for a task.", primary: true },
2027
+ { command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
2028
+ ],
2029
+ examples: ["rig plugin list", "rig plugin run <command-id>"]
2030
+ },
2031
+ {
2032
+ name: "init",
2033
+ summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
2034
+ usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
2035
+ commands: [
2036
+ { command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
2037
+ { command: "init --demo", description: "Offline demo project: files task source + 3 sample tasks, zero GitHub.", primary: true },
2038
+ { command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
2039
+ { command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
2040
+ { command: "init --repair", description: "Repair missing private state without replacing project config." }
2041
+ ],
2042
+ examples: [
2043
+ "rig init",
2044
+ "rig init --demo",
2045
+ "rig init --yes --repo humanity-org/humanwork",
2046
+ "rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
2047
+ ],
2048
+ next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
2049
+ },
2050
+ {
2051
+ name: "doctor",
2052
+ summary: "Diagnostics for project/server/GitHub/Pi state.",
2053
+ usage: ["rig doctor"],
2054
+ commands: [
2055
+ { command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
2056
+ { command: "check", description: "Compatibility spelling for diagnostics." }
2057
+ ],
2058
+ examples: ["rig doctor", "rig doctor --json"],
2059
+ next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
2060
+ },
2061
+ {
2062
+ name: "github",
2063
+ summary: "GitHub auth helpers for the selected Rig server.",
2064
+ usage: ["rig github auth <status|import-gh|token>"],
2065
+ commands: [
2066
+ { command: "auth status", description: "Show GitHub auth state.", primary: true },
2067
+ { command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
2068
+ { command: "auth token --token <token>", description: "Store a token on the selected server." }
2069
+ ],
2070
+ examples: ["rig github auth status", "rig github auth import-gh"],
2071
+ next: ["After auth is valid, use `rig task run --next`."]
2072
+ }
2073
+ ];
2074
+ var ADVANCED_GROUPS = [
2075
+ { name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
2076
+ { name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
2077
+ {
2078
+ name: "review",
2079
+ summary: "Inspect or change completion review gate policy.",
2080
+ usage: ["rig review <show|set>"],
2081
+ commands: [
2082
+ { command: "show", description: "Show current review gate settings." },
2083
+ { command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider." }
2084
+ ],
2085
+ examples: ["rig review show", "rig review set required --provider greptile"],
2086
+ next: ["Use `rig inbox approvals` for blocked run handoffs."]
2087
+ },
2088
+ {
2089
+ name: "browser",
2090
+ summary: "Browser/app diagnostics for browser-required tasks.",
2091
+ usage: ["rig browser <help|explain|demo|app|hp-next> [options]"],
2092
+ commands: [
2093
+ { command: "help", description: "Rich browser command help (canonical: `rig browser help`)." },
2094
+ { command: "explain", description: "Explain the browser-required task contract." },
2095
+ { command: "demo", description: "Run browser demo flows against a local page." },
2096
+ { command: "app", description: "Launch the Rig Browser workstation app." },
2097
+ { command: "hp-next <dev|check|e2e|reset>", description: "Drive the hp-next browser test harness." }
2098
+ ]
2099
+ },
2100
+ {
2101
+ name: "pi",
2102
+ summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
2103
+ usage: ["rig pi <list|add|remove|search> [args]"],
2104
+ commands: [
2105
+ { command: "list", description: "Show project and user Pi extension packages." },
2106
+ { command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
2107
+ { command: "remove <source>", description: "Remove an operator-added Pi extension." },
2108
+ { command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
2109
+ ],
2110
+ examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
2111
+ next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
2112
+ },
2113
+ { name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
2114
+ { name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
2115
+ { name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
2116
+ { name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
2117
+ { name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
2118
+ { name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
2119
+ { name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
2120
+ { name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
2121
+ { name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
2122
+ ];
2123
+ var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
2124
+ function heading(title) {
2125
+ return pc3.bold(pc3.cyan(title));
2126
+ }
2127
+ function commandLine(command, description) {
2128
+ const commandColumn = command.length >= 38 ? `${command} ` : command.padEnd(38);
2129
+ return `${pc3.dim("\u2502")} ${pc3.bold(commandColumn)} ${description}`;
2130
+ }
2131
+ function renderCommandBlock(commands) {
2132
+ return commands.map((entry) => commandLine(entry.command, entry.description)).join(`
2133
+ `);
2134
+ }
2135
+ function renderGroup(group) {
2136
+ const lines = [
2137
+ `${heading(`rig ${group.name}`)} \u2014 ${group.summary}`,
2138
+ "",
2139
+ pc3.bold("Usage"),
2140
+ ...group.usage.map((line) => ` ${line}`),
2141
+ "",
2142
+ pc3.bold("Commands"),
2143
+ ...group.commands.map((entry) => commandLine(entry.command, entry.description))
2144
+ ];
2145
+ if (group.examples?.length) {
2146
+ lines.push("", pc3.bold("Examples"), ...group.examples.map((line) => ` ${pc3.dim("$")} ${line}`));
2147
+ }
2148
+ if (group.next?.length) {
2149
+ lines.push("", pc3.bold("Next steps"), ...group.next.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
2150
+ }
2151
+ if (group.advanced?.length) {
2152
+ lines.push("", pc3.bold("Compatibility / advanced"), ...group.advanced.map((line) => ` ${pc3.dim("\u203A")} ${line}`));
2153
+ }
2154
+ return lines.join(`
2155
+ `);
2156
+ }
2157
+ function renderTopLevelHelp() {
2158
+ return [
2159
+ `${heading("rig")} ${pc3.dim("\u2014 server-owned task/run control plane for Pi-backed engineering work")}`,
2160
+ pc3.dim("The loop: pick a task, dispatch an agent, open its Pi console (`rig run attach <id>`) to watch and steer it live, clear inbox gates, merge."),
2161
+ "",
2162
+ ...TOP_LEVEL_SECTIONS.flatMap((section) => [
2163
+ `${pc3.bold(pc3.magenta(`\u25C7 ${section.title}`))} \u2014 ${pc3.dim(section.subtitle)}`,
2164
+ renderCommandBlock(section.commands),
2165
+ ""
2166
+ ]),
2167
+ pc3.dim("More: `rig help --advanced` for dev/compatibility commands; `rig <group> --help` for rich per-group help; `rig --version` for the installed version."),
2168
+ "",
2169
+ pc3.bold("Global options"),
2170
+ commandLine("--project <path>", "Use a project root instead of auto-discovery."),
2171
+ commandLine("--json", "Emit structured output for scripts/agents."),
2172
+ commandLine("--dry-run", "Print the command plan without mutating state.")
2173
+ ].join(`
2174
+ `).trimEnd();
2175
+ }
2176
+ function renderGroupHelp(groupName) {
2177
+ const group = ALL_GROUPS.find((candidate) => candidate.name === groupName);
2178
+ return group ? renderGroup(group) : null;
2179
+ }
2180
+ function printGroupHelpDocument(groupName) {
2181
+ console.log(renderGroupHelp(groupName) ?? renderTopLevelHelp());
2182
+ }
2183
+
852
2184
  // packages/cli/src/commands/task.ts
853
2185
  import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
854
2186
  import { loadConfig } from "@rig/core/load-config";
@@ -859,7 +2191,7 @@ async function readStdin() {
859
2191
  }
860
2192
  return Buffer.concat(chunks).toString("utf-8");
861
2193
  }
862
- function normalizeAssignedToAlias(value) {
2194
+ function normalizeAssigneeAlias(value) {
863
2195
  if (!value)
864
2196
  return;
865
2197
  return value.trim().toLowerCase() === "me" ? "@me" : value;
@@ -868,25 +2200,19 @@ function parseTaskFilters(args) {
868
2200
  let pending = args;
869
2201
  const assigneeResult = takeOption(pending, "--assignee");
870
2202
  pending = assigneeResult.rest;
871
- const assignedToResult = takeOption(pending, "--assigned-to");
872
- pending = assignedToResult.rest;
873
2203
  const stateResult = takeOption(pending, "--state");
874
2204
  pending = stateResult.rest;
875
2205
  const statusResult = takeOption(pending, "--status");
876
2206
  pending = statusResult.rest;
877
2207
  const limitResult = takeOption(pending, "--limit");
878
2208
  pending = limitResult.rest;
879
- const normalizedAssignedTo = normalizeAssignedToAlias(assignedToResult.value);
880
- if (assigneeResult.value && normalizedAssignedTo && assigneeResult.value !== normalizedAssignedTo) {
881
- throw new CliError2("--assignee and --assigned-to cannot specify different assignees.", 2);
882
- }
883
- const assignee = normalizedAssignedTo ?? assigneeResult.value;
2209
+ const assignee = normalizeAssigneeAlias(assigneeResult.value);
884
2210
  const limit = (() => {
885
2211
  if (!limitResult.value)
886
2212
  return;
887
2213
  const parsed = Number.parseInt(limitResult.value, 10);
888
2214
  if (!Number.isFinite(parsed) || parsed < 1) {
889
- throw new CliError2("--limit must be a positive integer.", 2);
2215
+ throw new CliError("--limit must be a positive integer.", 2, { hint: "Re-run with a positive number, e.g. `rig task list --limit 20`." });
890
2216
  }
891
2217
  return parsed;
892
2218
  })();
@@ -921,10 +2247,10 @@ function normalizePrMode(value) {
921
2247
  return;
922
2248
  if (value === "auto" || value === "ask" || value === "off")
923
2249
  return value;
924
- throw new CliError2("--pr must be auto, ask, or off.", 2);
2250
+ throw new CliError("--pr must be auto, ask, or off.", 2, { hint: "Re-run with `--pr auto|ask|off`, or pass `--no-pr` to disable the PR." });
925
2251
  }
926
2252
  function detectLocalDirtyState(projectRoot) {
927
- const result = spawnSync2("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
2253
+ const result = spawnSync("git", ["-C", projectRoot, "status", "--porcelain"], { encoding: "utf8", timeout: 5000 });
928
2254
  if (result.status !== 0)
929
2255
  return { dirty: false, modified: 0, untracked: 0, lines: [] };
930
2256
  const lines = result.stdout.split(/\r?\n/).map((line) => line.trimEnd()).filter(Boolean);
@@ -944,7 +2270,7 @@ function selectedServerKind(projectRoot) {
944
2270
  }
945
2271
  async function resolveDirtyBaselineForTaskRun(context, explicit) {
946
2272
  if (explicit && explicit !== "head" && explicit !== "dirty-snapshot") {
947
- throw new CliError2("--dirty-baseline must be head or dirty-snapshot.", 2);
2273
+ throw new CliError("--dirty-baseline must be head or dirty-snapshot.", 2, { hint: "Re-run with `--dirty-baseline head` or `--dirty-baseline dirty-snapshot`." });
948
2274
  }
949
2275
  if (selectedServerKind(context.projectRoot) !== "local") {
950
2276
  return { mode: explicit === "dirty-snapshot" ? "dirty-snapshot" : "head", state: null };
@@ -958,13 +2284,15 @@ async function resolveDirtyBaselineForTaskRun(context, explicit) {
958
2284
  if (explicit)
959
2285
  return { mode: explicit, state };
960
2286
  if (context.outputMode === "text" && process.stdin.isTTY && process.stdout.isTTY) {
961
- const rl = createInterface3({ input: process.stdin, output: process.stdout });
962
- try {
963
- const answer = (await rl.question("Include current uncommitted changes in run baseline? [y/N] ")).trim().toLowerCase();
964
- return { mode: answer === "y" || answer === "yes" ? "dirty-snapshot" : "head", state };
965
- } finally {
966
- rl.close();
2287
+ const answer = await droneConfirm({
2288
+ message: "Include current uncommitted changes in run baseline?",
2289
+ initialValue: false
2290
+ });
2291
+ if (answer === null) {
2292
+ droneCancel("Run cancelled.");
2293
+ throw new CliError("Run cancelled by user.", 1);
967
2294
  }
2295
+ return { mode: answer ? "dirty-snapshot" : "head", state };
968
2296
  }
969
2297
  return { mode: "head", state };
970
2298
  }
@@ -998,38 +2326,31 @@ function summarizeTask(task, options = {}) {
998
2326
  ...options.raw ? { raw: raw ?? task } : {}
999
2327
  };
1000
2328
  }
1001
- function printTaskSummary(task) {
1002
- const id = readTaskId(task) ?? "<unknown>";
1003
- const title = readTaskString(task, "title") ?? "Untitled task";
1004
- const status = readTaskString(task, "status") ?? "unknown";
1005
- console.log(`- ${id} \xB7 ${status} \xB7 ${title}`);
1006
- }
1007
2329
  async function validatorRegistryForTaskCommands(projectRoot) {
1008
2330
  return buildPluginHostContext(projectRoot).then((ctx) => ctx?.validatorRegistry ?? undefined).catch(() => {
1009
2331
  return;
1010
2332
  });
1011
2333
  }
1012
2334
  async function executeTask(context, args, options) {
1013
- const [command = "info", ...rest] = args;
2335
+ if (args.length === 0) {
2336
+ if (context.outputMode === "text") {
2337
+ printGroupHelpDocument("task");
2338
+ }
2339
+ return { ok: true, group: "task", command: "help" };
2340
+ }
2341
+ const [command = "help", ...rest] = args;
1014
2342
  switch (command) {
1015
2343
  case "list": {
1016
2344
  let pending = rest;
1017
2345
  const rawResult = takeFlag(pending, "--raw");
1018
2346
  pending = rawResult.rest;
1019
2347
  const { filters, rest: remaining } = parseTaskFilters(pending);
1020
- requireNoExtraArgs(remaining, "bun run rig task list [--raw] [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1021
- const tasks = await listWorkspaceTasksViaServer(context, filters);
2348
+ requireNoExtraArgs(remaining, "rig task list [--raw] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
2349
+ const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filters), { outputMode: context.outputMode });
1022
2350
  if (context.outputMode === "text") {
1023
- if (tasks.length === 0) {
1024
- console.log("No matching tasks.");
1025
- } else {
1026
- for (const task of tasks) {
1027
- if (rawResult.value)
1028
- console.log(JSON.stringify(summarizeTask(task, { raw: true })));
1029
- else
1030
- printTaskSummary(task);
1031
- }
1032
- }
2351
+ const renderedTasks = rawResult.value ? tasks.map((task) => summarizeTask(task, { raw: true })) : tasks.map((task) => summarizeTask(task));
2352
+ printFormattedOutput(formatTaskList(renderedTasks, { raw: rawResult.value }));
2353
+ await printPendingInboxFooter(context);
1033
2354
  }
1034
2355
  return {
1035
2356
  ok: true,
@@ -1039,30 +2360,34 @@ async function executeTask(context, args, options) {
1039
2360
  };
1040
2361
  }
1041
2362
  case "show": {
1042
- const taskOption = takeOption(rest, "--task");
2363
+ let pending = rest;
2364
+ const rawResult = takeFlag(pending, "--raw");
2365
+ pending = rawResult.rest;
2366
+ const taskOption = takeOption(pending, "--task");
1043
2367
  const positional = taskOption.rest.length > 0 && taskOption.rest[0] && !taskOption.rest[0].startsWith("-") ? taskOption.rest[0] : undefined;
1044
2368
  const remaining = positional ? taskOption.rest.slice(1) : taskOption.rest;
1045
- requireNoExtraArgs(remaining, "bun run rig task show <id>|--task <id>");
1046
- const taskId2 = normalizeTaskRunTaskId(taskOption.value ?? positional);
1047
- if (!taskId2)
1048
- throw new CliError2("task show requires a task id.", 2);
1049
- const task = await getWorkspaceTaskViaServer(context, taskId2);
2369
+ requireNoExtraArgs(remaining, "rig task show <id>|--task <id> [--raw]");
2370
+ const taskId3 = normalizeTaskRunTaskId(taskOption.value ?? positional);
2371
+ if (!taskId3)
2372
+ throw new CliError("task show requires a task id.", 2, { hint: "Run `rig task list` to find ids, then `rig task show <id>`." });
2373
+ const task = await withSpinner(`Reading task ${taskId3} from server\u2026`, () => getWorkspaceTaskViaServer(context, taskId3), { outputMode: context.outputMode });
1050
2374
  if (!task)
1051
- throw new CliError2(`Task not found: ${taskId2}`, 3);
2375
+ throw new CliError(`Task not found: ${taskId3}`, 3, { hint: "Run `rig task list` to see available tasks." });
1052
2376
  const summary = summarizeTask(task, { raw: true });
1053
- if (context.outputMode === "text")
1054
- console.log(JSON.stringify(summary, null, 2));
1055
- return { ok: true, group: "task", command, details: { task: summary } };
2377
+ if (context.outputMode === "text") {
2378
+ printFormattedOutput(rawResult.value ? JSON.stringify(summary, null, 2) : formatTaskDetails(summary));
2379
+ }
2380
+ return { ok: true, group: "task", command, details: { task: summary, raw: rawResult.value } };
1056
2381
  }
1057
2382
  case "next": {
1058
2383
  const { filters, rest: remaining } = parseTaskFilters(rest);
1059
- requireNoExtraArgs(remaining, "bun run rig task next [--assignee <login|@me>] [--assigned-to <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
1060
- const selected = await selectNextWorkspaceTaskViaServer(context, filters);
2384
+ requireNoExtraArgs(remaining, "rig task next [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>]");
2385
+ const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filters), { outputMode: context.outputMode });
1061
2386
  if (context.outputMode === "text") {
1062
2387
  if (selected.task) {
1063
- printTaskSummary(selected.task);
2388
+ printFormattedOutput(formatTaskCard(summarizeTask(selected.task, { raw: true }), { title: "Selected task", selected: true }));
1064
2389
  } else {
1065
- console.log("No matching tasks.");
2390
+ printFormattedOutput("No matching tasks.\n\nNext\n\u203A Try `rig task list` to inspect available work.\n\u203A Check server: `rig server status`");
1066
2391
  }
1067
2392
  }
1068
2393
  return {
@@ -1078,31 +2403,31 @@ async function executeTask(context, args, options) {
1078
2403
  }
1079
2404
  case "info": {
1080
2405
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1081
- requireNoExtraArgs(remaining, "bun run rig task info [--task <beads-id>]");
2406
+ requireNoExtraArgs(remaining, "rig task info [--task <task-id>]");
1082
2407
  await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, task || undefined));
1083
2408
  return { ok: true, group: "task", command, details: { task: task || null } };
1084
2409
  }
1085
2410
  case "scope": {
1086
2411
  const filesFlag = takeFlag(rest, "--files");
1087
2412
  const { value: task, rest: remaining } = takeOption(filesFlag.rest, "--task");
1088
- requireNoExtraArgs(remaining, "bun run rig task scope [--task <id>] [--files]");
2413
+ requireNoExtraArgs(remaining, "rig task scope [--task <id>] [--files]");
1089
2414
  await withMutedConsole(context.outputMode === "json", () => taskScope(context.projectRoot, filesFlag.value, task || undefined));
1090
2415
  return { ok: true, group: "task", command, details: { files: filesFlag.value, task: task || null } };
1091
2416
  }
1092
2417
  case "deps":
1093
- requireNoExtraArgs(rest, "bun run rig task deps");
2418
+ requireNoExtraArgs(rest, "rig task deps");
1094
2419
  await withMutedConsole(context.outputMode === "json", () => taskDeps(context.projectRoot));
1095
2420
  return { ok: true, group: "task", command };
1096
2421
  case "status":
1097
- requireNoExtraArgs(rest, "bun run rig task status");
2422
+ requireNoExtraArgs(rest, "rig task status");
1098
2423
  withMutedConsole(context.outputMode === "json", () => taskStatus2(context.projectRoot));
1099
2424
  return { ok: true, group: "task", command };
1100
2425
  case "artifacts":
1101
- requireNoExtraArgs(rest, "bun run rig task artifacts");
2426
+ requireNoExtraArgs(rest, "rig task artifacts");
1102
2427
  withMutedConsole(context.outputMode === "json", () => taskArtifacts(context.projectRoot));
1103
2428
  return { ok: true, group: "task", command };
1104
2429
  case "artifact-dir": {
1105
- requireNoExtraArgs(rest, "bun run rig task artifact-dir");
2430
+ requireNoExtraArgs(rest, "rig task artifact-dir");
1106
2431
  const path = taskArtifactDir(context.projectRoot);
1107
2432
  if (context.outputMode === "text") {
1108
2433
  console.log(path);
@@ -1111,7 +2436,7 @@ async function executeTask(context, args, options) {
1111
2436
  }
1112
2437
  case "artifact-write": {
1113
2438
  if (rest.length < 1) {
1114
- throw new CliError2(`Usage: bun run rig task artifact-write <filename> [--file <path>]
2439
+ throw new CliError(`Usage: rig task artifact-write <filename> [--file <path>]
1115
2440
  ` + ` Reads content from stdin (or --file), writes to the active task artifact dir.
1116
2441
  ` + " Example: echo '...' | rig task artifact-write collection-audit.md");
1117
2442
  }
@@ -1119,12 +2444,12 @@ async function executeTask(context, args, options) {
1119
2444
  const fileFlag = takeOption(rest.slice(1), "--file");
1120
2445
  let content;
1121
2446
  if (fileFlag.value) {
1122
- content = readFileSync4(resolve4(context.projectRoot, fileFlag.value), "utf-8");
2447
+ content = readFileSync4(resolve3(context.projectRoot, fileFlag.value), "utf-8");
1123
2448
  } else {
1124
2449
  content = await readStdin();
1125
2450
  }
1126
2451
  if (!artifactFilename) {
1127
- throw new CliError2("Usage: bun run rig task artifact-write <filename> [--file path]");
2452
+ throw new CliError("Usage: rig task artifact-write <filename> [--file path]");
1128
2453
  }
1129
2454
  withMutedConsole(context.outputMode === "json", () => taskArtifactWrite(context.projectRoot, artifactFilename, content));
1130
2455
  return { ok: true, group: "task", command, details: { filename: artifactFilename } };
@@ -1133,11 +2458,11 @@ async function executeTask(context, args, options) {
1133
2458
  return options.executeTaskReportBug(context, rest);
1134
2459
  case "lookup": {
1135
2460
  if (rest.length !== 1) {
1136
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
2461
+ throw new CliError("Usage: rig task lookup <task-id>");
1137
2462
  }
1138
2463
  const lookupId = rest[0];
1139
2464
  if (!lookupId) {
1140
- throw new CliError2("Usage: bun run rig task lookup <beads-id>");
2465
+ throw new CliError("Usage: rig task lookup <task-id>");
1141
2466
  }
1142
2467
  const result = taskLookup(context.projectRoot, lookupId);
1143
2468
  if (context.outputMode === "text") {
@@ -1147,17 +2472,17 @@ async function executeTask(context, args, options) {
1147
2472
  }
1148
2473
  case "record": {
1149
2474
  if (rest.length < 2) {
1150
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
2475
+ throw new CliError("Usage: rig task record <decision|failure> <text>");
1151
2476
  }
1152
2477
  const type = rest[0];
1153
2478
  if (type !== "decision" && type !== "failure") {
1154
- throw new CliError2("Usage: bun run rig task record <decision|failure> <text>");
2479
+ throw new CliError("Usage: rig task record <decision|failure> <text>");
1155
2480
  }
1156
2481
  withMutedConsole(context.outputMode === "json", () => taskRecord(context.projectRoot, type, rest.slice(1).join(" ")));
1157
2482
  return { ok: true, group: "task", command, details: { type: rest[0] } };
1158
2483
  }
1159
2484
  case "ready":
1160
- requireNoExtraArgs(rest, "bun run rig task ready");
2485
+ requireNoExtraArgs(rest, "rig task ready");
1161
2486
  await withMutedConsole(context.outputMode === "json", () => taskReady(context.projectRoot));
1162
2487
  return { ok: true, group: "task", command };
1163
2488
  case "run": {
@@ -1194,47 +2519,47 @@ async function executeTask(context, args, options) {
1194
2519
  if (positionalTaskId) {
1195
2520
  pending = pending.slice(1);
1196
2521
  }
1197
- 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]");
2522
+ requireNoExtraArgs(pending, "rig task run [#<issue>|<task-id>] [--next] [--task <id>] [--detach] [--assignee <login|me|@me>] [--state open|closed] [--status <status>] [--limit <n>] [--title <text>] [--runtime-adapter claude-code|codex|pi] [--model <model>] [--runtime-mode <mode>] [--interaction-mode <mode>] [--initial-prompt <text>] [--pr auto|ask|off] [--no-pr] [--dirty-baseline head|dirty-snapshot] [--skip-project-sync]");
1198
2523
  if (nextResult.value && (taskResult.value || positionalTaskId)) {
1199
- throw new CliError2("task run cannot combine --next with an explicit task id.", 2);
2524
+ throw new CliError("task run cannot combine --next with an explicit task id.", 2, { hint: "Use either `rig task run --next` or `rig task run <id>`." });
1200
2525
  }
1201
2526
  if (taskResult.value && positionalTaskId) {
1202
- throw new CliError2("task run cannot combine positional task id with --task <id>.", 2);
2527
+ throw new CliError("task run cannot combine positional task id with --task <id>.", 2, { hint: "Pass the id once, e.g. `rig task run <id>`." });
1203
2528
  }
1204
2529
  if (prResult.value && noPrResult.value) {
1205
- throw new CliError2("task run cannot combine --pr with --no-pr.", 2);
2530
+ throw new CliError("task run cannot combine --pr with --no-pr.", 2, { hint: "Use `--pr auto|ask|off` or `--no-pr`, not both." });
1206
2531
  }
1207
2532
  let selectedTask = null;
1208
2533
  let selectedTaskId = normalizeTaskRunTaskId(taskResult.value) ?? positionalTaskId;
1209
2534
  if (nextResult.value) {
1210
- const selected = await selectNextWorkspaceTaskViaServer(context, filterResult.filters);
2535
+ const selected = await withSpinner("Selecting next ready task\u2026", () => selectNextWorkspaceTaskViaServer(context, filterResult.filters), { outputMode: context.outputMode });
1211
2536
  selectedTask = selected.task;
1212
2537
  selectedTaskId = selected.task ? readTaskId(selected.task) : null;
1213
2538
  if (!selectedTaskId) {
1214
- throw new CliError2("No matching task found for task run --next.", 3);
2539
+ throw new CliError("No matching task found for task run --next.", 3, { hint: "Run `rig task list` to inspect available work, or relax the filters." });
1215
2540
  }
1216
2541
  }
1217
2542
  if (!selectedTaskId && !initialPromptResult.value && !titleResult.value) {
1218
2543
  if (context.outputMode !== "text" || !process.stdin.isTTY || !process.stdout.isTTY) {
1219
- 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);
2544
+ throw new CliError("task run requires an interactive terminal to pick a task; pass --next, --task <id>, or --initial-prompt/--title for an ad hoc run.", 2);
1220
2545
  }
1221
- const tasks = await listWorkspaceTasksViaServer(context, filterResult.filters);
2546
+ const tasks = await withSpinner("Reading tasks from server\u2026", () => listWorkspaceTasksViaServer(context, filterResult.filters), { outputMode: context.outputMode });
1222
2547
  selectedTask = await selectTaskWithTextPicker(tasks);
1223
2548
  selectedTaskId = selectedTask ? readTaskId(selectedTask) : null;
1224
2549
  if (!selectedTaskId) {
1225
- throw new CliError2("No task selected.", 3);
2550
+ throw new CliError("No task selected.", 3, { hint: "Run `rig task run --next` for the next ready task, or `rig task run --task <id>`." });
1226
2551
  }
1227
2552
  }
1228
2553
  await runProjectMainSyncPreflight(context, { disabled: skipProjectSyncResult.value });
1229
2554
  const projectDefaults = await loadTaskRunProjectDefaults(context.projectRoot);
1230
2555
  const runtimeAdapter = normalizeRuntimeAdapter(runtimeAdapterResult.value ?? projectDefaults.runtimeAdapter);
1231
- await runFastTaskRunPreflight(context, {
2556
+ await withSpinner("Running task-run preflight\u2026", () => runFastTaskRunPreflight(context, {
1232
2557
  taskId: selectedTaskId,
1233
2558
  runtimeAdapter
1234
- });
2559
+ }), { outputMode: context.outputMode });
1235
2560
  const dirtyBaseline = await resolveDirtyBaselineForTaskRun(context, dirtyBaselineResult.value);
1236
2561
  const prMode = noPrResult.value ? "off" : normalizePrMode(prResult.value) ?? projectDefaults.prMode;
1237
- const submitted = await submitTaskRunViaServer(context, {
2562
+ const submitted = await withSpinner("Dispatching run\u2026", () => submitTaskRunViaServer(context, {
1238
2563
  runId: context.runId,
1239
2564
  taskId: selectedTaskId ?? undefined,
1240
2565
  title: titleResult.value ?? undefined,
@@ -1245,19 +2570,27 @@ async function executeTask(context, args, options) {
1245
2570
  initialPrompt: initialPromptResult.value ?? undefined,
1246
2571
  baselineMode: dirtyBaseline.mode,
1247
2572
  prMode
1248
- });
2573
+ }), { outputMode: context.outputMode });
1249
2574
  let attachDetails = null;
1250
2575
  if (!detachResult.value && context.outputMode === "text") {
1251
- console.log(`Run submitted: ${submitted.runId}`);
1252
- if (selectedTask) {
1253
- printTaskSummary(selectedTask);
1254
- }
2576
+ printFormattedOutput(formatSubmittedRun({
2577
+ runId: submitted.runId,
2578
+ task: selectedTask ? summarizeTask(selectedTask) : null,
2579
+ runtimeAdapter,
2580
+ runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2581
+ interactionMode: interactionModeResult.value || "default",
2582
+ detached: false
2583
+ }));
1255
2584
  attachDetails = await attachRunOperatorView(context, { runId: submitted.runId, follow: true });
1256
2585
  } else if (context.outputMode === "text") {
1257
- console.log(`Run submitted: ${submitted.runId}`);
1258
- if (selectedTask) {
1259
- printTaskSummary(selectedTask);
1260
- }
2586
+ printFormattedOutput(formatSubmittedRun({
2587
+ runId: submitted.runId,
2588
+ task: selectedTask ? summarizeTask(selectedTask) : null,
2589
+ runtimeAdapter,
2590
+ runtimeMode: runtimeModeResult.value || projectDefaults.runtimeMode || "full-access",
2591
+ interactionMode: interactionModeResult.value || "default",
2592
+ detached: true
2593
+ }));
1261
2594
  }
1262
2595
  return {
1263
2596
  ok: true,
@@ -1281,41 +2614,34 @@ async function executeTask(context, args, options) {
1281
2614
  }
1282
2615
  case "validate": {
1283
2616
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1284
- requireNoExtraArgs(remaining, "bun run rig task validate [--task <beads-id>]");
2617
+ requireNoExtraArgs(remaining, "rig task validate [--task <task-id>]");
1285
2618
  if (context.dryRun) {
1286
2619
  await context.runCommand(["rig", "task", "validate", ...task ? ["--task", task] : []]);
1287
2620
  return { ok: true, group: "task", command, details: { task: task || "active" } };
1288
2621
  }
1289
2622
  const ok = await withMutedConsole(context.outputMode === "json", async () => taskValidate(context.projectRoot, task || undefined, await validatorRegistryForTaskCommands(context.projectRoot)));
1290
2623
  if (!ok) {
1291
- throw new CliError2(`Validation failed for ${task || "active task"}.`, 2);
2624
+ throw new CliError(`Validation failed for ${task || "active task"}.`, 2, { hint: "Inspect failures with `rig inspect failures --task <id>`, fix, then re-run `rig task validate --task <id>`." });
1292
2625
  }
1293
2626
  return { ok: true, group: "task", command, details: { task: task || "active" } };
1294
2627
  }
1295
2628
  case "verify": {
1296
2629
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1297
- requireNoExtraArgs(remaining, "bun run rig task verify [--task <beads-id>]");
2630
+ requireNoExtraArgs(remaining, "rig task verify [--task <task-id>]");
1298
2631
  if (context.dryRun) {
1299
2632
  await context.runCommand(["rig", "task", "verify", ...task ? ["--task", task] : []]);
1300
2633
  return { ok: true, group: "task", command, details: { task: task || "active" } };
1301
2634
  }
1302
- const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, context.plugins, task || undefined));
2635
+ const ok = await withMutedConsole(context.outputMode === "json", () => taskVerify(context.projectRoot, task || undefined));
1303
2636
  if (!ok) {
1304
- throw new CliError2(`Verification rejected for ${task || "active task"}.`, 2);
2637
+ throw new CliError(`Verification rejected for ${task || "active task"}.`, 2, { hint: "Check `rig inspect logs --task <id>`, address the rejection, then re-run `rig task verify --task <id>`." });
1305
2638
  }
1306
2639
  return { ok: true, group: "task", command, details: { task: task || "active" } };
1307
2640
  }
1308
- case "reset": {
1309
- const { value: task, rest: remaining } = takeOption(rest, "--task");
1310
- requireNoExtraArgs(remaining, "bun run rig task reset --task <beads-id>");
1311
- const requiredTask = requireTask(task, "bun run rig task reset --task <beads-id>");
1312
- await context.runCommand(["br", "--no-db", "update", requiredTask, "--status", "open"]);
1313
- return { ok: true, group: "task", command, details: { task: requiredTask } };
1314
- }
1315
2641
  case "details": {
1316
2642
  const { value: task, rest: remaining } = takeOption(rest, "--task");
1317
- requireNoExtraArgs(remaining, "bun run rig task details --task <beads-id>");
1318
- const requiredTask = requireTask(task, "bun run rig task details --task <beads-id>");
2643
+ requireNoExtraArgs(remaining, "rig task details --task <task-id>");
2644
+ const requiredTask = requireTask(task, "rig task details --task <task-id>");
1319
2645
  await withMutedConsole(context.outputMode === "json", () => taskInfo(context.projectRoot, requiredTask));
1320
2646
  return { ok: true, group: "task", command, details: { task: requiredTask } };
1321
2647
  }
@@ -1323,9 +2649,9 @@ async function executeTask(context, args, options) {
1323
2649
  const { value: task, rest: rest1 } = takeOption(rest, "--task");
1324
2650
  const allFlag = takeFlag(rest1, "--all");
1325
2651
  const { rest: remaining } = takeOption(allFlag.rest, "--reason");
1326
- requireNoExtraArgs(remaining, "bun run rig task reopen [--task <id> | --all] [--reason <text>]");
2652
+ requireNoExtraArgs(remaining, "rig task reopen [--task <id> | --all] [--reason <text>]");
1327
2653
  if (!allFlag.value && !task) {
1328
- throw new CliError2("Usage: bun run rig task reopen [--task <id> | --all] [--reason <text>]");
2654
+ throw new CliError("Usage: rig task reopen [--task <id> | --all] [--reason <text>]");
1329
2655
  }
1330
2656
  const summary = withMutedConsole(context.outputMode === "json", () => taskReopen(context.projectRoot, {
1331
2657
  all: allFlag.value,
@@ -1335,9 +2661,13 @@ async function executeTask(context, args, options) {
1335
2661
  return { ok: true, group: "task", command, details: summary };
1336
2662
  }
1337
2663
  default:
1338
- throw new CliError2(`Unknown task command: ${command}`);
2664
+ if (command === "reset") {
2665
+ throw new CliError("Unknown task command: reset", 1, { hint: "Use `rig task reopen --task <id>`." });
2666
+ }
2667
+ throw new CliError(`Unknown task command: ${command}`, 1, { hint: "Run `rig task --help` to list available task commands." });
1339
2668
  }
1340
2669
  }
1341
2670
  export {
2671
+ loadTaskRunProjectDefaults,
1342
2672
  executeTask
1343
2673
  };