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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +1 -1
  2. package/dist/bin/rig.js +4507 -1506
  3. package/dist/src/commands/_async-ui.js +152 -0
  4. package/dist/src/commands/_authority-runs.js +2 -3
  5. package/dist/src/commands/_cli-format.js +369 -0
  6. package/dist/src/commands/_connection-state.js +30 -11
  7. package/dist/src/commands/_doctor-checks.js +177 -43
  8. package/dist/src/commands/_help-catalog.js +485 -0
  9. package/dist/src/commands/_json-output.js +56 -0
  10. package/dist/src/commands/_operator-surface.js +220 -0
  11. package/dist/src/commands/_operator-view.js +595 -72
  12. package/dist/src/commands/_parsers.js +18 -11
  13. package/dist/src/commands/_pi-frontend.js +411 -0
  14. package/dist/src/commands/_pi-install.js +4 -3
  15. package/dist/src/commands/_policy.js +12 -5
  16. package/dist/src/commands/_preflight.js +187 -127
  17. package/dist/src/commands/_run-driver-helpers.js +75 -22
  18. package/dist/src/commands/_run-replay.js +142 -0
  19. package/dist/src/commands/_server-client.js +343 -60
  20. package/dist/src/commands/_snapshot-upload.js +160 -38
  21. package/dist/src/commands/_spinner.js +65 -0
  22. package/dist/src/commands/_task-picker.js +44 -16
  23. package/dist/src/commands/agent.js +39 -20
  24. package/dist/src/commands/browser.js +28 -21
  25. package/dist/src/commands/connect.js +146 -33
  26. package/dist/src/commands/dist.js +19 -12
  27. package/dist/src/commands/doctor.js +304 -44
  28. package/dist/src/commands/github.js +301 -52
  29. package/dist/src/commands/inbox.js +679 -72
  30. package/dist/src/commands/init.js +622 -118
  31. package/dist/src/commands/inspect.js +515 -32
  32. package/dist/src/commands/inspector.js +20 -13
  33. package/dist/src/commands/pi.js +177 -0
  34. package/dist/src/commands/plugin.js +95 -27
  35. package/dist/src/commands/profile-and-review.js +26 -19
  36. package/dist/src/commands/queue.js +32 -12
  37. package/dist/src/commands/remote.js +43 -36
  38. package/dist/src/commands/repo-git-harness.js +22 -15
  39. package/dist/src/commands/run.js +1162 -158
  40. package/dist/src/commands/server.js +373 -56
  41. package/dist/src/commands/setup.js +316 -62
  42. package/dist/src/commands/stats.js +1030 -0
  43. package/dist/src/commands/task-report-bug.js +29 -22
  44. package/dist/src/commands/task-run-driver.js +862 -129
  45. package/dist/src/commands/task.js +1423 -311
  46. package/dist/src/commands/test.js +15 -8
  47. package/dist/src/commands/workspace.js +18 -11
  48. package/dist/src/commands.js +4446 -1499
  49. package/dist/src/index.js +4502 -1504
  50. package/dist/src/launcher.js +77 -13
  51. package/dist/src/report-bug.js +3 -3
  52. package/dist/src/runner.js +16 -22
  53. package/package.json +10 -5
