@h-rig/cli 0.0.6-alpha.75 → 0.0.6-alpha.77

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.
@@ -0,0 +1,730 @@
1
+ // @bun
2
+ // packages/cli/src/commands/_operator-board.ts
3
+ import { ProcessTerminal, TUI, Text, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
4
+
5
+ // packages/cli/src/commands/_tui-theme.ts
6
+ var RIG_PALETTE = {
7
+ ink: "#f2f3f6",
8
+ ink2: "#aeb0ba",
9
+ ink3: "#6c6e79",
10
+ ink4: "#44464f",
11
+ accent: "#ccff4d",
12
+ accentDim: "#a9d63f",
13
+ cyan: "#56d8ff",
14
+ red: "#ff5d5d",
15
+ yellow: "#ffd24d"
16
+ };
17
+ function hexToRgb(hex) {
18
+ const value = hex.replace("#", "");
19
+ return [
20
+ Number.parseInt(value.slice(0, 2), 16),
21
+ Number.parseInt(value.slice(2, 4), 16),
22
+ Number.parseInt(value.slice(4, 6), 16)
23
+ ];
24
+ }
25
+ function fg(hex) {
26
+ const [r, g, b] = hexToRgb(hex);
27
+ return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
28
+ }
29
+ var ink = fg(RIG_PALETTE.ink);
30
+ var ink2 = fg(RIG_PALETTE.ink2);
31
+ var ink3 = fg(RIG_PALETTE.ink3);
32
+ var ink4 = fg(RIG_PALETTE.ink4);
33
+ var accent = fg(RIG_PALETTE.accent);
34
+ var accentDim = fg(RIG_PALETTE.accentDim);
35
+ var cyan = fg(RIG_PALETTE.cyan);
36
+ var red = fg(RIG_PALETTE.red);
37
+ var yellow = fg(RIG_PALETTE.yellow);
38
+ function bold(text) {
39
+ return `\x1B[1m${text}\x1B[22m`;
40
+ }
41
+ function statusColor(status) {
42
+ switch (status) {
43
+ case "running":
44
+ return accent;
45
+ case "preparing":
46
+ case "created":
47
+ case "validating":
48
+ case "reviewing":
49
+ case "closing-out":
50
+ return cyan;
51
+ case "needs-attention":
52
+ case "needs_attention":
53
+ return yellow;
54
+ case "failed":
55
+ return red;
56
+ default:
57
+ return ink3;
58
+ }
59
+ }
60
+ var RIG_SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
61
+ var DRONE_ART = [
62
+ " .-=-. .-=-. ",
63
+ " ( !!! ) ( !!! ) ",
64
+ " '-=-'._ _.'-=-' ",
65
+ " '._ _.' ",
66
+ " '=$$$$$$$=.' ",
67
+ " =$$$$$$$$$$$= ",
68
+ " $$$@@@@@@@@@@$$$ ",
69
+ " $$$@@ @@$$$ ",
70
+ " $$@ ? @$$$ ",
71
+ " $$$@ '-' @$$$ ",
72
+ " $$$@@ @@$$$ ",
73
+ " $$$@@@@@@@@@@$$$ ",
74
+ " =$$$$$$$$$$$= ",
75
+ " '=$$$$$$$=.' ",
76
+ " _.' '._ ",
77
+ " .-=-.' '.-=-. ",
78
+ " ( !!! ) ( !!! ) ",
79
+ " '-=-' '-=-' "
80
+ ];
81
+ var BLADE_FRAMES = ["---", "\\\\\\", "|||", "///"];
82
+ var EYE_FRAMES = ["@", "o", "."];
83
+ function droneCharColor(char) {
84
+ if (char === "$" || char === "@")
85
+ return accent;
86
+ if (char === "=" || char === "%")
87
+ return accentDim;
88
+ if (char === "\\" || char === "/")
89
+ return ink3;
90
+ return ink4;
91
+ }
92
+ function renderDroneFrame(tick) {
93
+ const blade = BLADE_FRAMES[Math.floor(tick / 4) % BLADE_FRAMES.length];
94
+ const pulse = Math.sin(tick * 0.07);
95
+ const eye = pulse > 0.45 ? EYE_FRAMES[0] : pulse > -0.1 ? EYE_FRAMES[1] : EYE_FRAMES[2];
96
+ return DRONE_ART.map((line) => {
97
+ let out = "";
98
+ let index = 0;
99
+ while (index < line.length) {
100
+ if (line.startsWith("!!!", index)) {
101
+ out += cyan(blade);
102
+ index += 3;
103
+ continue;
104
+ }
105
+ const char = line[index];
106
+ if (char === "?") {
107
+ out += bold(cyan(eye));
108
+ } else if (char !== " ") {
109
+ out += droneCharColor(char)(char);
110
+ } else {
111
+ out += " ";
112
+ }
113
+ index += 1;
114
+ }
115
+ return out;
116
+ });
117
+ }
118
+ var DRONE_WIDTH = DRONE_ART[0].length;
119
+ var DRONE_HEIGHT = DRONE_ART.length;
120
+
121
+ // packages/cli/src/commands/_server-client.ts
122
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
123
+ import { resolve as resolve2 } from "path";
124
+
125
+ // packages/cli/src/runner.ts
126
+ import { EventBus } from "@rig/runtime/control-plane/runtime/events";
127
+ import { CliError as RuntimeCliError } from "@rig/runtime/control-plane/errors";
128
+ import { evaluate, loadPolicy, resolveAction } from "@rig/runtime/control-plane/runtime/guard";
129
+ import { buildBinary } from "@rig/runtime/control-plane/runtime/isolation";
130
+
131
+ class CliError extends RuntimeCliError {
132
+ hint;
133
+ constructor(message, exitCode = 1, options = {}) {
134
+ super(message, exitCode);
135
+ if (options.hint?.trim()) {
136
+ this.hint = options.hint.trim();
137
+ }
138
+ }
139
+ }
140
+
141
+ // packages/cli/src/commands/_server-client.ts
142
+ import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
143
+
144
+ // packages/cli/src/commands/_connection-state.ts
145
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
146
+ import { homedir } from "os";
147
+ import { dirname, resolve } from "path";
148
+ function resolveGlobalConnectionsPath(env = process.env) {
149
+ const explicit = env.RIG_CONNECTIONS_FILE?.trim();
150
+ if (explicit)
151
+ return resolve(explicit);
152
+ const stateDir = env.RIG_GLOBAL_STATE_DIR?.trim();
153
+ if (stateDir)
154
+ return resolve(stateDir, "connections.json");
155
+ return resolve(homedir(), ".rig", "connections.json");
156
+ }
157
+ function resolveRepoConnectionPath(projectRoot) {
158
+ return resolve(projectRoot, ".rig", "state", "connection.json");
159
+ }
160
+ function readJsonFile(path) {
161
+ if (!existsSync(path))
162
+ return null;
163
+ try {
164
+ return JSON.parse(readFileSync(path, "utf8"));
165
+ } catch (error) {
166
+ 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>`." });
167
+ }
168
+ }
169
+ function writeJsonFile(path, value) {
170
+ mkdirSync(dirname(path), { recursive: true });
171
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
172
+ `, "utf8");
173
+ }
174
+ function normalizeConnection(value) {
175
+ if (!value || typeof value !== "object" || Array.isArray(value))
176
+ return null;
177
+ const record = value;
178
+ if (record.kind === "local")
179
+ return { kind: "local", mode: "auto" };
180
+ if (record.kind === "remote" && typeof record.baseUrl === "string" && record.baseUrl.trim()) {
181
+ const baseUrl = record.baseUrl.trim().replace(/\/+$/, "");
182
+ return { kind: "remote", baseUrl };
183
+ }
184
+ return null;
185
+ }
186
+ function readGlobalConnections(options = {}) {
187
+ const path = resolveGlobalConnectionsPath(options.env ?? process.env);
188
+ const payload = readJsonFile(path);
189
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
190
+ return { connections: {} };
191
+ }
192
+ const rawConnections = payload.connections;
193
+ const connections = {};
194
+ if (rawConnections && typeof rawConnections === "object" && !Array.isArray(rawConnections)) {
195
+ for (const [alias, raw] of Object.entries(rawConnections)) {
196
+ const connection = normalizeConnection(raw);
197
+ if (connection)
198
+ connections[alias] = connection;
199
+ }
200
+ }
201
+ return { connections };
202
+ }
203
+ function readRepoConnection(projectRoot) {
204
+ const payload = readJsonFile(resolveRepoConnectionPath(projectRoot));
205
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
206
+ return null;
207
+ const record = payload;
208
+ const selected = typeof record.selected === "string" ? record.selected.trim() : "";
209
+ if (!selected)
210
+ return null;
211
+ return {
212
+ selected,
213
+ project: typeof record.project === "string" ? record.project : undefined,
214
+ linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
215
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
216
+ };
217
+ }
218
+ function writeRepoConnection(projectRoot, state) {
219
+ writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
220
+ }
221
+ function resolveSelectedConnection(projectRoot, options = {}) {
222
+ const repo = readRepoConnection(projectRoot);
223
+ if (!repo)
224
+ return null;
225
+ if (repo.selected === "local")
226
+ return { alias: "local", connection: { kind: "local", mode: "auto" }, serverProjectRoot: repo.serverProjectRoot };
227
+ const global = readGlobalConnections(options);
228
+ const connection = global.connections[repo.selected];
229
+ if (!connection) {
230
+ throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
231
+ }
232
+ return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
233
+ }
234
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
235
+ const repo = readRepoConnection(projectRoot);
236
+ if (!repo)
237
+ return;
238
+ writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
239
+ }
240
+
241
+ // packages/cli/src/commands/_server-client.ts
242
+ var scopedGitHubBearerTokens = new Map;
243
+ var serverPhaseListener = null;
244
+ function reportServerPhase(label) {
245
+ serverPhaseListener?.(label);
246
+ }
247
+ function cleanToken(value) {
248
+ const trimmed = value?.trim();
249
+ return trimmed ? trimmed : null;
250
+ }
251
+ function readPrivateRemoteSessionToken(projectRoot) {
252
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
253
+ if (!existsSync2(path))
254
+ return null;
255
+ try {
256
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
257
+ return cleanToken(typeof parsed.apiSessionToken === "string" ? parsed.apiSessionToken : typeof parsed.sessionToken === "string" ? parsed.sessionToken : undefined);
258
+ } catch {
259
+ return null;
260
+ }
261
+ }
262
+ function readGitHubBearerTokenForRemote(projectRoot) {
263
+ const scopedKey = resolve2(projectRoot);
264
+ if (scopedGitHubBearerTokens.has(scopedKey))
265
+ return scopedGitHubBearerTokens.get(scopedKey) ?? null;
266
+ const privateSession = readPrivateRemoteSessionToken(projectRoot);
267
+ if (privateSession)
268
+ return privateSession;
269
+ return cleanToken(process.env.RIG_SERVER_AUTH_TOKEN) ?? cleanToken(process.env.RIG_REMOTE_AUTH_TOKEN);
270
+ }
271
+ function readStoredGitHubAuthToken(projectRoot) {
272
+ const path = resolve2(projectRoot, ".rig", "state", "github-auth.json");
273
+ if (!existsSync2(path))
274
+ return null;
275
+ try {
276
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
277
+ return cleanToken(typeof parsed.token === "string" ? parsed.token : undefined);
278
+ } catch {
279
+ return null;
280
+ }
281
+ }
282
+ function readLocalConnectionFallbackToken(projectRoot) {
283
+ return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
284
+ }
285
+ async function ensureServerForCli(projectRoot) {
286
+ try {
287
+ const selected = resolveSelectedConnection(projectRoot);
288
+ if (selected?.connection.kind === "remote") {
289
+ reportServerPhase(`Connecting to ${selected.alias}\u2026`);
290
+ const authToken = readGitHubBearerTokenForRemote(projectRoot);
291
+ const serverProjectRoot = selected.serverProjectRoot ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
292
+ return {
293
+ baseUrl: selected.connection.baseUrl,
294
+ authToken,
295
+ connectionKind: "remote",
296
+ serverProjectRoot
297
+ };
298
+ }
299
+ reportServerPhase("Starting local Rig server\u2026");
300
+ const connection = await ensureLocalRigServerConnection(projectRoot);
301
+ return {
302
+ baseUrl: connection.baseUrl,
303
+ authToken: connection.authToken ?? readLocalConnectionFallbackToken(projectRoot),
304
+ connectionKind: "local",
305
+ serverProjectRoot: resolve2(projectRoot)
306
+ };
307
+ } catch (error) {
308
+ if (error instanceof Error) {
309
+ throw new CliError(error.message, 1);
310
+ }
311
+ throw error;
312
+ }
313
+ }
314
+ async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
315
+ const repo = readRepoConnection(projectRoot);
316
+ const slug = repo?.project?.trim();
317
+ if (!slug)
318
+ return null;
319
+ try {
320
+ const response = await fetch(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`, {
321
+ headers: mergeHeaders(undefined, authToken)
322
+ });
323
+ if (!response.ok)
324
+ return null;
325
+ const payload = await response.json();
326
+ const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
327
+ const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
328
+ const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
329
+ const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
330
+ if (path)
331
+ writeRepoServerProjectRoot(projectRoot, path);
332
+ return path;
333
+ } catch {
334
+ return null;
335
+ }
336
+ }
337
+ function mergeHeaders(headers, authToken) {
338
+ const merged = new Headers(headers);
339
+ if (authToken) {
340
+ merged.set("authorization", `Bearer ${authToken}`);
341
+ }
342
+ return merged;
343
+ }
344
+ function diagnosticMessage(payload) {
345
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
346
+ return null;
347
+ const record = payload;
348
+ const diagnostics = Array.isArray(record.diagnostics) ? record.diagnostics : [];
349
+ const messages = diagnostics.flatMap((entry) => {
350
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
351
+ return [];
352
+ const diagnostic = entry;
353
+ const kind = typeof diagnostic.kind === "string" ? diagnostic.kind : "task-source";
354
+ const message = typeof diagnostic.message === "string" ? diagnostic.message : null;
355
+ return message ? [`${kind}: ${message}`] : [];
356
+ });
357
+ return messages.length > 0 ? messages.join("; ") : null;
358
+ }
359
+ var serverReachabilityCache = new Map;
360
+ async function probeServerReachability(baseUrl, authToken) {
361
+ try {
362
+ const response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/server/status`, {
363
+ headers: mergeHeaders(undefined, authToken),
364
+ signal: AbortSignal.timeout(1500)
365
+ });
366
+ return response.ok;
367
+ } catch {
368
+ return false;
369
+ }
370
+ }
371
+ function cachedServerReachability(projectRoot, baseUrl, authToken) {
372
+ const key = resolve2(projectRoot);
373
+ const cached = serverReachabilityCache.get(key);
374
+ if (cached)
375
+ return cached;
376
+ const probe = probeServerReachability(baseUrl, authToken);
377
+ serverReachabilityCache.set(key, probe);
378
+ return probe;
379
+ }
380
+ function describeSelectedServer(projectRoot, server) {
381
+ try {
382
+ const selected = resolveSelectedConnection(projectRoot);
383
+ if (selected) {
384
+ return {
385
+ alias: selected.alias,
386
+ target: selected.connection.kind === "remote" ? selected.connection.baseUrl : server.baseUrl
387
+ };
388
+ }
389
+ } catch {}
390
+ return { alias: server.connectionKind === "remote" ? "remote" : "local", target: server.baseUrl };
391
+ }
392
+ async function buildServerFailureContext(projectRoot, server) {
393
+ const { alias, target } = describeSelectedServer(projectRoot, server);
394
+ const reachable = await cachedServerReachability(projectRoot, server.baseUrl, server.authToken);
395
+ const reachability = reachable ? "server is reachable" : "server is unreachable";
396
+ return {
397
+ contextLine: `Currently connected to: ${alias} at ${target} (${reachability}).`,
398
+ hint: "Check the selected server with `rig server status`, or switch with `rig server use <alias|local>`."
399
+ };
400
+ }
401
+ async function requestServerJson(context, pathname, init = {}) {
402
+ const server = await ensureServerForCli(context.projectRoot);
403
+ const headers = mergeHeaders(init.headers, server.authToken);
404
+ if (server.serverProjectRoot)
405
+ headers.set("x-rig-project-root", server.serverProjectRoot);
406
+ reportServerPhase(`${(init.method ?? "GET").toUpperCase()} ${pathname.split("?")[0]}\u2026`);
407
+ let response;
408
+ try {
409
+ response = await fetch(`${server.baseUrl}${pathname}`, {
410
+ ...init,
411
+ headers
412
+ });
413
+ } catch (error) {
414
+ const failure = await buildServerFailureContext(context.projectRoot, server);
415
+ throw new CliError(`Rig server request failed: ${error instanceof Error ? error.message : String(error)}
416
+ ${failure.contextLine}`, 1, { hint: failure.hint });
417
+ }
418
+ const text = await response.text();
419
+ const payload = text.trim().length > 0 ? (() => {
420
+ try {
421
+ return JSON.parse(text);
422
+ } catch {
423
+ return null;
424
+ }
425
+ })() : null;
426
+ if (!response.ok) {
427
+ const diagnostics = diagnosticMessage(payload);
428
+ const detail = diagnostics ?? (text || response.statusText);
429
+ const failure = await buildServerFailureContext(context.projectRoot, server);
430
+ throw new CliError(`Rig server request failed (${response.status}): ${detail}
431
+ ${failure.contextLine}`, 1, { hint: failure.hint });
432
+ }
433
+ return payload;
434
+ }
435
+ async function listRunsViaServer(context, options = {}) {
436
+ const url = new URL("http://rig.local/api/runs");
437
+ if (options.limit !== undefined)
438
+ url.searchParams.set("limit", String(options.limit));
439
+ const payload = await requestServerJson(context, `${url.pathname}${url.search}`);
440
+ const runs = Array.isArray(payload) ? payload : payload && typeof payload === "object" && !Array.isArray(payload) && Array.isArray(payload.runs) ? payload.runs : [];
441
+ return runs.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
442
+ }
443
+ var RESUMABLE_RUN_STATUSES = new Set([
444
+ "created",
445
+ "preparing",
446
+ "running",
447
+ "validating",
448
+ "reviewing",
449
+ "stopped",
450
+ "failed",
451
+ "needs-attention",
452
+ "needs_attention"
453
+ ]);
454
+ async function resolveServerConnectionLabel(projectRoot) {
455
+ try {
456
+ const selected = resolveSelectedConnection(projectRoot);
457
+ if (!selected)
458
+ return "no server selected";
459
+ if (selected.connection.kind === "remote") {
460
+ return selected.connection.baseUrl.replace(/^https?:\/\//, "");
461
+ }
462
+ return `local (${selected.alias})`;
463
+ } catch {
464
+ return "no server selected";
465
+ }
466
+ }
467
+ async function stopRunViaServer(context, runId) {
468
+ const payload = await requestServerJson(context, "/api/runs/stop", {
469
+ method: "POST",
470
+ headers: { "content-type": "application/json" },
471
+ body: JSON.stringify({ runId })
472
+ });
473
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : { ok: true, runId };
474
+ }
475
+
476
+ // packages/cli/src/commands/_cli-format.ts
477
+ import { log, note } from "@clack/prompts";
478
+ import pc from "picocolors";
479
+
480
+ // packages/cli/src/commands/_async-ui.ts
481
+ import pc2 from "picocolors";
482
+ var DONE_SYMBOL = pc2.green("\u25C7");
483
+ var FAIL_SYMBOL = pc2.red("\u25A0");
484
+
485
+ // packages/cli/src/commands/inbox.ts
486
+ async function listInboxRecords(context, kind, filters) {
487
+ const params = new URLSearchParams;
488
+ if (filters.run)
489
+ params.set("runId", filters.run);
490
+ if (filters.task)
491
+ params.set("taskId", filters.task);
492
+ const query = params.size > 0 ? `?${params.toString()}` : "";
493
+ const payload = await requestServerJson(context, `/api/inbox/${kind}${query}`);
494
+ const records = Array.isArray(payload) ? payload : [];
495
+ return filters.pendingOnly ? records.filter((entry) => (entry.status ?? "pending") !== "resolved") : records;
496
+ }
497
+ async function readPendingInboxCounts(context) {
498
+ try {
499
+ const [approvals, inputs] = await Promise.all([
500
+ listInboxRecords(context, "approvals", { pendingOnly: true }),
501
+ listInboxRecords(context, "inputs", { pendingOnly: true })
502
+ ]);
503
+ return { approvals: approvals.length, inputs: inputs.length };
504
+ } catch {
505
+ return null;
506
+ }
507
+ }
508
+
509
+ // packages/cli/src/commands/_operator-board.ts
510
+ var BOARD_REFRESH_MS = 5000;
511
+ var BOARD_TICK_MS = 120;
512
+ function normalizeRuns(payload) {
513
+ return payload.map((run) => ({
514
+ runId: typeof run.runId === "string" ? run.runId : "",
515
+ status: typeof run.status === "string" ? run.status : "unknown",
516
+ title: String(run.title ?? run.taskId ?? "untitled")
517
+ })).filter((run) => run.runId);
518
+ }
519
+
520
+ class RunsList {
521
+ runs = [];
522
+ selected = 0;
523
+ loading = true;
524
+ tick = 0;
525
+ moveSelection(delta) {
526
+ if (this.runs.length === 0)
527
+ return;
528
+ this.selected = Math.max(0, Math.min(this.runs.length - 1, this.selected + delta));
529
+ }
530
+ selectedRun() {
531
+ return this.runs[this.selected] ?? null;
532
+ }
533
+ setRuns(runs) {
534
+ const previous = this.selectedRun()?.runId;
535
+ this.runs = runs;
536
+ if (previous) {
537
+ const index = runs.findIndex((run) => run.runId === previous);
538
+ this.selected = index >= 0 ? index : Math.min(this.selected, Math.max(0, runs.length - 1));
539
+ } else {
540
+ this.selected = Math.min(this.selected, Math.max(0, runs.length - 1));
541
+ }
542
+ this.loading = false;
543
+ }
544
+ invalidate() {}
545
+ render(width) {
546
+ if (this.loading) {
547
+ const frame = renderDroneFrame(this.tick);
548
+ const spinner = RIG_SPINNER_FRAMES[this.tick % RIG_SPINNER_FRAMES.length];
549
+ const pad = Math.max(0, Math.floor((width - 34) / 2));
550
+ return [
551
+ "",
552
+ ...frame.map((line) => " ".repeat(pad) + line),
553
+ "",
554
+ " ".repeat(Math.max(0, Math.floor((width - 24) / 2))) + accent(spinner) + ink3(" contacting the fleet\u2026"),
555
+ ""
556
+ ];
557
+ }
558
+ if (this.runs.length === 0) {
559
+ const frame = renderDroneFrame(this.tick);
560
+ const pad = Math.max(0, Math.floor((width - 34) / 2));
561
+ return [
562
+ "",
563
+ ...frame.map((line) => " ".repeat(pad) + line),
564
+ "",
565
+ " ".repeat(Math.max(0, Math.floor((width - 38) / 2))) + ink2("no runs yet \u2014 ") + accent("rig task run --next") + ink2(" launches one"),
566
+ ""
567
+ ];
568
+ }
569
+ const maxVisible = 16;
570
+ const start = Math.max(0, Math.min(this.selected - Math.floor(maxVisible / 2), this.runs.length - maxVisible));
571
+ const visible = this.runs.slice(start, start + maxVisible);
572
+ const lines = visible.map((run, index) => {
573
+ const absolute = start + index;
574
+ const isSelected = absolute === this.selected;
575
+ const dot = statusColor(run.status)(isSelected ? "\u25CF" : "\xB7");
576
+ const id = run.runId.slice(0, 8);
577
+ const status = statusColor(run.status)(run.status.padEnd(16));
578
+ const title = truncateToWidth(run.title, Math.max(8, width - 36));
579
+ const row = ` ${dot} ${isSelected ? bold(ink(id)) : ink3(id)} ${status} ${isSelected ? ink(title) : ink2(title)}`;
580
+ return isSelected ? accent("\u258C") + row : " " + row;
581
+ });
582
+ if (this.runs.length > maxVisible) {
583
+ lines.push(ink4(` ${this.selected + 1}/${this.runs.length}`));
584
+ }
585
+ return ["", ...lines, ""];
586
+ }
587
+ }
588
+ function hairline(width) {
589
+ return ink4("\u2500".repeat(Math.max(0, width)));
590
+ }
591
+
592
+ class Rule {
593
+ invalidate() {}
594
+ render(width) {
595
+ return [hairline(width)];
596
+ }
597
+ }
598
+ async function runOperatorBoard(context) {
599
+ const terminal = new ProcessTerminal;
600
+ const tui = new TUI(terminal);
601
+ const list = new RunsList;
602
+ const header = new Text("");
603
+ const footer = new Text("");
604
+ let serverLabel = "resolving server\u2026";
605
+ let inboxCounts = null;
606
+ let notice = null;
607
+ let tick = 0;
608
+ const renderHeader = (width = 100) => {
609
+ header.setText(` ${accent("\u258D")}${bold(ink("rig"))} ${ink3("\u2014 operate the drones")} ${ink4("\xB7")} ${cyan(serverLabel)}`);
610
+ };
611
+ const renderFooter = () => {
612
+ const pending = inboxCounts && inboxCounts.approvals + inboxCounts.inputs > 0 ? `${RIG_SPINNER_FRAMES[tick % RIG_SPINNER_FRAMES.length]} ${inboxCounts.approvals + inboxCounts.inputs} inbox gate${inboxCounts.approvals + inboxCounts.inputs === 1 ? "" : "s"} waiting \u2014 rig inbox` : "fleet idle gates clear";
613
+ const status = notice ?? pending;
614
+ footer.setText([
615
+ ` ${inboxCounts && inboxCounts.approvals + inboxCounts.inputs > 0 ? accentDim(status) : ink4(status)}`,
616
+ ` ${accent("enter")}${ink3(" attach (full session, live)")} ${accent("x")}${ink3(" stop")} ${accent("r")}${ink3(" refresh")} ${accent("q")}${ink3(" quit")}`
617
+ ].join(`
618
+ `));
619
+ };
620
+ renderHeader();
621
+ renderFooter();
622
+ tui.addChild(header);
623
+ tui.addChild(new Rule);
624
+ tui.addChild(list);
625
+ tui.addChild(new Rule);
626
+ tui.addChild(footer);
627
+ let stopped = false;
628
+ let outcome = { action: "quit" };
629
+ const finish = (result) => {
630
+ if (stopped)
631
+ return;
632
+ stopped = true;
633
+ outcome = result;
634
+ tui.stop();
635
+ };
636
+ const refresh = async () => {
637
+ try {
638
+ const [runs, counts] = await Promise.all([
639
+ listRunsViaServer(context),
640
+ readPendingInboxCounts(context)
641
+ ]);
642
+ list.setRuns(normalizeRuns(runs));
643
+ inboxCounts = counts;
644
+ notice = null;
645
+ } catch (error) {
646
+ list.loading = false;
647
+ notice = `server unreachable: ${error instanceof Error ? error.message : String(error)}`;
648
+ }
649
+ renderFooter();
650
+ tui.requestRender();
651
+ };
652
+ resolveServerConnectionLabel(context.projectRoot).then((label) => {
653
+ serverLabel = label;
654
+ renderHeader();
655
+ tui.requestRender();
656
+ }).catch(() => {});
657
+ tui.addInputListener((data) => {
658
+ if (matchesKey(data, "up") || data === "k") {
659
+ list.moveSelection(-1);
660
+ tui.requestRender();
661
+ return { consume: true };
662
+ }
663
+ if (matchesKey(data, "down") || data === "j") {
664
+ list.moveSelection(1);
665
+ tui.requestRender();
666
+ return { consume: true };
667
+ }
668
+ if (matchesKey(data, "enter") || matchesKey(data, "return")) {
669
+ const run = list.selectedRun();
670
+ if (run)
671
+ finish({ action: "attach", runId: run.runId });
672
+ return { consume: true };
673
+ }
674
+ if (data === "x") {
675
+ const run = list.selectedRun();
676
+ if (run) {
677
+ notice = `stop requested for ${run.runId.slice(0, 8)}\u2026`;
678
+ renderFooter();
679
+ tui.requestRender();
680
+ stopRunViaServer(context, run.runId).then(() => refresh()).catch(() => refresh());
681
+ }
682
+ return { consume: true };
683
+ }
684
+ if (data === "r") {
685
+ refresh();
686
+ return { consume: true };
687
+ }
688
+ if (data === "q" || matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
689
+ finish({ action: "quit" });
690
+ return { consume: true };
691
+ }
692
+ return { consume: true };
693
+ });
694
+ const animation = setInterval(() => {
695
+ tick += 1;
696
+ list.tick = tick;
697
+ if (list.loading || list.runs.length === 0 || inboxCounts && inboxCounts.approvals + inboxCounts.inputs > 0) {
698
+ renderFooter();
699
+ tui.requestRender();
700
+ }
701
+ }, BOARD_TICK_MS);
702
+ const refreshTimer = setInterval(() => {
703
+ refresh();
704
+ }, BOARD_REFRESH_MS);
705
+ tui.start();
706
+ refresh();
707
+ await new Promise((resolve3) => {
708
+ const poll = setInterval(() => {
709
+ if (stopped) {
710
+ clearInterval(poll);
711
+ resolve3();
712
+ }
713
+ }, 50);
714
+ });
715
+ clearInterval(animation);
716
+ clearInterval(refreshTimer);
717
+ return outcome;
718
+ }
719
+ async function runOperatorBoardLoop(context, attach) {
720
+ for (;; ) {
721
+ const outcome = await runOperatorBoard(context);
722
+ if (outcome.action === "quit")
723
+ return;
724
+ await attach(outcome.runId);
725
+ }
726
+ }
727
+ export {
728
+ runOperatorBoardLoop,
729
+ runOperatorBoard
730
+ };