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

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 (118) hide show
  1. package/README.md +18 -19
  2. package/dist/bin/build-rig-binaries.js +22 -10
  3. package/dist/bin/rig.d.ts +71 -1
  4. package/dist/bin/rig.js +15078 -11169
  5. package/dist/config/rig-default-config.yml +5 -0
  6. package/dist/src/app/drone-ui.d.ts +11 -14
  7. package/dist/src/app/drone-ui.js +70 -86
  8. package/dist/src/commands/_async-ui.d.ts +1 -4
  9. package/dist/src/commands/_async-ui.js +9 -111
  10. package/dist/src/commands/_cli-format.d.ts +16 -9
  11. package/dist/src/commands/_cli-format.js +167 -295
  12. package/dist/src/commands/_connection-state.d.ts +11 -1
  13. package/dist/src/commands/_connection-state.js +50 -5
  14. package/dist/src/commands/_doctor-checks.d.ts +0 -6
  15. package/dist/src/commands/_doctor-checks.js +79 -382
  16. package/dist/src/commands/_help-catalog.d.ts +1 -1
  17. package/dist/src/commands/_help-catalog.js +217 -157
  18. package/dist/src/commands/_inprocess-services.d.ts +33 -0
  19. package/dist/src/commands/_inprocess-services.js +102 -0
  20. package/dist/src/commands/_json-output.js +4 -0
  21. package/dist/src/commands/_lazy-reconcile.d.ts +34 -0
  22. package/dist/src/commands/_lazy-reconcile.js +102 -0
  23. package/dist/src/commands/_paths.js +1 -1
  24. package/dist/src/commands/_pi-frontend.d.ts +18 -10
  25. package/dist/src/commands/_pi-frontend.js +37 -715
  26. package/dist/src/commands/_pi-install.js +18 -36
  27. package/dist/src/commands/_policy.d.ts +1 -1
  28. package/dist/src/commands/_policy.js +56 -15
  29. package/dist/src/commands/_run-bridge.d.ts +114 -0
  30. package/dist/src/commands/_run-bridge.js +387 -0
  31. package/dist/src/commands/_run-diagnostics.d.ts +9 -0
  32. package/dist/src/commands/_run-diagnostics.js +51 -0
  33. package/dist/src/commands/_run-driver-helpers.d.ts +8 -81
  34. package/dist/src/commands/_run-driver-helpers.js +79 -283
  35. package/dist/src/commands/_run-projection.d.ts +50 -0
  36. package/dist/src/commands/_run-projection.js +349 -0
  37. package/dist/src/commands/_run-subcommands.d.ts +3 -0
  38. package/dist/src/commands/_run-subcommands.js +31 -0
  39. package/dist/src/commands/_spinner.js +1 -1
  40. package/dist/src/commands/agent.d.ts +1 -1
  41. package/dist/src/commands/agent.js +8559 -239
  42. package/dist/src/commands/dist.d.ts +1 -1
  43. package/dist/src/commands/dist.js +27 -19
  44. package/dist/src/commands/doctor.d.ts +1 -1
  45. package/dist/src/commands/doctor.js +93 -475
  46. package/dist/src/commands/github.d.ts +1 -1
  47. package/dist/src/commands/github.js +113 -387
  48. package/dist/src/commands/inbox.d.ts +22 -24
  49. package/dist/src/commands/inbox.js +420 -691
  50. package/dist/src/commands/init.d.ts +6 -16
  51. package/dist/src/commands/init.js +334 -971
  52. package/dist/src/commands/inspect.d.ts +19 -2
  53. package/dist/src/commands/inspect.js +644 -610
  54. package/dist/src/commands/pi.d.ts +1 -1
  55. package/dist/src/commands/plugin.d.ts +1 -1
  56. package/dist/src/commands/plugin.js +486 -7
  57. package/dist/src/commands/profile-and-review.d.ts +1 -1
  58. package/dist/src/commands/profile-and-review.js +94 -56
  59. package/dist/src/commands/queue.js +1 -21
  60. package/dist/src/commands/remote.d.ts +1 -1
  61. package/dist/src/commands/remote.js +837 -14
  62. package/dist/src/commands/repo-git-harness.d.ts +1 -1
  63. package/dist/src/commands/repo-git-harness.js +57 -14
  64. package/dist/src/commands/run.d.ts +20 -2
  65. package/dist/src/commands/run.js +17579 -1759
  66. package/dist/src/commands/server.d.ts +2 -6
  67. package/dist/src/commands/server.js +141 -723
  68. package/dist/src/commands/setup.d.ts +1 -1
  69. package/dist/src/commands/setup.js +102 -484
  70. package/dist/src/commands/stats.d.ts +13 -10
  71. package/dist/src/commands/stats.js +689 -761
  72. package/dist/src/commands/task-run-driver.d.ts +50 -88
  73. package/dist/src/commands/task-run-driver.js +116 -2717
  74. package/dist/src/commands/task.d.ts +34 -13
  75. package/dist/src/commands/task.js +668 -2523
  76. package/dist/src/commands/test.d.ts +1 -1
  77. package/dist/src/commands/triage.d.ts +11 -0
  78. package/dist/src/commands/triage.js +227 -0
  79. package/dist/src/commands/workspace.d.ts +1 -1
  80. package/dist/src/commands.d.ts +0 -16
  81. package/dist/src/commands.js +16657 -12250
  82. package/dist/src/index.js +16528 -12497
  83. package/dist/src/launcher.js +4 -0
  84. package/dist/src/operator-cli.d.ts +2 -0
  85. package/dist/src/operator-cli.js +17837 -0
  86. package/dist/src/operator-entry.d.ts +1 -0
  87. package/dist/src/operator-entry.js +3 -0
  88. package/package.json +18 -12
  89. package/dist/src/app/board.d.ts +0 -23
  90. package/dist/src/app/board.js +0 -1786
  91. package/dist/src/app/theme.d.ts +0 -47
  92. package/dist/src/app/theme.js +0 -150
  93. package/dist/src/commands/_authority-runs.d.ts +0 -22
  94. package/dist/src/commands/_authority-runs.js +0 -110
  95. package/dist/src/commands/_operator-surface.d.ts +0 -34
  96. package/dist/src/commands/_operator-surface.js +0 -220
  97. package/dist/src/commands/_operator-view.d.ts +0 -30
  98. package/dist/src/commands/_operator-view.js +0 -1070
  99. package/dist/src/commands/_preflight.d.ts +0 -22
  100. package/dist/src/commands/_preflight.js +0 -540
  101. package/dist/src/commands/_run-replay.d.ts +0 -24
  102. package/dist/src/commands/_run-replay.js +0 -142
  103. package/dist/src/commands/_server-client.d.ts +0 -186
  104. package/dist/src/commands/_server-client.js +0 -681
  105. package/dist/src/commands/_snapshot-upload.d.ts +0 -39
  106. package/dist/src/commands/_snapshot-upload.js +0 -455
  107. package/dist/src/commands/_task-picker.d.ts +0 -9
  108. package/dist/src/commands/_task-picker.js +0 -201
  109. package/dist/src/commands/browser.d.ts +0 -65
  110. package/dist/src/commands/browser.js +0 -1173
  111. package/dist/src/commands/connect.d.ts +0 -7
  112. package/dist/src/commands/connect.js +0 -419
  113. package/dist/src/commands/inspector.d.ts +0 -3
  114. package/dist/src/commands/inspector.js +0 -263
  115. package/dist/src/commands/task-report-bug.d.ts +0 -19
  116. package/dist/src/commands/task-report-bug.js +0 -1281
  117. package/dist/src/report-bug.d.ts +0 -44
  118. package/dist/src/report-bug.js +0 -260