@@ -0,0 +1,152 @@
1
+ // @bun
2
+ // packages/cli/src/commands/_async-ui.ts
3
+ import pc from "picocolors";
4
+
5
+ // packages/cli/src/commands/_spinner.ts
6
+ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
7
+ function createTtySpinner(input) {
8
+ const output = input.output ?? process.stdout;
9
+ const isTty = output.isTTY === true;
10
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
11
+ let label = input.label;
12
+ let frame = 0;
13
+ let paused = false;
14
+ let stopped = false;
15
+ let lastPrintedLabel = "";
16
+ const render = () => {
17
+ if (stopped || paused)
18
+ return;
19
+ if (!isTty) {
20
+ if (label !== lastPrintedLabel) {
21
+ output.write(`${label}
22
+ `);
23
+ lastPrintedLabel = label;
24
+ }
25
+ return;
26
+ }
27
+ frame = (frame + 1) % frames.length;
28
+ const glyph = frames[frame] ?? frames[0] ?? "";
29
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
30
+ };
31
+ const clearLine = () => {
32
+ if (isTty)
33
+ output.write("\r\x1B[2K");
34
+ };
35
+ render();
36
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 120) : null;
37
+ return {
38
+ setLabel(next) {
39
+ label = next;
40
+ render();
41
+ },
42
+ pause() {
43
+ paused = true;
44
+ clearLine();
45
+ },
46
+ resume() {
47
+ if (stopped)
48
+ return;
49
+ paused = false;
50
+ render();
51
+ },
52
+ stop(finalLine) {
53
+ if (stopped)
54
+ return;
55
+ stopped = true;
56
+ if (timer)
57
+ clearInterval(timer);
58
+ clearLine();
59
+ if (finalLine)
60
+ output.write(`${finalLine}
61
+ `);
62
+ }
63
+ };
64
+ }
65
+
66
+ // packages/cli/src/runner.ts
67
+ import { EventBus } from "@rig/runtime/control-plane/runtime/events";
68
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
69
+ import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
70
+ import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
71
+
72
+ // packages/cli/src/commands/_server-client.ts
73
+ import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
74
+ var scopedGitHubBearerTokens = new Map;
75
+ var serverPhaseListener = null;
76
+ function setServerPhaseListener(listener) {
77
+ const previous = serverPhaseListener;
78
+ serverPhaseListener = listener;
79
+ return previous;
80
+ }
81
+ var serverReachabilityCache = new Map;
82
+ var RESUMABLE_RUN_STATUSES = new Set([
83
+ "created",
84
+ "preparing",
85
+ "running",
86
+ "validating",
87
+ "reviewing",
88
+ "stopped",
89
+ "failed",
90
+ "needs-attention",
91
+ "needs_attention"
92
+ ]);
93
+
94
+ // packages/cli/src/commands/_async-ui.ts
95
+ var CLACK_SPINNER_FRAMES = ["\u25D2", "\u25D0", "\u25D3", "\u25D1"];
96
+ var DONE_SYMBOL = pc.green("\u25C7");
97
+ var FAIL_SYMBOL = pc.red("\u25A0");
98
+ var activeUpdate = null;
99
+ async function withSpinner(label, work, options = {}) {
100
+ if (options.outputMode === "json") {
101
+ return work(() => {});
102
+ }
103
+ if (activeUpdate) {
104
+ const outer = activeUpdate;
105
+ outer(label);
106
+ return work(outer);
107
+ }
108
+ const output = options.output ?? process.stderr;
109
+ const isTty = output.isTTY === true;
110
+ let lastLabel = label;
111
+ if (!isTty) {
112
+ output.write(`${label}
113
+ `);
114
+ const update2 = (next) => {
115
+ lastLabel = next;
116
+ };
117
+ activeUpdate = update2;
118
+ const previousListener2 = setServerPhaseListener(update2);
119
+ try {
120
+ return await work(update2);
121
+ } finally {
122
+ activeUpdate = null;
123
+ setServerPhaseListener(previousListener2);
124
+ }
125
+ }
126
+ const spinner = createTtySpinner({
127
+ label,
128
+ output,
129
+ frames: CLACK_SPINNER_FRAMES,
130
+ styleFrame: (frame) => pc.magenta(frame)
131
+ });
132
+ const update = (next) => {
133
+ lastLabel = next;
134
+ spinner.setLabel(next);
135
+ };
136
+ activeUpdate = update;
137
+ const previousListener = setServerPhaseListener(update);
138
+ try {
139
+ const result = await work(update);
140
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
141
+ return result;
142
+ } catch (error) {
143
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
144
+ throw error;
145
+ } finally {
146
+ activeUpdate = null;
147
+ setServerPhaseListener(previousListener);
148
+ }
149
+ }
150
+ export {
151
+ withSpinner
152
+ };
@@ -5,8 +5,7 @@ import { resolve } from "path";
5
5
  import {
6
6
  readAuthorityRun,
7
7
  readJsonlFile,
8
- resolveAuthorityRunDir,
9
- writeJsonFile
8
+ writeAuthorityRunRecord
10
9
  } from "@rig/runtime/control-plane/authority-files";
11
10
 
12
11
  // packages/cli/src/commands/_paths.ts
@@ -100,7 +99,7 @@ function upsertAgentAuthorityRun(projectRoot, input) {
100
99
  } else if ("errorText" in next) {
101
100
  delete next.errorText;
102
101
  }
103
- writeJsonFile(resolve(resolveAuthorityRunDir(projectRoot, input.runId), "run.json"), next);
102
+ writeAuthorityRunRecord(projectRoot, input.runId, next);
104
103
  return next;
105
104
  }
106
105
  export {
@@ -0,0 +1,369 @@
1
+ // @bun
2
+ // packages/cli/src/commands/_cli-format.ts
3
+ import { log, note } from "@clack/prompts";
4
+ import pc from "picocolors";
5
+ function stringField(record, key, fallback = "") {
6
+ const value = record[key];
7
+ return typeof value === "string" && value.trim() ? value.trim() : fallback;
8
+ }
9
+ function numberField(record, key) {
10
+ const value = record[key];
11
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
12
+ }
13
+ function arrayField(record, key) {
14
+ const value = record[key];
15
+ return Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() ? [entry.trim()] : []) : [];
16
+ }
17
+ function rawObject(record) {
18
+ const raw = record.raw;
19
+ return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
20
+ }
21
+ function truncate(value, width) {
22
+ if (value.length <= width)
23
+ return value;
24
+ if (width <= 1)
25
+ return "\u2026";
26
+ return `${value.slice(0, width - 1)}\u2026`;
27
+ }
28
+ function pad(value, width) {
29
+ return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
30
+ }
31
+ function statusColor(status) {
32
+ const normalized = status.toLowerCase();
33
+ if (["completed", "merged", "closed", "done", "accepted", "pass", "selected", "approved"].includes(normalized))
34
+ return pc.green;
35
+ if (["failed", "needs_attention", "needs-attention", "blocked", "error", "rejected"].includes(normalized))
36
+ return pc.red;
37
+ if (["running", "reviewing", "validating", "in_progress", "in-progress", "remote"].includes(normalized))
38
+ return pc.cyan;
39
+ if (["ready", "open", "queued", "created", "preparing", "local", "pending"].includes(normalized))
40
+ return pc.yellow;
41
+ return pc.dim;
42
+ }
43
+ function compactDate(value) {
44
+ if (!value.trim())
45
+ return "";
46
+ const parsed = Date.parse(value);
47
+ if (!Number.isFinite(parsed))
48
+ return value;
49
+ return new Date(parsed).toISOString().replace("T", " ").replace(/\.\d{3}Z$/, "Z");
50
+ }
51
+ function compactValue(value) {
52
+ if (value === null || value === undefined)
53
+ return "";
54
+ if (typeof value === "string")
55
+ return value;
56
+ if (typeof value === "number" || typeof value === "boolean")
57
+ return String(value);
58
+ if (Array.isArray(value))
59
+ return value.map(compactValue).filter(Boolean).join(", ");
60
+ return JSON.stringify(value);
61
+ }
62
+ function firstString(record, keys, fallback = "") {
63
+ for (const key of keys) {
64
+ const value = stringField(record, key);
65
+ if (value)
66
+ return value;
67
+ }
68
+ return fallback;
69
+ }
70
+ function runIdOf(run) {
71
+ return firstString(run, ["runId", "id"], "(unknown-run)");
72
+ }
73
+ function taskIdOf(run) {
74
+ return firstString(run, ["taskId", "task", "task_id"]);
75
+ }
76
+ function runTitleOf(run) {
77
+ return firstString(run, ["title", "summary", "name"], taskIdOf(run) || "(untitled)");
78
+ }
79
+ function requestIdOf(entry) {
80
+ return firstString(entry, ["requestId", "id", "approvalId", "inputId"], "(unknown-request)");
81
+ }
82
+ function shouldUseClackOutput() {
83
+ return Boolean(process.stdout.isTTY) && process.env.RIG_CLI_PLAIN_HELP !== "1";
84
+ }
85
+ function printFormattedOutput(message, options = {}) {
86
+ if (!shouldUseClackOutput()) {
87
+ console.log(message);
88
+ return;
89
+ }
90
+ if (options.title)
91
+ note(message, options.title);
92
+ else
93
+ log.message(message);
94
+ }
95
+ function formatStatusPill(status) {
96
+ const label = status || "unknown";
97
+ return statusColor(label)(`\u25CF ${label}`);
98
+ }
99
+ function formatSection(title, subtitle) {
100
+ return `${pc.bold(pc.cyan("\u25C6"))} ${pc.bold(title)}${subtitle ? pc.dim(` \u2014 ${subtitle}`) : ""}`;
101
+ }
102
+ function formatSuccessCard(title, rows = []) {
103
+ const body = rows.filter(([, value]) => value !== undefined && value !== null && String(value).length > 0).map(([key, value]) => `${pc.dim("\u2502")} ${pc.dim(key.padEnd(12))} ${value}`);
104
+ return [formatSection(title), ...body].join(`
105
+ `);
106
+ }
107
+ function formatNextSteps(steps) {
108
+ if (steps.length === 0)
109
+ return [];
110
+ return [pc.bold("Next"), ...steps.map((step) => `${pc.dim("\u203A")} ${step}`)];
111
+ }
112
+ function formatTaskList(tasks, options = {}) {
113
+ if (options.raw)
114
+ return tasks.map((task) => JSON.stringify(task)).join(`
115
+ `);
116
+ if (tasks.length === 0)
117
+ 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(`
118
+ `);
119
+ const rows = tasks.map((task) => {
120
+ const raw = rawObject(task);
121
+ const id = stringField(task, "id", "<unknown>");
122
+ const status = stringField(task, "status", "unknown");
123
+ const title = stringField(task, "title", "Untitled task");
124
+ const source = stringField(task, "source", stringField(raw, "source", ""));
125
+ const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
126
+ return { id, status, title, source, labels };
127
+ });
128
+ const idWidth = Math.min(18, Math.max(4, ...rows.map((row) => row.id.length)));
129
+ const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
130
+ const header = `${pc.bold(pad("TASK", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
131
+ const body = rows.map((row) => {
132
+ const labels = row.labels.length > 0 ? pc.dim(` ${row.labels.slice(0, 4).map((label) => `#${label}`).join(" ")}`) : "";
133
+ const source = row.source ? pc.dim(` ${row.source}`) : "";
134
+ return [
135
+ pc.bold(pad(truncate(row.id, idWidth), idWidth)),
136
+ statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
137
+ `${row.title}${labels}${source}`
138
+ ].join(" ");
139
+ });
140
+ 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(`
141
+ `);
142
+ }
143
+ function formatTaskCard(task, options = {}) {
144
+ const raw = rawObject(task);
145
+ const id = stringField(task, "id", stringField(raw, "id", "<unknown>"));
146
+ const status = stringField(task, "status", stringField(raw, "status", "unknown"));
147
+ const title = stringField(task, "title", stringField(raw, "title", "Untitled task"));
148
+ const source = stringField(task, "source", stringField(raw, "source", ""));
149
+ const url = stringField(task, "url", stringField(raw, "url", ""));
150
+ const number = numberField(task, "number") ?? numberField(raw, "number");
151
+ const labels = arrayField(task, "labels").length > 0 ? arrayField(task, "labels") : arrayField(raw, "labels");
152
+ const assignees = arrayField(task, "assignees").length > 0 ? arrayField(task, "assignees") : arrayField(raw, "assignees");
153
+ const readiness = compactValue(task.readiness ?? raw.readiness);
154
+ const validators = compactValue(task.validators ?? raw.validators ?? task.validation ?? raw.validation);
155
+ const rows = [
156
+ ["task", pc.bold(id)],
157
+ ["status", formatStatusPill(status)],
158
+ ["title", title],
159
+ ["source", source],
160
+ ["number", number],
161
+ ["labels", labels.length ? labels.map((label) => `#${label}`).join(" ") : ""],
162
+ ["assignees", assignees.join(", ")],
163
+ ["readiness", readiness],
164
+ ["validators", validators],
165
+ ["url", url]
166
+ ];
167
+ return [
168
+ formatSuccessCard(options.title ?? (options.selected ? "Selected task" : "Task"), rows),
169
+ "",
170
+ ...formatNextSteps([`Start: \`rig task run ${id}\``, `Details: \`rig task show ${id} --raw\``])
171
+ ].join(`
172
+ `);
173
+ }
174
+ function formatTaskDetails(task) {
175
+ return formatTaskCard(task, { title: "Task details" });
176
+ }
177
+ function formatRunList(runs, options = {}) {
178
+ if (runs.length === 0) {
179
+ return [
180
+ formatSection("Runs", "none recorded"),
181
+ options.source === "server" ? pc.dim("No runs recorded on the selected Rig server.") : pc.dim("No runs recorded in .rig/runs."),
182
+ "",
183
+ ...formatNextSteps(["Start one: `rig task run --next`", "Check server: `rig server status`"])
184
+ ].join(`
185
+ `);
186
+ }
187
+ const rows = runs.map((run) => {
188
+ const runId = stringField(run, "runId", stringField(run, "id", "(unknown-run)"));
189
+ const status = stringField(run, "status", "unknown");
190
+ const taskId = stringField(run, "taskId", "");
191
+ const title = stringField(run, "title", taskId || "(untitled)");
192
+ const runtime = stringField(run, "runtimeAdapter", "");
193
+ return { runId, status, title, runtime };
194
+ });
195
+ const idWidth = Math.min(36, Math.max(6, ...rows.map((row) => row.runId.length)));
196
+ const statusWidth = Math.min(16, Math.max(6, ...rows.map((row) => row.status.length)));
197
+ const header = `${pc.bold(pad("RUN", idWidth))} ${pc.bold(pad("STATUS", statusWidth))} ${pc.bold("TITLE")}`;
198
+ const body = rows.map((row) => [
199
+ pc.bold(pad(truncate(row.runId, idWidth), idWidth)),
200
+ statusColor(row.status)(pad(truncate(row.status, statusWidth), statusWidth)),
201
+ `${row.title}${row.runtime ? pc.dim(` ${row.runtime}`) : ""}`
202
+ ].join(" "));
203
+ return [formatSection("Runs", options.source === "server" ? "selected server" : "local state"), header, ...body, "", ...formatNextSteps(["Follow live: `rig run attach <run-id> --follow`", "Details: `rig run show <run-id>`"])].join(`
204
+ `);
205
+ }
206
+ function formatSubmittedRun(input) {
207
+ const rows = [["run", pc.bold(input.runId)]];
208
+ if (input.task) {
209
+ const id = stringField(input.task, "id", "<unknown>");
210
+ const status = stringField(input.task, "status", "unknown");
211
+ const title = stringField(input.task, "title", "Untitled task");
212
+ rows.push(["task", `${pc.bold(id)} ${formatStatusPill(status)} ${title}`]);
213
+ }
214
+ const runtime = [input.runtimeAdapter || "pi", input.runtimeMode || "full-access", input.interactionMode || "default"].filter(Boolean).join(" \xB7 ");
215
+ rows.push(["runtime", runtime]);
216
+ return [
217
+ formatSuccessCard("Run submitted", rows),
218
+ "",
219
+ ...formatNextSteps([
220
+ `Attach: \`rig run attach ${input.runId} --follow\``,
221
+ `Inspect: \`rig run show ${input.runId}\``,
222
+ input.detached ? "Submitted detached; attach when you are ready." : "Interactive mode opens the enriched bundled Pi (native UI + Rig layers, worker brain)."
223
+ ])
224
+ ].join(`
225
+ `);
226
+ }
227
+ function formatRunCard(run, options = {}) {
228
+ const raw = rawObject(run);
229
+ const merged = { ...raw, ...run };
230
+ const runId = runIdOf(merged);
231
+ const status = firstString(merged, ["status"], "unknown");
232
+ const taskId = taskIdOf(merged);
233
+ const title = runTitleOf(merged);
234
+ const runtime = firstString(merged, ["runtimeAdapter", "runtime", "adapter"]);
235
+ const mode = firstString(merged, ["runtimeMode", "mode"]);
236
+ const interaction = firstString(merged, ["interactionMode"]);
237
+ const created = compactDate(firstString(merged, ["createdAt"]));
238
+ const started = compactDate(firstString(merged, ["startedAt"]));
239
+ const updated = compactDate(firstString(merged, ["updatedAt"]));
240
+ const completed = compactDate(firstString(merged, ["completedAt", "finishedAt"]));
241
+ const worktree = firstString(merged, ["worktreePath", "cwd", "projectRoot"]);
242
+ const piSession = merged.piSession && typeof merged.piSession === "object" && !Array.isArray(merged.piSession) ? firstString(merged.piSession, ["sessionId", "id"]) : "";
243
+ const timeline = Array.isArray(merged.timeline) ? merged.timeline.length : null;
244
+ const approvals = Array.isArray(merged.approvals) ? merged.approvals.length : null;
245
+ const inputs = Array.isArray(merged.userInputs) ? merged.userInputs.length : null;
246
+ const rows = [
247
+ ["run", pc.bold(runId)],
248
+ ["status", formatStatusPill(status)],
249
+ ["task", taskId],
250
+ ["title", title],
251
+ ["runtime", [runtime, mode, interaction].filter(Boolean).join(" \xB7 ")],
252
+ ["created", created],
253
+ ["started", started],
254
+ ["updated", updated],
255
+ ["completed", completed],
256
+ ["worktree", worktree],
257
+ ["pi", piSession],
258
+ ["timeline", timeline],
259
+ ["approvals", approvals],
260
+ ["inputs", inputs]
261
+ ];
262
+ return [
263
+ formatSuccessCard(options.title ?? "Run details", rows),
264
+ "",
265
+ ...formatNextSteps([`Follow live: \`rig run attach ${runId} --follow\``, `Raw payload: \`rig run show ${runId} --raw\``])
266
+ ].join(`
267
+ `);
268
+ }
269
+ function formatRunStatus(summary, options = {}) {
270
+ const activeRuns = summary.activeRuns ?? [];
271
+ const recentRuns = summary.recentRuns ?? [];
272
+ const lines = [formatSection("Run status", options.source === "server" ? "selected server" : "local state")];
273
+ lines.push("", pc.bold(`Active runs (${activeRuns.length})`));
274
+ if (activeRuns.length === 0) {
275
+ lines.push(pc.dim("No active runs."));
276
+ } else {
277
+ for (const run of activeRuns) {
278
+ lines.push(formatRunSummaryLine(run));
279
+ }
280
+ }
281
+ lines.push("", pc.bold(`Recent runs (${recentRuns.length})`));
282
+ if (recentRuns.length === 0) {
283
+ lines.push(pc.dim("No recent terminal runs."));
284
+ } else {
285
+ for (const run of recentRuns.slice(0, 10)) {
286
+ lines.push(formatRunSummaryLine(run));
287
+ }
288
+ }
289
+ lines.push("", ...formatNextSteps(["Start work: `rig task run --next`", "Attach: `rig run attach <run-id> --follow`", "Details: `rig run show <run-id>`"]));
290
+ return lines.join(`
291
+ `);
292
+ }
293
+ function formatRunSummaryLine(run) {
294
+ const record = run;
295
+ const runId = runIdOf(record);
296
+ const status = firstString(record, ["status"], "unknown");
297
+ const taskId = taskIdOf(record);
298
+ const title = runTitleOf(record);
299
+ const runtime = firstString(record, ["runtimeAdapter", "runtime", "adapter"]);
300
+ const descriptor = [taskId, title].filter(Boolean).join(" \xB7 ");
301
+ return `${pc.dim("\u2502")} ${pc.bold(runId)} ${formatStatusPill(status)} ${descriptor}${runtime ? pc.dim(` ${runtime}`) : ""}`;
302
+ }
303
+ function formatInboxList(kind, entries) {
304
+ const title = kind === "approvals" ? "Approval inbox" : "Input inbox";
305
+ if (entries.length === 0) {
306
+ return [
307
+ formatSection(title, "empty"),
308
+ pc.dim(kind === "approvals" ? "No pending approvals." : "No pending user-input requests."),
309
+ "",
310
+ ...formatNextSteps(["Check runs: `rig run status`", "Start work: `rig task run --next`"])
311
+ ].join(`
312
+ `);
313
+ }
314
+ const lines = [formatSection(title, `${entries.length} pending`)];
315
+ for (const entry of entries) {
316
+ const record = entry.record && typeof entry.record === "object" && !Array.isArray(entry.record) ? entry.record : entry;
317
+ const runId = firstString(entry, ["runId"], firstString(record, ["runId"]));
318
+ const taskId = firstString(entry, ["taskId"], firstString(record, ["taskId", "task"]));
319
+ const requestId = requestIdOf(record);
320
+ const status = firstString(record, ["status", "state"], "pending");
321
+ const prompt = firstString(record, ["prompt", "message", "reason", "title", "summary"], kind === "approvals" ? "Approval requested" : "Input requested");
322
+ lines.push(`${pc.dim("\u2502")} ${pc.bold(requestId)} ${formatStatusPill(status)} ${prompt}`);
323
+ lines.push(`${pc.dim("\u2502")} ${pc.dim("run ")} ${runId || "(unknown-run)"}${taskId ? pc.dim(` task ${taskId}`) : ""}`);
324
+ }
325
+ lines.push("", ...formatNextSteps(kind === "approvals" ? ["Resolve: `rig inbox approve --run <run-id> --request <request-id> --decision approve|reject`", "Rejoin: `rig run attach <run-id> --follow`"] : ["Respond: `rig inbox respond --run <run-id> --request <request-id> --answer key=value`", "Rejoin: `rig run attach <run-id> --follow`"]));
326
+ return lines.join(`
327
+ `);
328
+ }
329
+ function formatConnectionList(connections) {
330
+ const rows = [["local", { kind: "local", mode: "auto" }], ...Object.entries(connections)];
331
+ const aliasWidth = Math.min(24, Math.max(5, ...rows.map(([alias]) => alias.length)));
332
+ const lines = rows.map(([alias, connection]) => [
333
+ pc.bold(pad(truncate(alias, aliasWidth), aliasWidth)),
334
+ formatStatusPill(connection.kind),
335
+ connection.kind === "remote" ? connection.baseUrl ?? "" : connection.mode ?? "local"
336
+ ].join(" "));
337
+ return [formatSection("Rig servers", `${rows.length} available`), `${pc.bold(pad("ALIAS", aliasWidth))} ${pc.bold("KIND")} ${pc.bold("TARGET")}`, ...lines, "", ...formatNextSteps(["Select one: `rig server use <alias|local>`"])].join(`
338
+ `);
339
+ }
340
+ function formatConnectionStatus(selected, connections) {
341
+ const connection = selected === "local" ? { kind: "local", mode: "auto" } : connections[selected];
342
+ const target = !connection ? "not configured" : connection.kind === "remote" ? connection.baseUrl : "local";
343
+ return [
344
+ formatSection("Rig server", "selected for this repo"),
345
+ `${pc.dim("\u2502")} ${pc.dim("selected ")} ${pc.bold(selected)}`,
346
+ `${pc.dim("\u2502")} ${pc.dim("kind ")} ${formatStatusPill(connection?.kind ?? "unknown")}`,
347
+ `${pc.dim("\u2502")} ${pc.dim("target ")} ${target ?? "not configured"}`,
348
+ "",
349
+ ...formatNextSteps(["Change: `rig server use <alias|local>`", "List saved servers: `rig server list`"])
350
+ ].join(`
351
+ `);
352
+ }
353
+ export {
354
+ printFormattedOutput,
355
+ formatTaskList,
356
+ formatTaskDetails,
357
+ formatTaskCard,
358
+ formatSuccessCard,
359
+ formatSubmittedRun,
360
+ formatStatusPill,
361
+ formatSection,
362
+ formatRunStatus,
363
+ formatRunList,
364
+ formatRunCard,
365
+ formatNextSteps,
366
+ formatInboxList,
367
+ formatConnectionStatus,
368
+ formatConnectionList
369
+ };
@@ -6,12 +6,19 @@ import { dirname, resolve } from "path";
6
6
 