@@ -1,1786 +0,0 @@
1
- // @bun
2
- // packages/cli/src/app/board.ts
3
- import { randomUUID } from "crypto";
4
- import { existsSync as existsSync3 } from "fs";
5
- import { resolve as resolvePath } from "path";
6
- import { ProcessTerminal as ProcessTerminal2, TUI as TUI2, Text as Text2, isKeyRelease, matchesKey as matchesKey2, truncateToWidth } from "@earendil-works/pi-tui";
7
-
8
- // packages/cli/src/app/theme.ts
9
- var RIG_PALETTE = {
10
- ink: "#f2f3f6",
11
- ink2: "#aeb0ba",
12
- ink3: "#6c6e79",
13
- ink4: "#44464f",
14
- accent: "#ccff4d",
15
- accentDim: "#a9d63f",
16
- cyan: "#56d8ff",
17
- red: "#ff5d5d",
18
- yellow: "#ffd24d"
19
- };
20
- function hexToRgb(hex) {
21
- const value = hex.replace("#", "");
22
- return [
23
- Number.parseInt(value.slice(0, 2), 16),
24
- Number.parseInt(value.slice(2, 4), 16),
25
- Number.parseInt(value.slice(4, 6), 16)
26
- ];
27
- }
28
- function fg(hex) {
29
- const [r, g, b] = hexToRgb(hex);
30
- return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
31
- }
32
- var ink = fg(RIG_PALETTE.ink);
33
- var ink2 = fg(RIG_PALETTE.ink2);
34
- var ink3 = fg(RIG_PALETTE.ink3);
35
- var ink4 = fg(RIG_PALETTE.ink4);
36
- var accent = fg(RIG_PALETTE.accent);
37
- var accentDim = fg(RIG_PALETTE.accentDim);
38
- var cyan = fg(RIG_PALETTE.cyan);
39
- var red = fg(RIG_PALETTE.red);
40
- var yellow = fg(RIG_PALETTE.yellow);
41
- function bold(text) {
42
- return `\x1B[1m${text}\x1B[22m`;
43
- }
44
- function statusColor(status) {
45
- switch (status) {
46
- case "running":
47
- return accent;
48
- case "preparing":
49
- case "created":
50
- case "validating":
51
- case "reviewing":
52
- case "closing-out":
53
- return cyan;
54
- case "needs-attention":
55
- case "needs_attention":
56
- return yellow;
57
- case "failed":
58
- return red;
59
- default:
60
- return ink3;
61
- }
62
- }
63
- var RIG_SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
64
- var DRONE_ART = [
65
- " .-=-. .-=-. ",
66
- " ( !!! ) ( !!! ) ",
67
- " '-=-'._ _.'-=-' ",
68
- " '._ _.' ",
69
- " '=$$$$$$$=.' ",
70
- " =$$$$$$$$$$$= ",
71
- " $$$@@@@@@@@@@$$$ ",
72
- " $$$@@ @@$$$ ",
73
- " $$@ ? @$$$ ",
74
- " $$$@ '-' @$$$ ",
75
- " $$$@@ @@$$$ ",
76
- " $$$@@@@@@@@@@$$$ ",
77
- " =$$$$$$$$$$$= ",
78
- " '=$$$$$$$=.' ",
79
- " _.' '._ ",
80
- " .-=-.' '.-=-. ",
81
- " ( !!! ) ( !!! ) ",
82
- " '-=-' '-=-' "
83
- ];
84
- var BLADE_FRAMES = ["---", "\\\\\\", "|||", "///"];
85
- var EYE_FRAMES = ["@", "o", "."];
86
- function droneCharColor(char) {
87
- if (char === "$" || char === "@")
88
- return accent;
89
- if (char === "=" || char === "%")
90
- return accentDim;
91
- if (char === "\\" || char === "/")
92
- return ink3;
93
- return ink4;
94
- }
95
- function renderDroneFrame(tick) {
96
- const blade = BLADE_FRAMES[Math.floor(tick / 4) % BLADE_FRAMES.length];
97
- const pulse = Math.sin(tick * 0.07);
98
- const eye = pulse > 0.45 ? EYE_FRAMES[0] : pulse > -0.1 ? EYE_FRAMES[1] : EYE_FRAMES[2];
99
- return DRONE_ART.map((line) => {
100
- let out = "";
101
- let index = 0;
102
- while (index < line.length) {
103
- if (line.startsWith("!!!", index)) {
104
- out += cyan(blade);
105
- index += 3;
106
- continue;
107
- }
108
- const char = line[index];
109
- if (char === "?") {
110
- out += bold(cyan(eye));
111
- } else if (char !== " ") {
112
- out += droneCharColor(char)(char);
113
- } else {
114
- out += " ";
115
- }
116
- index += 1;
117
- }
118
- return out;
119
- });
120
- }
121
- var DRONE_WIDTH = DRONE_ART[0].length;
122
- var DRONE_HEIGHT = DRONE_ART.length;
123
- var MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
124
- function microDroneFrame(tick) {
125
- const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
126
- const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
127
- return `(${blade})${eye}(${blade})`;
128
- }
129
- var MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
130
-
131
- // packages/cli/src/commands/_help-catalog.ts
132
- import pc from "picocolors";
133
- function helpCatalog() {
134
- return { sections: TOP_LEVEL_SECTIONS, groups: ALL_GROUPS };
135
- }
136
- var TOP_LEVEL_SECTIONS = [
137
- {
138
- title: "Pi console",
139
- subtitle: "the operator surface \u2014 every attach opens the run's FULL Pi session",
140
- commands: [
141
- { command: "rig run attach <run-id>", description: "Open the run's Pi console: complete transcript (live AND finished runs), worker turns streaming in live." },
142
- { 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." },
143
- { command: "!<command>", description: "Inside the console, runs shell in the WORKER's workspace; output streams back into the transcript." },
144
- { command: "/<command>", description: "The palette includes the WORKER session's slash commands ([worker]-tagged) next to /rig." },
145
- { command: "/rig abort | /rig stop", description: "Abort the worker's current turn, or stop the whole run, from inside the console." },
146
- { command: "rig run steer <id> --message <text>", description: "Steer without attaching \u2014 queue a message; the worker picks it up within seconds." }
147
- ]
148
- },
149
- {
150
- title: "Start here",
151
- subtitle: "one-time setup, pick a server",
152
- commands: [
153
- { command: "rig init", description: "Wizard: config, GitHub auth, task source, server, Pi wiring." },
154
- { command: "rig server use <alias|local>", description: "Pick which Rig server owns this repo (`rig server list` to see them)." },
155
- { command: "rig server status", description: "Show the selected server for this repo." }
156
- ]
157
- },
158
- {
159
- title: "Work",
160
- subtitle: "find a task, put an agent on it, answer what it asks",
161
- commands: [
162
- { command: "rig task list", description: "What's on the board (from the selected source/server)." },
163
- { command: "rig task run --next", description: "Dispatch an agent on the next ready task; interactive mode drops you into its Pi console." },
164
- { command: "rig run status", description: "Active and recent runs at a glance." },
165
- { command: "rig run attach <id> --follow", description: "Same as plain attach \u2014 the Pi console is always the interactive surface." },
166
- { command: "rig inbox approvals", description: "Approvals workers are waiting on (then `rig inbox approve \u2026`)." }
167
- ]
168
- },
169
- {
170
- title: "Watch",
171
- subtitle: "fleet metrics and per-task forensics",
172
- commands: [
173
- { command: "rig stats [--since 7d]", description: "Fleet metrics: completion/failure rates, median run time, steering, stalls." },
174
- { command: "rig inspect logs --task <id>", description: "Latest run log for a task." },
175
- { command: "rig inspect diff --task <id>", description: "Changed files for a task." }
176
- ]
177
- },
178
- {
179
- title: "Unblock",
180
- subtitle: "diagnose wiring, fix auth",
181
- commands: [
182
- { command: "rig doctor", description: "Check every part of the wiring \u2014 run this when anything feels off." },
183
- { command: "rig github auth status", description: "GitHub auth state on the selected server." }
184
- ]
185
- },
186
- {
187
- title: "Extend",
188
- subtitle: "plugins contribute validators, hooks, task sources, commands",
189
- commands: [
190
- { command: "rig plugin list", description: "What the rig.config.ts plugins contribute." },
191
- { command: "rig plugin run <command-id>", description: "Execute a plugin-contributed CLI command." }
192
- ]
193
- }
194
- ];
195
- var PRIMARY_GROUPS = [
196
- {
197
- name: "server",
198
- summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
199
- usage: ["rig server <status|list|add|use|start> [options]"],
200
- commands: [
201
- { command: "status", description: "Show the selected server for this repo.", primary: true },
202
- { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
203
- { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
204
- { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
205
- { command: "list", description: "List saved local/remote server aliases.", primary: true },
206
- { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
207
- ],
208
- examples: [
209
- "rig server status",
210
- "rig server add prod https://where.rig-does.work",
211
- "rig server use prod",
212
- "rig server use local",
213
- "rig server start --port 3773"
214
- ],
215
- next: ["Use `rig task list` to see server-owned work.", "Use `rig run list` or `rig run attach <id> --follow` to monitor runs."]
216
- },
217
- {
218
- name: "task",
219
- summary: "Find work, start Pi-backed runs, and validate task results.",
220
- usage: ["rig task <list|next|show|run> [options]"],
221
- commands: [
222
- { command: "list [--assignee <login|me|@me>] [--state open|closed]", description: "List tasks from the selected server/source.", primary: true },
223
- { command: "next [filters]", description: "Render the next matching task as a selected-task card.", primary: true },
224
- { command: "show <id>|--task <id> [--raw]", description: "Show a human task summary; --raw prints the full payload.", primary: true },
225
- { command: "run [#<issue>|<task-id>|--next|--task <id>]", description: "Submit a task run; interactive follows with bundled Pi.", primary: true },
226
- { command: "ready", description: "List task IDs that are runnable now." },
227
- { command: "validate|verify [--task <id>]", description: "Run configured task checks/review gates." },
228
- { command: "details --task <id>", description: "Show full task info from the configured source." },
229
- { command: "reopen [--task <id> | --all] [--reason <text>]", description: "Reopen closed task(s) in the configured source." },
230
- { command: "artifacts|artifact-dir|artifact-write", description: "Inspect or write task artifacts." },
231
- { command: "report-bug", description: "Create a structured bug report/task." }
232
- ],
233
- examples: [
234
- "rig task list --assignee @me --limit 20",
235
- "rig task next",
236
- "rig task show 123 --raw",
237
- "rig task run --next",
238
- "rig task run #123 --runtime-adapter pi",
239
- "rig task run --title 'Investigate deploy drift' --initial-prompt 'Check server health'"
240
- ],
241
- next: ["Use `--detach` to submit without attaching.", "Use `rig run attach <run-id> --follow` to rejoin a live run."]
242
- },
243
- {
244
- name: "run",
245
- summary: "Observe, attach to, and control Rig runs. `attach` opens the Pi console \u2014 the full worker session, live.",
246
- usage: ["rig run <list|status|show|attach|steer|stop|resume|restart> [options]"],
247
- commands: [
248
- { command: "list", description: "List recent runs from the selected server or local state.", primary: true },
249
- { command: "status", description: "Render active and recent run groups.", primary: true },
250
- { command: "show <id>|--run <id> [--raw]", description: "Show a human run summary; --raw prints the full payload.", primary: true },
251
- { 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 },
252
- { 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 },
253
- { command: "stop [<run-id>|--run <id>]", description: "Request stop for one run or local active runs.", primary: true },
254
- { command: "resume [<run-id>]", description: "Resume an interrupted run on the selected server (defaults to the most recent resumable)." },
255
- { command: "restart [<run-id>]", description: "Re-dispatch a run from a clean runtime, reopening its Pi session where possible." },
256
- { command: "timeline --run <id> [--follow]", description: "Stream raw run timeline events (scripts; humans should attach)." },
257
- { 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." },
258
- { command: "delete|cleanup", description: "Remove completed run records/artifacts." }
259
- ],
260
- examples: [
261
- "rig run attach <run-id> # full session console \u2014 live mirror, steering, worker shell",
262
- "rig run steer <run-id> --message 'focus on the failing test first'",
263
- "rig run list",
264
- "rig run show <run-id>",
265
- "rig run stop <run-id>"
266
- ],
267
- next: [
268
- "Inside the console: the run's COMPLETE transcript loads on open (finished runs too), and new worker turns stream in live.",
269
- "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.",
270
- "The console is read-write but remote-only: nothing runs on your machine; the worker keeps running when you exit.",
271
- "Use `rig task run --next` to create a new run; interactive mode drops you straight into its console.",
272
- "Use `--json` when scripts need the full structured record."
273
- ]
274
- },
275
- {
276
- name: "inbox",
277
- summary: "Review approval and user-input requests that block worker runs.",
278
- usage: ["rig inbox <approvals|approve|inputs|respond> [options]"],
279
- commands: [
280
- { command: "approvals [--run <id>] [--task <id>]", description: "List pending approvals.", primary: true },
281
- { command: "inputs [--run <id>] [--task <id>]", description: "List pending user-input requests.", primary: true },
282
- { command: "approve --run <id> --request <id> --decision approve|reject", description: "Resolve an approval request." },
283
- { command: "respond --run <id> --request <id> --answer key=value", description: "Answer a user-input request." }
284
- ],
285
- examples: [
286
- "rig inbox approvals",
287
- "rig inbox inputs --run <run-id>",
288
- "rig inbox approve --run <run-id> --request <request-id> --decision approve"
289
- ],
290
- next: ["Rejoin the run after resolving a block: `rig run attach <run-id> --follow`."]
291
- },
292
- {
293
- name: "stats",
294
- summary: "Fleet metrics computed from on-disk run journals (no server required).",
295
- usage: ["rig stats [show] [--since <7d|30d|ISO date>]"],
296
- commands: [
297
- { command: "show [--since <window>]", description: "Total runs, completion/failure/needs-attention rates, median run time, steering, stalls, approvals.", primary: true }
298
- ],
299
- examples: [
300
- "rig stats",
301
- "rig stats --since 7d",
302
- "rig stats --since 2026-06-01 --json"
303
- ],
304
- 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)."]
305
- },
306
- {
307
- name: "inspect",
308
- summary: "Inspect logs, artifacts, graphs, failures for a task.",
309
- usage: ["rig inspect <logs|artifacts|failures|graph|audit|diff> --task <id>"],
310
- commands: [
311
- { command: "logs --task <id>", description: "Latest run log for a task (local or selected server).", primary: true },
312
- { command: "artifacts --task <id>", description: "List the task's completion artifacts.", primary: true },
313
- { command: "failures --task <id>", description: "Recorded failures for a task.", primary: true },
314
- { command: "diff --task <id>", description: "Changed files for a task.", primary: true },
315
- { command: "graph", description: "Task dependency graph." },
316
- { command: "audit", description: "Controlled-command audit trail." }
317
- ],
318
- examples: ["rig inspect logs --task <id>", "rig inspect diff --task <id>"],
319
- next: ["Use `rig stats` for fleet-level metrics across runs."]
320
- },
321
- {
322
- name: "repo",
323
- summary: "Repository sync/baseline helpers for the Rig-managed checkout.",
324
- usage: ["rig repo <sync|reset-baseline>"],
325
- commands: [
326
- { command: "sync", description: "Sync project repository state.", primary: true },
327
- { command: "reset-baseline", description: "Reset the managed baseline for the repo." }
328
- ],
329
- examples: ["rig repo sync"]
330
- },
331
- {
332
- name: "plugin",
333
- summary: "Plugin listing, validation, and plugin-contributed commands.",
334
- usage: ["rig plugin <list|validate|run> [options]"],
335
- commands: [
336
- { command: "list", description: "List plugins declared in rig.config.ts and their contributions.", primary: true },
337
- { command: "validate --task <id>", description: "Run plugin-contributed validators for a task.", primary: true },
338
- { command: "run <command-id> [args...]", description: "Execute a plugin-contributed CLI command (also callable as `rig <command-id>`)." }
339
- ],
340
- examples: ["rig plugin list", "rig plugin run <command-id>"]
341
- },
342
- {
343
- name: "init",
344
- summary: "Set up Rig for this repo: server, GitHub auth, checkout strategy, task source, and Pi wiring.",
345
- usage: ["rig init [--yes] [--server local|remote] [--repo owner/repo] [--remote-url <url>]"],
346
- commands: [
347
- { command: "init", description: "Interactive setup wizard for a new or existing Rig repo.", primary: true },
348
- { command: "init --demo", description: "Offline demo project: files task source + 3 sample tasks, zero GitHub.", primary: true },
349
- { command: "init --yes", description: "Non-interactive setup using detected/default settings.", primary: true },
350
- { command: "init --server remote --remote-url <url>", description: "Link this repo to a remote Rig server.", primary: true },
351
- { command: "init --repair", description: "Repair missing private state without replacing project config." }
352
- ],
353
- examples: [
354
- "rig init",
355
- "rig init --demo",
356
- "rig init --yes --repo humanity-org/humanwork",
357
- "rig init --server remote --remote-url https://where.rig-does.work --repo owner/repo"
358
- ],
359
- next: ["After init, run `rig server status`.", "Then use `rig task list` and `rig task run --next` for day-to-day work."]
360
- },
361
- {
362
- name: "doctor",
363
- summary: "Diagnostics for project/server/GitHub/Pi state.",
364
- usage: ["rig doctor"],
365
- commands: [
366
- { command: "doctor", description: "Run setup and runtime diagnostics.", primary: true },
367
- { command: "check", description: "Compatibility spelling for diagnostics." }
368
- ],
369
- examples: ["rig doctor", "rig doctor --json"],
370
- next: ["Use `rig server status` and `rig github auth status` to inspect common failure points."]
371
- },
372
- {
373
- name: "github",
374
- summary: "GitHub auth helpers for the selected Rig server.",
375
- usage: ["rig github auth <status|import-gh|token>"],
376
- commands: [
377
- { command: "auth status", description: "Show GitHub auth state.", primary: true },
378
- { command: "auth import-gh", description: "Import the current `gh` token into the selected server." },
379
- { command: "auth token --token <token>", description: "Store a token on the selected server." }
380
- ],
381
- examples: ["rig github auth status", "rig github auth import-gh"],
382
- next: ["After auth is valid, use `rig task run --next`."]
383
- }
384
- ];
385
- var ADVANCED_GROUPS = [
386
- { name: "setup", summary: "Bootstrap/check local setup.", usage: ["rig setup <bootstrap|check|preflight>"], commands: [{ command: "bootstrap|check|preflight", description: "Setup helpers." }] },
387
- { name: "profile", summary: "Runtime profile/model defaults.", usage: ["rig profile <show|set>"], commands: [{ command: "show", description: "Show active profile." }] },
388
- {
389
- name: "review",
390
- summary: "Inspect or change completion review gate policy.",
391
- usage: ["rig review <show|set>"],
392
- commands: [
393
- { command: "show", description: "Show current review gate settings." },
394
- { command: "set <off|advisory|required> [--provider greptile]", description: "Change review strictness/provider." }
395
- ],
396
- examples: ["rig review show", "rig review set required --provider greptile"],
397
- next: ["Use `rig inbox approvals` for blocked run handoffs."]
398
- },
399
- {
400
- name: "browser",
401
- summary: "Browser/app diagnostics for browser-required tasks.",
402
- usage: ["rig browser <help|explain|demo|app|hp-next> [options]"],
403
- commands: [
404
- { command: "help", description: "Rich browser command help (canonical: `rig browser help`)." },
405
- { command: "explain", description: "Explain the browser-required task contract." },
406
- { command: "demo", description: "Run browser demo flows against a local page." },
407
- { command: "app", description: "Launch the Rig Browser workstation app." },
408
- { command: "hp-next <dev|check|e2e|reset>", description: "Drive the hp-next browser test harness." }
409
- ]
410
- },
411
- {
412
- name: "pi",
413
- summary: "Manage Pi extension packages for this project (community extensions from npm/git).",
414
- usage: ["rig pi <list|add|remove|search> [args]"],
415
- commands: [
416
- { command: "list", description: "Show project and user Pi extension packages." },
417
- { command: "add <source>", description: "Add an npm/git Pi extension to .pi/settings.json (auto-installs at next session)." },
418
- { command: "remove <source>", description: "Remove an operator-added Pi extension." },
419
- { command: "search [term]", description: "Discover Pi extension packages on the npm registry." }
420
- ],
421
- examples: ["rig pi search subagents", "rig pi add pi-subagents", "rig pi list"],
422
- next: ["Config-managed extensions: declare `runtime: { pi: { packages: [...] } }` in rig.config.ts \u2014 workers pick them up automatically."]
423
- },
424
- { name: "queue", summary: "Run task queues locally.", usage: ["rig queue run [options]"], commands: [{ command: "run", description: "Process queue work." }] },
425
- { name: "agent", summary: "Runtime agent workspace helpers.", usage: ["rig agent <list|prepare|run|cleanup>"], commands: [{ command: "list", description: "List prepared agents." }] },
426
- { name: "inspector", summary: "Event stream and drift scanners.", usage: ["rig inspector <stream|scan-upstream-drift>"], commands: [{ command: "stream", description: "Stream events." }] },
427
- { name: "dist", summary: "Build/install packaged Rig CLI.", usage: ["rig dist <build|install|doctor>"], commands: [{ command: "build", description: "Build distribution." }] },
428
- { name: "workspace", summary: "Workspace topology/service helpers.", usage: ["rig workspace <summary|topology|remote-hosts>"], commands: [{ command: "summary", description: "Show workspace summary." }] },
429
- { name: "remote", summary: "Compatibility remote orchestration controls.", usage: ["rig remote <status|watch|pause|resume|...>"], commands: [{ command: "status", description: "Show remote state." }] },
430
- { name: "git", summary: "Pass through to Rig git-flow helper.", usage: ["rig git <args...>"], commands: [{ command: "<args...>", description: "Advanced git flow operations." }] },
431
- { name: "harness", summary: "Pass through to runtime harness CLI.", usage: ["rig harness <args...>"], commands: [{ command: "<args...>", description: "Advanced harness operations." }] },
432
- { name: "test", summary: "Project test wrappers.", usage: ["rig test <unit|e2e|all>"], commands: [{ command: "all", description: "Run configured project tests." }] }
433
- ];
434
- var ALL_GROUPS = [...PRIMARY_GROUPS, ...ADVANCED_GROUPS];
435
-
436
- // packages/cli/src/commands/_server-client.ts
437
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
438
- import { resolve as resolve2 } from "path";
439
-
440
- // packages/cli/src/runner.ts
441
- import { EventBus } from "@rig/runtime/control-plane/runtime/events";
442
- import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
443
- import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
444
- import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
445
-
446
- class CliError extends RuntimeCliError {
447
- hint;
448
- constructor(message, exitCode = 1, options = {}) {
449
- super(message, exitCode);
450
- if (options.hint?.trim()) {
451
- this.hint = options.hint.trim();
452
- }
453
- }
454
- }
455
-
456
- // packages/cli/src/commands/_server-client.ts
457
- import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
458
-
459
- // packages/cli/src/commands/_connection-state.ts
460
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
461
- import { homedir } from "os";
462
- import { dirname, resolve } from "path";
463
- function resolveGlobalConnectionsPath(env = process.env) {
464
- const explicit = env.RIG_CONNECTIONS_FILE?.trim();
465
- if (explicit)
466
- return resolve(explicit);
467
- const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
468
- if (stateDir)
469
- return resolve(stateDir, "connections.json");
470
- return resolve(homedir(), ".rig", "connections.json");
471
- }
472
- function resolveRepoConnectionPath(projectRoot) {
473
- return resolve(projectRoot, ".rig", "state", "connection.json");
474
- }
475
- function readJsonFile(path) {
476
- if (!existsSync(path))
477
- return null;
478
- try {
479
- return JSON.parse(readFileSync(path, "utf8"));
480
- } catch (error) {
481
- 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>`." });
482
- }
483
- }
484
- function writeJsonFile(path, value) {
485
- mkdirSync(dirname(path), { recursive: true });
486
- writeFileSync(path, `${JSON.stringify(value, null, 2)}
487
- `, "utf8");
488
- }
489
- function normalizeConnection(value) {
490
- if (!value || typeof value !== "object" || Array.isArray(value))
491
- return null;
492
- const record = value;
493
- if (record.kind === "local")
494
- return { kind: "local", mode: "auto" };
495
- if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
496
- const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
497
- return { kind: "remote", baseUrl };
498
- }
499
- return null;
500
- }
501
- function readGlobalConnections(options = {}) {
502
- const path = resolveGlobalConnectionsPath(options.env ?? process.env);
503
- const payload = readJsonFile(path);
504
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
505
- return { connections: {} };
506
- }
507
- const rawConnections = payload.connections;
508
- const connections = {};
509
- if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
510
- for (const [alias, raw] of Object.entries(rawConnections)) {
511
- const connection = normalizeConnection(raw);
512
- if (connection)
513
- connections[alias] = connection;
514
- }
515
- }
516
- return { connections };
517
- }
518
- function readRepoConnection(projectRoot) {
519
- const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
520
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
521
- return null;
522
- const record = payload;
523
- const selected = typeof record.selected === "string" ? record.selected.trim() : "";
524
- if (!selected)
525
- return null;
526
- return {
527
- selected,
528
- project: typeof record.project === "string" ? record.project : undefined,
529
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
530
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
531
- };
532
- }
533
- function writeRepoConnection(projectRoot, state) {
534
- writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
535
- }
536
- function resolveSelectedConnection(projectRoot, options = {}) {
537
- const repo = readRepoConnection(projectRoot);
538
- if (!repo)
539
- return null;
540
- if (repo.selected === "local")
541
- return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
542
- const global = readGlobalConnections(options);
543
- const connection = global.connections[repo.selected];
544
- if (!connection) {
545
- throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
546
- }
547
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
548
- }
549
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
550
- const repo = readRepoConnection(projectRoot);
551
- if (!repo)
552
- return;
553
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
554
- }
555
-
556
- // packages/cli/src/commands/_server-client.ts
557
- var scopedGitHubBearerTokens = new Map;
558
- var serverPhaseListener = null;
559
- function reportServerPhase(label) {
560
- serverPhaseListener?.(label);
561
- }
562
- function cleanToken(value) {
563
- const trimmed = value?.trim();
564
- return trimmed ? trimmed : null;
565
- }
566
- function readPrivateRemoteSessionToken(projectRoot) {
567
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
568
- if (!existsSync2(path))
569
- return null;
570
- try {
571
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
572
- return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
573
- } catch {
574
- return null;
575
- }
576
- }
577
- function readGitHubBearerTokenForRemote(projectRoot) {
578
- const scopedKey = resolve2(projectRoot);
579
- if (scopedGitHubBearerTokens.has(scopedKey))
580
- return scopedGitHubBearerTokens.get(scopedKey) ?? null;
581
- const privateSession = readPrivateRemoteSessionToken(projectRoot);
582
- if (privateSession)
583
- return privateSession;
584
- return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
585
- }
586
- function readStoredGitHubAuthToken(projectRoot) {
587
- const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
588
- if (!existsSync2(path))
589
- return null;
590
- try {
591
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
592
- return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
593
- } catch {
594
- return null;
595
- }
596
- }
597
- function readLocalConnectionFallbackToken(projectRoot) {
598
- return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
599
- }
600
- async function ensureServerForCli(projectRoot) {
601
- try {
602
- const selected = resolveSelectedConnection(projectRoot);
603
- if (selected?.connection.kind === "remote") {
604
- reportServerPhase(`Connecting to ${selected.alias}\u2026`);
605
- const authToken = readGitHubBearerTokenForRemote(projectRoot);
606
- const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
607
- return {
608
- baseUrl: selected.connection.baseUrl,
609
- authToken,
610
- connectionKind: "remote",
611
- serverProjectRoot
612
- };
613
- }
614
- reportServerPhase("Starting local Rig server\u2026");
615
- const connection = await ensureLocalRigServerConnection(projectRoot);
616
- return {
617
- baseUrl: connection.baseUrl,
618
- authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
619
- connectionKind: "local",
620
- serverProjectRoot: resolve2(projectRoot)
621
- };
622
- } catch (error) {
623
- if (error instanceof Error) {
624
- throw new CliError(error.message, 1);
625
- }
626
- throw error;
627
- }
628
- }
629
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
630
- const repo = readRepoConnection(projectRoot);
631
- const slug = repo?.project?.trim();
632
- if (!slug)
633
- return null;
634
- try {
635
- const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
636
- headers: mergeHeaders(undefined, authToken)
637
- });
638
- if (!response.ok)
639
- return null;
640
- const payload = await response.json();
641
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
642
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
643
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
644
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
645
- if (path)
646
- writeRepoServerProjectRoot(projectRoot, path);
647
- return path;
648
- } catch {
649
- return null;
650
- }
651
- }
652
- function appendTaskFilterParams(url, filters) {
653
- if (filters.assignee)
654
- url.searchParams.set("assignee", filters.assignee);
655
- if (filters.state)
656
- url.searchParams.set("state", filters.state);
657
- if (filters.status)
658
- url.searchParams.set("status", filters.status);
659
- if (filters.limit !== undefined)
660
- url.searchParams.set("limit", String(filters.limit));
661
- }
662
- function mergeHeaders(headers, authToken) {
663
- const merged = new Headers(headers);
664
- if (authToken) {
665
- merged.set("authorization", `Bearer ${authToken}`);
666
- }
667
- return merged;
668
- }
669
- function diagnosticMessage(payload) {
670
- if (!payload || typeof payload !== "object" || Array.isArray(payload))
671
- return null;
672
- const record = payload;
673
- const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
674
- const messages = diagnostics.flatMap((entry) => {
675
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
676
- return [];
677
- const diagnostic = entry;
678
- const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
679
- const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
680
- return message ? [`${kind}: ${message}`] : [];
681
- });
682
- return messages.length > 0 ? messages.join("; ") : null;
683
- }
684
- var serverReachabilityCache = new Map;
685
- async function probeServerReachability(baseUrl, authToken) {
686
- try {
687
- const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
688
- headers: mergeHeaders(undefined, authToken),
689
- signal: AbortSignal.timeout(1500)
690
- });
691
- return response.ok;
692
- } catch {
693
- return false;
694
- }
695
- }
696
- function cachedServerReachability(projectRoot, baseUrl, authToken) {
697
- const key = resolve2(projectRoot);
698
- const cached = serverReachabilityCache.get(key);
699
- if (cached)
700
- return cached;
701
- const probe = probeServerReachability(baseUrl, authToken);
702
- serverReachabilityCache.set(key, probe);
703
- return probe;
704
- }
705
- function describeSelectedServer(projectRoot, server) {
706
- try {
707
- const selected = resolveSelectedConnection(projectRoot);
708
- if (selected) {
709
- return {
710
- alias: selected.alias,
711
- target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
712
- };
713
- }
714
- } catch {}
715
- return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
716
- }
717
- async function buildServerFailureContext(projectRoot, server) {
718
- const { alias, target } = describeSelectedServer(projectRoot, server);
719
- const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
720
- const reachability = reachable ? "server is reachable" : "server is unreachable";
721
- return {
722
- contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
723
- hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
724
- };
725
- }
726
- async function requestServerJson(context, pathname, init = {}) {
727
- const server = await ensureServerForCli(context.projectRoot);
728
- const headers = mergeHeaders(init.headers, server.authToken);
729
- if (server.serverProjectRoot)
730
- headers.set("x-rig-project-root", server.serverProjectRoot);
731
- reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
732
- let response;
733
- try {
734
- response = await fetch(`${server.baseUrl}${pathname}`, {
735
- ...init,
736
- headers
737
- });
738
- } catch (error) {
739
- const failure = await buildServerFailureContext(context.projectRoot, server);
740
- throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
741
- ${failure.contextLine}`, 1, { hint: failure.hint });
742
- }
743
- const text = await response.text();
744
- const payload = text.trim().length > 0 ? (() => {
745
- try {
746
- return JSON.parse(text);
747
- } catch {
748
- return null;
749
- }
750
- })() : null;
751
- if (!response.ok) {
752
- const diagnostics = diagnosticMessage(payload);
753
- const rawDetail = diagnostics ?? (text || response.statusText);
754
- const detail = diagnostics ? rawDetail : rawDetail.split(`
755
- `).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? response.statusText;
756
- const failure = await buildServerFailureContext(context.projectRoot, server);
757
- throw new CliError(`Rig server request failed (${response.status}): ${detail}
758
- ${failure.contextLine}`, 1, { hint: failure.hint });
759
- }
760
- return payload;
761
- }
762
- async function listWorkspaceTasksViaServer(context, filters = {}) {
763
- const url = new URL("http://rig.local/api/workspace/tasks");
764
- appendTaskFilterParams(url, filters);
765
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
766
- if (!Array.isArray(payload)) {
767
- 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`." });
768
- }
769
- return payload.flatMap((entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? [entry] : []);
770
- }
771
- async function listRunsViaServer(context, options = {}) {
772
- const url = new URL("http://rig.local/api/runs");
773
- if (options.limit !== undefined)
774
- url.searchParams.set("limit", String(options.limit));
775
- const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
776
- const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
777
- return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
778
- }
779
- var RESUMABLE_RUN_STATUSES = new Set([
780
- "created",
781
- "preparing",
782
- "running",
783
- "validating",
784
- "reviewing",
785
- "stopped",
786
- "failed",
787
- "needs-attention",
788
- "needs_attention"
789
- ]);
790
- async function resolveServerConnectionLabel(projectRoot) {
791
- try {
792
- const selected = resolveSelectedConnection(projectRoot);
793
- if (!selected)
794
- return "no server selected";
795
- if (selected.connection.kind === "remote") {
796
- return selected.connection.baseUrl.replace(/^https?:\/\//, "");
797
- }
798
- return `local (${selected.alias})`;
799
- } catch {
800
- return "no server selected";
801
- }
802
- }
803
- async function stopRunViaServer(context, runId) {
804
- const payload = await requestServerJson(context, "/api/runs/stop", {
805
- method: "POST",
806
- headers: { "content-type": "application/json" },
807
- body: JSON.stringify({ runId })
808
- });
809
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
810
- }
811
- async function submitTaskRunViaServer(context, input) {
812
- const isTaskRun = Boolean(input.taskId);
813
- const endpoint = isTaskRun ? "/api/runs/task" : "/api/runs/adhoc";
814
- const payload = await requestServerJson(context, endpoint, {
815
- method: "POST",
816
- headers: {
817
- "content-type": "application/json"
818
- },
819
- body: JSON.stringify({
820
- runId: input.runId,
821
- taskId: input.taskId,
822
- title: input.title,
823
- runtimeAdapter: input.runtimeAdapter,
824
- model: input.model,
825
- runtimeMode: input.runtimeMode,
826
- interactionMode: input.interactionMode,
827
- initialPrompt: input.initialPrompt,
828
- baselineMode: input.baselineMode,
829
- prMode: input.prMode,
830
- executionTarget: "local"
831
- })
832
- });
833
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
834
- 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." });
835
- }
836
- const runId = payload.runId;
837
- if (typeof runId !== "string" || runId.trim().length === 0) {
838
- 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." });
839
- }
840
- return { runId };
841
- }
842
-
843
- // packages/cli/src/commands/_authority-runs.ts
844
- import {
845
- readAuthorityRun,
846
- readJsonlFile,
847
- writeAuthorityRunRecord
848
- } from "@rig/runtime/control-plane/authority-files";
849
-
850
- // packages/cli/src/commands/_paths.ts
851
- import { resolveMonorepoRoot } from "@rig/runtime/control-plane/native/utils";
852
-
853
- // packages/cli/src/commands/_authority-runs.ts
854
- function normalizeRuntimeAdapter(value) {
855
- const normalized = value?.trim().toLowerCase();
856
- if (!normalized) {
857
- return "pi";
858
- }
859
- if (normalized === "codex" || normalized === "codex-cli" || normalized === "codex-app-server" || normalized === "gpt-codex") {
860
- return "codex";
861
- }
862
- if (normalized === "pi" || normalized === "rig-pi" || normalized === "@rig/pi") {
863
- return "pi";
864
- }
865
- return "claude-code";
866
- }
867
-
868
- // packages/cli/src/app/drone-ui.ts
869
- import { ProcessTerminal, TUI, Text, Input, SelectList, matchesKey } from "@earendil-works/pi-tui";
870
-
871
- // packages/cli/src/commands/_cli-format.ts
872
- import pc2 from "picocolors";
873
-
874
- // packages/cli/src/commands/_async-ui.ts
875
- import pc3 from "picocolors";
876
- var DONE_SYMBOL = pc3.green("\u25C7");
877
- var FAIL_SYMBOL = pc3.red("\u25A0");
878
-
879
- // packages/cli/src/commands/inbox.ts
880
- async function listInboxRecords(context, kind, filters) {
881
- const params = new URLSearchParams;
882
- if (filters.run)
883
- params.set("runId", filters.run);
884
- if (filters.task)
885
- params.set("taskId", filters.task);
886
- const query = params.size > 0 ? `?${params.toString()}` : "";
887
- const payload = await requestServerJson(context, `/api/inbox/${kind}${query}`);
888
- const records = Array.isArray(payload) ? payload : [];
889
- return filters.pendingOnly ? records.filter((entry) => (entry.status ?? "pending") !== "resolved") : records;
890
- }
891
- async function readPendingInboxCounts(context) {
892
- try {
893
- const [approvals, inputs] = await Promise.all([
894
- listInboxRecords(context, "approvals", { pendingOnly: true }),
895
- listInboxRecords(context, "inputs", { pendingOnly: true })
896
- ]);
897
- return { approvals: approvals.length, inputs: inputs.length };
898
- } catch {
899
- return null;
900
- }
901
- }
902
-
903
- // packages/cli/src/commands/task.ts
904
- import {
905
- taskArtifactDir,
906
- taskArtifacts,
907
- taskArtifactWrite,
908
- taskDeps,
909
- taskInfo,
910
- taskLookup,
911
- taskReady,
912
- taskRecord,
913
- taskReopen,
914
- taskScope,
915
- taskStatus,
916
- taskValidate,
917
- taskVerify
918
- } from "@rig/runtime/control-plane/native/task-ops";
919
-
920
- // packages/cli/src/commands/_preflight.ts
921
- import { ensureProjectMainFreshBeforeRun } from "@rig/runtime/control-plane/project-main-pre-run-sync";
922
-
923
- // packages/cli/src/commands/_pi-frontend.ts
924
- import { main as runPiMain } from "@earendil-works/pi-coding-agent";
925
- import createPiRigExtension from "@rig/pi-rig";
926
-
927
- // packages/cli/src/commands/_operator-view.ts
928
- var TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
929
-
930
- // packages/cli/src/commands/task.ts
931
- import { buildPluginHostContext } from "@rig/runtime/control-plane/plugin-host-context";
932
- import { loadConfig } from "@rig/core/load-config";
933
- function mapConfiguredRuntimeMode(mode) {
934
- if (!mode)
935
- return;
936
- return mode === "yolo" ? "full-access" : mode;
937
- }
938
- async function loadTaskRunProjectDefaults(projectRoot) {
939
- try {
940
- const config = await loadConfig(projectRoot);
941
- return {
942
- runtimeAdapter: config.runtime?.harness,
943
- model: config.runtime?.model,
944
- runtimeMode: mapConfiguredRuntimeMode(config.runtime?.mode),
945
- prMode: config.pr?.mode
946
- };
947
- } catch {
948
- return {};
949
- }
950
- }
951
-
952
- // packages/cli/src/app/board.ts
953
- var BOARD_REFRESH_MS = 5000;
954
- var BOARD_TICK_MS = 250;
955
- var BOARD_TASK_PAGE = 20;
956
- function oneLine(message) {
957
- return message.split(`
958
- `).map((line) => line.trim()).find((line) => line.length > 0)?.slice(0, 200) ?? "unknown error";
959
- }
960
- function normalizeRuns(payload) {
961
- return payload.map((run) => ({
962
- runId: typeof run.runId === "string" ? run.runId : "",
963
- status: typeof run.status === "string" ? run.status : "unknown",
964
- title: String(run.title ?? run.taskId ?? "untitled")
965
- })).filter((run) => run.runId);
966
- }
967
- function statusRank(status) {
968
- switch (status) {
969
- case "needs-attention":
970
- case "needs_attention":
971
- return 0;
972
- case "running":
973
- return 1;
974
- case "pending":
975
- case "preparing":
976
- case "adopted":
977
- return 2;
978
- case "completed":
979
- case "merged":
980
- return 3;
981
- case "failed":
982
- return 4;
983
- default:
984
- return 5;
985
- }
986
- }
987
-
988
- class RunsList {
989
- runs = [];
990
- selected = 0;
991
- loading = true;
992
- noProject = false;
993
- tick = 0;
994
- filter = "";
995
- sortMode = "active";
996
- visibleRuns() {
997
- const query = this.filter.trim().toLowerCase();
998
- const filtered = query ? this.runs.filter((run) => run.runId.toLowerCase().includes(query) || run.status.toLowerCase().includes(query) || run.title.toLowerCase().includes(query)) : [...this.runs];
999
- if (this.sortMode === "active") {
1000
- return filtered.map((run, index) => ({ run, index })).sort((a, b) => statusRank(a.run.status) - statusRank(b.run.status) || a.index - b.index).map((entry) => entry.run);
1001
- }
1002
- if (this.sortMode === "status") {
1003
- return filtered.map((run, index) => ({ run, index })).sort((a, b) => a.run.status.localeCompare(b.run.status) || a.index - b.index).map((entry) => entry.run);
1004
- }
1005
- return filtered;
1006
- }
1007
- moveSelection(delta) {
1008
- const visible = this.visibleRuns();
1009
- if (visible.length === 0)
1010
- return;
1011
- this.selected = Math.max(0, Math.min(visible.length - 1, this.selected + delta));
1012
- }
1013
- selectedRun() {
1014
- return this.visibleRuns()[this.selected] ?? null;
1015
- }
1016
- cycleSort() {
1017
- this.sortMode = this.sortMode === "active" ? "recent" : this.sortMode === "recent" ? "status" : "active";
1018
- this.clampSelection();
1019
- return this.sortMode;
1020
- }
1021
- setFilter(filter) {
1022
- this.filter = filter;
1023
- this.clampSelection();
1024
- }
1025
- clampSelection() {
1026
- this.selected = Math.max(0, Math.min(this.selected, Math.max(0, this.visibleRuns().length - 1)));
1027
- }
1028
- setRuns(runs) {
1029
- const previous = this.selectedRun()?.runId;
1030
- this.runs = runs;
1031
- if (previous) {
1032
- const index = this.visibleRuns().findIndex((run) => run.runId === previous);
1033
- if (index >= 0)
1034
- this.selected = index;
1035
- }
1036
- this.clampSelection();
1037
- this.loading = false;
1038
- }
1039
- invalidate() {}
1040
- render(width) {
1041
- return this.renderLines(width).map((line) => truncateToWidth(line, Math.max(10, width - 1)));
1042
- }
1043
- renderLines(width) {
1044
- if (this.loading) {
1045
- const frame = renderDroneFrame(this.tick);
1046
- const spinner = RIG_SPINNER_FRAMES[this.tick % RIG_SPINNER_FRAMES.length];
1047
- const pad = Math.max(0, Math.floor((width - 34) / 2));
1048
- return [
1049
- "",
1050
- ...frame.map((line) => " ".repeat(pad) + line),
1051
- "",
1052
- " ".repeat(Math.max(0, Math.floor((width - 24) / 2))) + accent(spinner) + ink3(" contacting the fleet\u2026"),
1053
- ""
1054
- ];
1055
- }
1056
- if (this.noProject) {
1057
- const frame = renderDroneFrame(this.tick);
1058
- const pad = Math.max(0, Math.floor((width - 34) / 2));
1059
- const center = (text, visible2) => " ".repeat(Math.max(0, Math.floor((width - visible2) / 2))) + text;
1060
- return [
1061
- "",
1062
- ...frame.map((line) => " ".repeat(pad) + line),
1063
- "",
1064
- center(ink2("no rig project in this directory"), 32),
1065
- "",
1066
- center(`${accent("rig init")}${ink2(" set this repo up: config, GitHub auth, task source, server, Pi")}`, 80),
1067
- center(`${accent("rig init --yes")}${ink2(" same, non-interactive, sensible defaults")}`, 60),
1068
- center(`${accent("rig doctor")}${ink2(" already initialized somewhere else? check the wiring")}`, 70),
1069
- "",
1070
- center(ink3("after init: rig task run --next puts a drone on your next task"), 62),
1071
- ""
1072
- ];
1073
- }
1074
- const visible = this.visibleRuns();
1075
- if (this.runs.length === 0) {
1076
- const frame = renderDroneFrame(this.tick);
1077
- const pad = Math.max(0, Math.floor((width - 34) / 2));
1078
- return [
1079
- "",
1080
- ...frame.map((line) => " ".repeat(pad) + line),
1081
- "",
1082
- " ".repeat(Math.max(0, Math.floor((width - 44) / 2))) + ink2("no runs yet \u2014 ") + accent("n") + ink2(" picks a task and launches one"),
1083
- ""
1084
- ];
1085
- }
1086
- if (visible.length === 0) {
1087
- return ["", ` ${ink2("no runs match")} ${accent(`/${this.filter}`)} ${ink3("\u2014 esc clears the filter")}`, ""];
1088
- }
1089
- const maxVisible = 16;
1090
- const start = Math.max(0, Math.min(this.selected - Math.floor(maxVisible / 2), visible.length - maxVisible));
1091
- const window = visible.slice(start, start + maxVisible);
1092
- const lines = window.map((run, index) => {
1093
- const absolute = start + index;
1094
- const isSelected = absolute === this.selected;
1095
- const dot = statusColor(run.status)(isSelected ? "\u25CF" : "\xB7");
1096
- const id = run.runId.slice(0, 8);
1097
- const status = statusColor(run.status)(run.status.padEnd(16));
1098
- const title = truncateToWidth(run.title, Math.max(8, width - 36));
1099
- const row = ` ${dot} ${isSelected ? bold(ink(id)) : ink3(id)} ${status} ${isSelected ? ink(title) : ink2(title)}`;
1100
- return isSelected ? accent("\u258C") + row : " " + row;
1101
- });
1102
- const meta = [];
1103
- if (visible.length > maxVisible)
1104
- meta.push(`${this.selected + 1}/${visible.length}`);
1105
- if (this.filter)
1106
- meta.push(`filter: ${this.filter}`);
1107
- meta.push(`sort: ${this.sortMode}`);
1108
- lines.push(ink4(` ${meta.join(" \xB7 ")}`));
1109
- return ["", ...lines, ""];
1110
- }
1111
- }
1112
- function normalizeTasks(payload) {
1113
- return payload.map((task) => ({
1114
- id: typeof task.id === "string" || typeof task.id === "number" ? String(task.id) : "",
1115
- status: typeof task.status === "string" ? task.status : "open",
1116
- title: typeof task.title === "string" ? task.title : "(untitled)"
1117
- })).filter((task) => task.id);
1118
- }
1119
-
1120
- class TasksView {
1121
- tasks = [];
1122
- selected = 0;
1123
- loading = true;
1124
- error = null;
1125
- tick = 0;
1126
- setTasks(tasks) {
1127
- this.tasks = tasks;
1128
- this.selected = Math.min(this.selected, Math.max(0, tasks.length - 1));
1129
- this.loading = false;
1130
- this.error = null;
1131
- }
1132
- moveSelection(delta) {
1133
- if (this.tasks.length === 0)
1134
- return;
1135
- this.selected = Math.max(0, Math.min(this.tasks.length - 1, this.selected + delta));
1136
- }
1137
- selectedTask() {
1138
- return this.tasks[this.selected] ?? null;
1139
- }
1140
- invalidate() {}
1141
- render(width) {
1142
- return this.renderLines(width).map((line) => truncateToWidth(line, Math.max(10, width - 1)));
1143
- }
1144
- renderLines(width) {
1145
- if (this.loading) {
1146
- const spinner = RIG_SPINNER_FRAMES[this.tick % RIG_SPINNER_FRAMES.length];
1147
- return ["", ` ${accent(spinner)} ${ink3("reading tasks from the server\u2026")}`, ""];
1148
- }
1149
- if (this.error) {
1150
- return ["", ` ${red("tasks unavailable:")} ${ink2(this.error)}`, ""];
1151
- }
1152
- if (this.tasks.length === 0) {
1153
- return ["", ` ${ink2("no ready tasks \u2014 the task source is drained")}`, ""];
1154
- }
1155
- const maxVisible = 16;
1156
- const start = Math.max(0, Math.min(this.selected - Math.floor(maxVisible / 2), this.tasks.length - maxVisible));
1157
- const window = this.tasks.slice(start, start + maxVisible);
1158
- const lines = window.map((task, index) => {
1159
- const absolute = start + index;
1160
- const isSelected = absolute === this.selected;
1161
- const id = task.id.padEnd(8).slice(0, 12);
1162
- const status = statusColor(task.status)(task.status.padEnd(12));
1163
- const title = truncateToWidth(task.title, Math.max(8, width - 32));
1164
- const row = ` ${isSelected ? bold(ink(id)) : ink3(id)} ${status} ${isSelected ? ink(title) : ink2(title)}`;
1165
- return isSelected ? accent("\u258C") + row : " " + row;
1166
- });
1167
- if (this.tasks.length > maxVisible)
1168
- lines.push(ink4(` ${this.selected + 1}/${this.tasks.length}`));
1169
- return ["", ...lines, ""];
1170
- }
1171
- }
1172
- function firstQuestion(record) {
1173
- const payload = record && typeof record === "object" ? record : {};
1174
- const questions = Array.isArray(payload.questions) ? payload.questions : [];
1175
- const question = questions[0];
1176
- if (!question)
1177
- return { id: null, text: null, options: [] };
1178
- const options = Array.isArray(question.options) ? question.options.flatMap((option) => {
1179
- if (typeof option === "string")
1180
- return [option];
1181
- if (option && typeof option === "object" && !Array.isArray(option)) {
1182
- const label = option.label ?? option.value;
1183
- return typeof label === "string" ? [label] : [];
1184
- }
1185
- return [];
1186
- }) : [];
1187
- return {
1188
- id: typeof question.id === "string" ? question.id : null,
1189
- text: typeof question.question === "string" ? question.question : null,
1190
- options
1191
- };
1192
- }
1193
- function normalizeInboxItems(approvals, inputs) {
1194
- const items = [];
1195
- for (const record of approvals) {
1196
- if (!record.runId || !record.requestId)
1197
- continue;
1198
- const detail = record.record && typeof record.record === "object" ? record.record : {};
1199
- const prompt = typeof detail.prompt === "string" ? String(detail.prompt) : typeof detail.title === "string" ? String(detail.title) : "approval requested";
1200
- items.push({ kind: "approval", runId: record.runId, requestId: record.requestId, summary: prompt, questionId: null, options: [] });
1201
- }
1202
- for (const record of inputs) {
1203
- if (!record.runId || !record.requestId)
1204
- continue;
1205
- const question = firstQuestion(record.record);
1206
- items.push({
1207
- kind: "input",
1208
- runId: record.runId,
1209
- requestId: record.requestId,
1210
- summary: question.text ?? "input requested",
1211
- questionId: question.id,
1212
- options: question.options
1213
- });
1214
- }
1215
- return items;
1216
- }
1217
-
1218
- class InboxView {
1219
- items = [];
1220
- selected = 0;
1221
- loading = true;
1222
- error = null;
1223
- tick = 0;
1224
- setItems(items) {
1225
- this.items = items;
1226
- this.selected = Math.min(this.selected, Math.max(0, items.length - 1));
1227
- this.loading = false;
1228
- this.error = null;
1229
- }
1230
- moveSelection(delta) {
1231
- if (this.items.length === 0)
1232
- return;
1233
- this.selected = Math.max(0, Math.min(this.items.length - 1, this.selected + delta));
1234
- }
1235
- selectedItem() {
1236
- return this.items[this.selected] ?? null;
1237
- }
1238
- invalidate() {}
1239
- render(width) {
1240
- return this.renderLines(width).map((line) => truncateToWidth(line, Math.max(10, width - 1)));
1241
- }
1242
- renderLines(width) {
1243
- if (this.loading) {
1244
- const spinner = RIG_SPINNER_FRAMES[this.tick % RIG_SPINNER_FRAMES.length];
1245
- return ["", ` ${accent(spinner)} ${ink3("reading the inbox\u2026")}`, ""];
1246
- }
1247
- if (this.error) {
1248
- return ["", ` ${red("inbox unavailable:")} ${ink2(this.error)}`, ""];
1249
- }
1250
- if (this.items.length === 0) {
1251
- return ["", ` ${ink2("inbox clear \u2014 no drone is waiting on you")}`, ""];
1252
- }
1253
- const maxVisible = 14;
1254
- const start = Math.max(0, Math.min(this.selected - Math.floor(maxVisible / 2), this.items.length - maxVisible));
1255
- const window = this.items.slice(start, start + maxVisible);
1256
- const lines = window.flatMap((item, index) => {
1257
- const absolute = start + index;
1258
- const isSelected = absolute === this.selected;
1259
- const kind = item.kind === "approval" ? accentDim("approval") : cyan("input ");
1260
- const run = item.runId.slice(0, 8);
1261
- const summary = truncateToWidth(item.summary, Math.max(8, width - 30));
1262
- const row = ` ${kind} ${isSelected ? bold(ink(run)) : ink3(run)} ${isSelected ? ink(summary) : ink2(summary)}`;
1263
- const main = isSelected ? accent("\u258C") + row : " " + row;
1264
- if (isSelected && item.kind === "input" && item.options.length > 0) {
1265
- return [main, ink4(` options: ${item.options.join(" \xB7 ")}`)];
1266
- }
1267
- return [main];
1268
- });
1269
- if (this.items.length > maxVisible)
1270
- lines.push(ink4(` ${this.selected + 1}/${this.items.length}`));
1271
- return ["", ...lines, ""];
1272
- }
1273
- }
1274
- function hairline(width) {
1275
- return ink4("\u2500".repeat(Math.max(0, width)));
1276
- }
1277
- function hasRigProject(projectRoot) {
1278
- return ["rig.config.ts", "rig.config.mts", "rig.config.json", ".rig"].some((name) => existsSync3(resolvePath(projectRoot, name)));
1279
- }
1280
-
1281
- class Rule {
1282
- invalidate() {}
1283
- render(width) {
1284
- return [hairline(width)];
1285
- }
1286
- }
1287
-
1288
- class HelpView {
1289
- group;
1290
- offset = 0;
1291
- built = null;
1292
- constructor(group) {
1293
- this.group = group;
1294
- }
1295
- build(width) {
1296
- if (this.built)
1297
- return this.built;
1298
- const { sections, groups } = helpCatalog();
1299
- const lines = [];
1300
- const groupAnchors = new Map;
1301
- const columnWidth = Math.min(38, Math.max(24, Math.floor(width * 0.4)));
1302
- const row = (command, description) => {
1303
- const left = command.length >= columnWidth ? `${command} ` : command.padEnd(columnWidth);
1304
- return ` ${bold(ink(left))} ${ink2(truncateToWidth(description, Math.max(16, width - columnWidth - 4)))}`;
1305
- };
1306
- for (const section of sections) {
1307
- lines.push(`${accent("\u25C7")} ${bold(ink(section.title))} ${ink3(`\u2014 ${section.subtitle}`)}`);
1308
- for (const command of section.commands)
1309
- lines.push(row(command.command, command.description));
1310
- lines.push("");
1311
- }
1312
- lines.push(`${accent("\u25C7")} ${bold(ink("command groups"))} ${ink3("\u2014 every `rig <group>` surface")}`);
1313
- lines.push("");
1314
- for (const group of groups) {
1315
- groupAnchors.set(group.name, lines.length);
1316
- lines.push(`${accentDim("\u258D")}${bold(ink(`rig ${group.name}`))} ${ink3(`\u2014 ${group.summary}`)}`);
1317
- for (const usage of group.usage)
1318
- lines.push(` ${cyan(usage)}`);
1319
- for (const command of group.commands)
1320
- lines.push(row(command.command, command.description));
1321
- if (group.examples?.length) {
1322
- for (const example of group.examples)
1323
- lines.push(` ${ink4("$")} ${ink2(example)}`);
1324
- }
1325
- if (group.next?.length) {
1326
- for (const next of group.next)
1327
- lines.push(` ${accent("\u203A")} ${ink3(next)}`);
1328
- }
1329
- lines.push("");
1330
- }
1331
- this.built = { lines, groupAnchors };
1332
- if (this.group) {
1333
- const anchor = groupAnchors.get(this.group);
1334
- if (anchor !== undefined)
1335
- this.offset = anchor;
1336
- }
1337
- return this.built;
1338
- }
1339
- scroll(delta) {
1340
- if (!this.built)
1341
- return;
1342
- const max = Math.max(0, this.built.lines.length - 10);
1343
- this.offset = Math.max(0, Math.min(max, this.offset + delta));
1344
- }
1345
- invalidate() {
1346
- this.built = null;
1347
- }
1348
- render(width) {
1349
- const { lines } = this.build(width);
1350
- const viewport = Math.max(10, (process.stdout.rows ?? 30) - 8);
1351
- const slice = lines.slice(this.offset, this.offset + viewport);
1352
- const more = this.offset + viewport < lines.length;
1353
- return [
1354
- "",
1355
- ...slice.map((line) => truncateToWidth(` ${line}`, Math.max(10, width - 1))),
1356
- more ? ink4(` \u2026 ${lines.length - this.offset - viewport} more (\u2193)`) : ""
1357
- ];
1358
- }
1359
- }
1360
- async function runOperatorBoard(context, options = {}) {
1361
- const terminal = new ProcessTerminal2;
1362
- const tui = new TUI2(terminal);
1363
- const list = new RunsList;
1364
- const helpView = new HelpView(options.helpGroup);
1365
- const tasksView = new TasksView;
1366
- const inboxView = new InboxView;
1367
- const header = new Text2("");
1368
- const footer = new Text2("");
1369
- let view = options.initialView ?? "board";
1370
- let serverLabel = "resolving server\u2026";
1371
- let inboxCounts = null;
1372
- let notice = null;
1373
- let inputLine = null;
1374
- let tick = 0;
1375
- const viewHost = {
1376
- invalidate() {},
1377
- render(width) {
1378
- if (view === "help")
1379
- return helpView.render(width);
1380
- if (view === "tasks")
1381
- return tasksView.render(width);
1382
- if (view === "inbox")
1383
- return inboxView.render(width);
1384
- return list.render(width);
1385
- }
1386
- };
1387
- const renderHeader = () => {
1388
- const crumbs = {
1389
- board: "",
1390
- help: ` ${ink4("\u203A")} ${ink2("help")}`,
1391
- tasks: ` ${ink4("\u203A")} ${ink2("new run")}`,
1392
- inbox: ` ${ink4("\u203A")} ${ink2("inbox")}`
1393
- };
1394
- header.setText(` ${accent("\u258D")}${bold(ink("rig"))} ${ink3("\u2014 operate the drones")}${crumbs[view]} ${ink4("\xB7")} ${cyan(serverLabel)}`);
1395
- };
1396
- const renderFooter = () => {
1397
- if (inputLine) {
1398
- const label = inputLine.kind === "search" ? `${accent("/")}${ink(inputLine.buffer)}` : `${accentDim("answer")} ${ink3(`(${inputLine.item.runId.slice(0, 8)})`)} ${accent("\u276F")} ${ink(inputLine.buffer)}`;
1399
- footer.setText([
1400
- ` ${label}${accent("\u2588")}`,
1401
- ` ${accent("enter")}${ink3(inputLine.kind === "search" ? " keep filter" : " send answer")} ${accent("esc")}${ink3(inputLine.kind === "search" ? " clear" : " cancel")}`
1402
- ].join(`
1403
- `));
1404
- return;
1405
- }
1406
- if (view === "help") {
1407
- footer.setText(` ${accent("\u2190")}${ink3(" back")} ${accent("\u2191\u2193")}${ink3(" scroll")} ${accent("esc")}${ink3(" board")} ${accent("q")}${ink3(" quit")}`);
1408
- return;
1409
- }
1410
- if (view === "tasks") {
1411
- footer.setText([
1412
- ` ${notice ? accentDim(notice) : ink4("pick a task \u2014 a drone launches with project defaults")}`,
1413
- ` ${accent("\u2190")}${ink3(" back")} ${accent("enter")}${ink3(" dispatch")} ${accent("r")}${ink3(" reload")} ${accent("esc")}${ink3(" board")} ${accent("q")}${ink3(" quit")}`
1414
- ].join(`
1415
- `));
1416
- return;
1417
- }
1418
- if (view === "inbox") {
1419
- footer.setText([
1420
- ` ${notice ? accentDim(notice) : ink4("gates the fleet is waiting on \u2014 resolve them here")}`,
1421
- ` ${accent("\u2190")}${ink3(" back")} ${accent("a")}${ink3(" approve")} ${accent("d")}${ink3(" reject")} ${accent("enter")}${ink3(" answer input")} ${accent("r")}${ink3(" reload")} ${accent("esc")}${ink3(" board")}`
1422
- ].join(`
1423
- `));
1424
- return;
1425
- }
1426
- const pendingCount = inboxCounts ? inboxCounts.approvals + inboxCounts.inputs : 0;
1427
- const pending = pendingCount > 0 ? `${RIG_SPINNER_FRAMES[tick % RIG_SPINNER_FRAMES.length]} ${pendingCount} inbox gate${pendingCount === 1 ? "" : "s"} waiting \u2014 press i` : "fleet idle gates clear";
1428
- const status = notice ?? pending;
1429
- footer.setText([
1430
- ` ${pendingCount > 0 ? accentDim(status) : ink4(status)}`,
1431
- ` ${accent("enter")}${ink3(" attach")} ${accent("n")}${ink3(" new run")} ${accent("i")}${ink3(" inbox")} ${accent("/")}${ink3(" search")} ${accent("o")}${ink3(" sort")} ${accent("x")}${ink3(" stop")} ${accent("?")}${ink3(" help")} ${accent("q")}${ink3(" quit")}`
1432
- ].join(`
1433
- `));
1434
- };
1435
- const setView = (next) => {
1436
- view = next;
1437
- notice = null;
1438
- renderHeader();
1439
- renderFooter();
1440
- tui.requestRender();
1441
- };
1442
- renderHeader();
1443
- renderFooter();
1444
- tui.addChild(header);
1445
- tui.addChild(new Rule);
1446
- tui.addChild(viewHost);
1447
- tui.addChild(new Rule);
1448
- tui.addChild(footer);
1449
- let stopped = false;
1450
- let outcome = { action: "quit" };
1451
- const finish = (result) => {
1452
- if (stopped)
1453
- return;
1454
- stopped = true;
1455
- outcome = result;
1456
- tui.stop();
1457
- };
1458
- let refreshInFlight = false;
1459
- const refresh = async () => {
1460
- if (refreshInFlight)
1461
- return;
1462
- if (!hasRigProject(context.projectRoot)) {
1463
- list.loading = false;
1464
- list.noProject = true;
1465
- notice = null;
1466
- renderFooter();
1467
- tui.requestRender();
1468
- return;
1469
- }
1470
- list.noProject = false;
1471
- refreshInFlight = true;
1472
- try {
1473
- const [runs, counts] = await Promise.all([
1474
- listRunsViaServer(context),
1475
- readPendingInboxCounts(context)
1476
- ]);
1477
- list.setRuns(normalizeRuns(runs));
1478
- inboxCounts = counts;
1479
- notice = null;
1480
- } catch (error) {
1481
- list.loading = false;
1482
- notice = `server unreachable: ${oneLine(error instanceof Error ? error.message : String(error))}`;
1483
- } finally {
1484
- refreshInFlight = false;
1485
- }
1486
- renderFooter();
1487
- tui.requestRender();
1488
- };
1489
- const refreshTasks = async () => {
1490
- tasksView.loading = true;
1491
- tui.requestRender();
1492
- try {
1493
- const tasks = await listWorkspaceTasksViaServer(context, { limit: BOARD_TASK_PAGE });
1494
- tasksView.setTasks(normalizeTasks(tasks));
1495
- } catch (error) {
1496
- tasksView.loading = false;
1497
- tasksView.error = oneLine(error instanceof Error ? error.message : String(error));
1498
- }
1499
- tui.requestRender();
1500
- };
1501
- const refreshInbox = async () => {
1502
- inboxView.loading = true;
1503
- tui.requestRender();
1504
- try {
1505
- const [approvals, inputs] = await Promise.all([
1506
- listInboxRecords(context, "approvals", { pendingOnly: true }),
1507
- listInboxRecords(context, "inputs", { pendingOnly: true })
1508
- ]);
1509
- inboxView.setItems(normalizeInboxItems(approvals, inputs));
1510
- } catch (error) {
1511
- inboxView.loading = false;
1512
- inboxView.error = oneLine(error instanceof Error ? error.message : String(error));
1513
- }
1514
- tui.requestRender();
1515
- };
1516
- const dispatchTask = async (task) => {
1517
- notice = `dispatching drone for ${task.id}\u2026`;
1518
- renderFooter();
1519
- tui.requestRender();
1520
- try {
1521
- const defaults = await loadTaskRunProjectDefaults(context.projectRoot);
1522
- const submitted = await submitTaskRunViaServer(context, {
1523
- runId: randomUUID(),
1524
- taskId: task.id,
1525
- runtimeAdapter: normalizeRuntimeAdapter(defaults.runtimeAdapter),
1526
- model: defaults.model,
1527
- runtimeMode: defaults.runtimeMode ?? "full-access",
1528
- interactionMode: "default",
1529
- prMode: defaults.prMode
1530
- });
1531
- notice = `drone ${String(submitted.runId).slice(0, 8)} dispatched on ${task.id} \u2014 enter attaches`;
1532
- setView("board");
1533
- notice = `drone ${String(submitted.runId).slice(0, 8)} dispatched on ${task.id}`;
1534
- renderFooter();
1535
- await refresh();
1536
- } catch (error) {
1537
- notice = `dispatch failed: ${oneLine(error instanceof Error ? error.message : String(error))}`;
1538
- renderFooter();
1539
- tui.requestRender();
1540
- }
1541
- };
1542
- const resolveApproval = async (item, decision) => {
1543
- notice = `${decision === "approve" ? "approving" : "rejecting"} ${item.requestId.slice(0, 12)}\u2026`;
1544
- renderFooter();
1545
- tui.requestRender();
1546
- try {
1547
- await requestServerJson(context, "/api/inbox/approvals/resolve", {
1548
- method: "POST",
1549
- headers: { "content-type": "application/json" },
1550
- body: JSON.stringify({ runId: item.runId, requestId: item.requestId, decision, note: null })
1551
- });
1552
- notice = `${decision === "approve" ? "approved" : "rejected"} \u2014 drone resumes`;
1553
- } catch (error) {
1554
- notice = `resolve failed: ${oneLine(error instanceof Error ? error.message : String(error))}`;
1555
- }
1556
- renderFooter();
1557
- await refreshInbox();
1558
- inboxCounts = await readPendingInboxCounts(context).catch(() => inboxCounts) ?? inboxCounts;
1559
- };
1560
- const answerInput = async (item, text) => {
1561
- notice = `answering ${item.requestId.slice(0, 12)}\u2026`;
1562
- renderFooter();
1563
- tui.requestRender();
1564
- try {
1565
- await requestServerJson(context, "/api/inbox/inputs/respond", {
1566
- method: "POST",
1567
- headers: { "content-type": "application/json" },
1568
- body: JSON.stringify({
1569
- runId: item.runId,
1570
- requestId: item.requestId,
1571
- answers: { [item.questionId ?? "response"]: text }
1572
- })
1573
- });
1574
- notice = "answer sent \u2014 drone resumes";
1575
- } catch (error) {
1576
- notice = `answer failed: ${oneLine(error instanceof Error ? error.message : String(error))}`;
1577
- }
1578
- renderFooter();
1579
- await refreshInbox();
1580
- inboxCounts = await readPendingInboxCounts(context).catch(() => inboxCounts) ?? inboxCounts;
1581
- };
1582
- resolveServerConnectionLabel(context.projectRoot).then((label) => {
1583
- serverLabel = label;
1584
- renderHeader();
1585
- tui.requestRender();
1586
- }).catch(() => {});
1587
- tui.addInputListener((data) => {
1588
- if (isKeyRelease(data))
1589
- return { consume: true };
1590
- if (inputLine) {
1591
- if (matchesKey2(data, "escape")) {
1592
- if (inputLine.kind === "search")
1593
- list.setFilter("");
1594
- inputLine = null;
1595
- } else if (matchesKey2(data, "enter") || matchesKey2(data, "return")) {
1596
- if (inputLine.kind === "answer" && inputLine.buffer.trim()) {
1597
- answerInput(inputLine.item, inputLine.buffer.trim());
1598
- }
1599
- inputLine = null;
1600
- } else if (matchesKey2(data, "backspace")) {
1601
- inputLine = { ...inputLine, buffer: inputLine.buffer.slice(0, -1) };
1602
- if (inputLine.kind === "search")
1603
- list.setFilter(inputLine.buffer);
1604
- } else if (data.length === 1 && data >= " ") {
1605
- inputLine = { ...inputLine, buffer: inputLine.buffer + data };
1606
- if (inputLine.kind === "search")
1607
- list.setFilter(inputLine.buffer);
1608
- }
1609
- renderFooter();
1610
- tui.requestRender();
1611
- return { consume: true };
1612
- }
1613
- if (data === "q" || matchesKey2(data, "ctrl+c")) {
1614
- finish({ action: "quit" });
1615
- return { consume: true };
1616
- }
1617
- if (view === "help") {
1618
- if (matchesKey2(data, "up") || data === "k")
1619
- helpView.scroll(-1);
1620
- else if (matchesKey2(data, "down") || data === "j")
1621
- helpView.scroll(1);
1622
- else if (matchesKey2(data, "pageUp"))
1623
- helpView.scroll(-15);
1624
- else if (matchesKey2(data, "pageDown") || data === " ")
1625
- helpView.scroll(15);
1626
- else if (matchesKey2(data, "left") || matchesKey2(data, "escape") || data === "?") {
1627
- setView("board");
1628
- return { consume: true };
1629
- }
1630
- tui.requestRender();
1631
- return { consume: true };
1632
- }
1633
- if (view === "tasks") {
1634
- if (matchesKey2(data, "up") || data === "k")
1635
- tasksView.moveSelection(-1);
1636
- else if (matchesKey2(data, "down") || data === "j")
1637
- tasksView.moveSelection(1);
1638
- else if (matchesKey2(data, "enter") || matchesKey2(data, "return")) {
1639
- const task = tasksView.selectedTask();
1640
- if (task)
1641
- dispatchTask(task);
1642
- } else if (data === "r")
1643
- refreshTasks();
1644
- else if (matchesKey2(data, "left") || matchesKey2(data, "escape"))
1645
- setView("board");
1646
- tui.requestRender();
1647
- return { consume: true };
1648
- }
1649
- if (view === "inbox") {
1650
- if (matchesKey2(data, "up") || data === "k")
1651
- inboxView.moveSelection(-1);
1652
- else if (matchesKey2(data, "down") || data === "j")
1653
- inboxView.moveSelection(1);
1654
- else if (data === "a") {
1655
- const item = inboxView.selectedItem();
1656
- if (item?.kind === "approval")
1657
- resolveApproval(item, "approve");
1658
- } else if (data === "d") {
1659
- const item = inboxView.selectedItem();
1660
- if (item?.kind === "approval")
1661
- resolveApproval(item, "reject");
1662
- } else if (matchesKey2(data, "enter") || matchesKey2(data, "return")) {
1663
- const item = inboxView.selectedItem();
1664
- if (item?.kind === "input") {
1665
- inputLine = { kind: "answer", buffer: "", item };
1666
- renderFooter();
1667
- } else if (item?.kind === "approval") {
1668
- resolveApproval(item, "approve");
1669
- }
1670
- } else if (data === "r")
1671
- refreshInbox();
1672
- else if (matchesKey2(data, "left") || matchesKey2(data, "escape"))
1673
- setView("board");
1674
- tui.requestRender();
1675
- return { consume: true };
1676
- }
1677
- if (matchesKey2(data, "up") || data === "k") {
1678
- list.moveSelection(-1);
1679
- tui.requestRender();
1680
- return { consume: true };
1681
- }
1682
- if (matchesKey2(data, "down") || data === "j") {
1683
- list.moveSelection(1);
1684
- tui.requestRender();
1685
- return { consume: true };
1686
- }
1687
- if (matchesKey2(data, "enter") || matchesKey2(data, "return")) {
1688
- const run = list.selectedRun();
1689
- if (run)
1690
- finish({ action: "attach", runId: run.runId });
1691
- return { consume: true };
1692
- }
1693
- if (data === "?" || data === "h") {
1694
- setView("help");
1695
- return { consume: true };
1696
- }
1697
- if (data === "n") {
1698
- setView("tasks");
1699
- refreshTasks();
1700
- return { consume: true };
1701
- }
1702
- if (data === "i") {
1703
- setView("inbox");
1704
- refreshInbox();
1705
- return { consume: true };
1706
- }
1707
- if (data === "/") {
1708
- inputLine = { kind: "search", buffer: list.filter };
1709
- renderFooter();
1710
- tui.requestRender();
1711
- return { consume: true };
1712
- }
1713
- if (data === "o") {
1714
- const mode = list.cycleSort();
1715
- notice = `sorted: ${mode}`;
1716
- renderFooter();
1717
- tui.requestRender();
1718
- return { consume: true };
1719
- }
1720
- if (data === "x") {
1721
- const run = list.selectedRun();
1722
- if (run) {
1723
- notice = `stop requested for ${run.runId.slice(0, 8)}\u2026`;
1724
- renderFooter();
1725
- tui.requestRender();
1726
- stopRunViaServer(context, run.runId).then(() => refresh()).catch(() => refresh());
1727
- }
1728
- return { consume: true };
1729
- }
1730
- if (data === "r") {
1731
- refresh();
1732
- return { consume: true };
1733
- }
1734
- if (matchesKey2(data, "escape")) {
1735
- if (list.filter) {
1736
- list.setFilter("");
1737
- renderFooter();
1738
- tui.requestRender();
1739
- return { consume: true };
1740
- }
1741
- finish({ action: "quit" });
1742
- return { consume: true };
1743
- }
1744
- return { consume: true };
1745
- });
1746
- const animation = setInterval(() => {
1747
- tick += 1;
1748
- list.tick = tick;
1749
- tasksView.tick = tick;
1750
- inboxView.tick = tick;
1751
- if (list.loading || list.runs.length === 0 || view === "tasks" && tasksView.loading || view === "inbox" && inboxView.loading || inboxCounts && inboxCounts.approvals + inboxCounts.inputs > 0) {
1752
- renderFooter();
1753
- tui.requestRender();
1754
- }
1755
- }, BOARD_TICK_MS);
1756
- const refreshTimer = setInterval(() => {
1757
- refresh();
1758
- }, BOARD_REFRESH_MS);
1759
- tui.start();
1760
- refresh();
1761
- await new Promise((resolve3) => {
1762
- const poll = setInterval(() => {
1763
- if (stopped) {
1764
- clearInterval(poll);
1765
- resolve3();
1766
- }
1767
- }, 50);
1768
- });
1769
- clearInterval(animation);
1770
- clearInterval(refreshTimer);
1771
- return outcome;
1772
- }
1773
- async function runOperatorBoardLoop(context, attach, options = {}) {
1774
- let initial = options;
1775
- for (;; ) {
1776
- const outcome = await runOperatorBoard(context, initial ?? {});
1777
- initial = null;
1778
- if (outcome.action === "quit")
1779
- return;
1780
- await attach(outcome.runId);
1781
- }
1782
- }
1783
- export {
1784
- runOperatorBoardLoop,
1785
- runOperatorBoard
1786
- };