7
7
  // packages/cli/src/runner.ts
8
8
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
9
- import { CliError } from "@rig/runtime/control-plane/errors";
9
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
10
10
  import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
11
- import { PluginManager } from "@rig/runtime/control-plane/runtime/plugins";
12
- import { loadRuntimeContextFromEnv } from "@rig/runtime/control-plane/runtime/context";
13
11
  import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
14
- import { CliError as CliError2 } from "@rig/runtime/control-plane/errors";
12
+
13
+ class CliError extends RuntimeCliError {
14
+ hint;
15
+ constructor(message, exitCode = 1, options = {}) {
16
+ super(message, exitCode);
17
+ if (options.hint?.trim()) {
18
+ this.hint = options.hint.trim();
19
+ }
20
+ }
21
+ }
15
22
 
16
23
  // packages/cli/src/commands/_connection-state.ts
17
24
  function resolveGlobalConnectionsPath(env = process.env) {
@@ -32,7 +39,7 @@ function readJsonFile(path) {
32
39
  try {
33
40
  return JSON.parse(readFileSync(path, "utf8"));
34
41
  } catch (error) {
35
- throw new CliError2(`Invalid Rig connection state at ${path}: ${error instanceof Error ? error.message : String(error)}`, 1);
42
+ 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>`." });
36
43
  }
37
44
  }
38
45
  function writeJsonFile(path, value) {
@@ -75,7 +82,7 @@ function writeGlobalConnections(state, options = {}) {
75
82
  function upsertGlobalConnection(alias, connection, options = {}) {
76
83
  const cleanAlias = alias.trim();
77
84
  if (!cleanAlias)
78
- throw new CliError2("Connection alias is required.", 1);
85
+ throw new CliError("Connection alias is required.", 1, { hint: "Save a server with `rig server add <alias> <url>`." });
79
86
  const state = readGlobalConnections(options);
80
87
  state.connections[cleanAlias] = connection;
81
88
  writeGlobalConnections(state, options);
@@ -92,7 +99,8 @@ function readRepoConnection(projectRoot) {
92
99
  return {
93
100
  selected,
94
101
  project: typeof record.project === "string" ? record.project : undefined,
95
- linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined
102
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
103
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
96
104
  };
97
105
  }
98
106
  function writeRepoConnection(projectRoot, state) {
@@ -103,15 +111,25 @@ function resolveSelectedConnection(projectRoot, options = {}) {
103
111
  if (!repo)
104
112
  return null;
105
113
  if (repo.selected === "local")
106
- return { alias: "local", connection: { kind: "local", mode: "auto" } };
114
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
107
115
  const global = readGlobalConnections(options);
108
116
  const connection = global.connections[repo.selected];
109
117
  if (!connection) {
110
- throw new CliError2(`Selected Rig connection "${repo.selected}" was not found. Run \`rig connect list\` or \`rig connect use local\`.`, 1);
118
+ throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
111
119
  }
112
- return { alias: repo.selected, connection };
120
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
121
+ }
122
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
123
+ const repo = readRepoConnection(projectRoot);
124
+ if (!repo)
125
+ return;
126
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
127
+ }
128
+ function isRemoteConnectionSelected(projectRoot) {
129
+ return resolveSelectedConnection(projectRoot)?.connection.kind === "remote";
113
130
  }
114
131
  export {
132
+ writeRepoServerProjectRoot,
115
133
  writeRepoConnection,
116
134
  writeGlobalConnections,
117
135
  upsertGlobalConnection,
@@ -119,5 +137,6 @@ export {
119
137
  resolveRepoConnectionPath,
120
138
  resolveGlobalConnectionsPath,
121
139
  readRepoConnection,
122
- readGlobalConnections
140
+ readGlobalConnections,
141
+ isRemoteConnectionSelected
123
142
  };