@h-rig/cli 0.0.6-alpha.87 → 0.0.6-alpha.89

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 (78) hide show
  1. package/dist/bin/rig.js +1380 -865
  2. package/dist/src/app/board.js +462 -48
  3. package/dist/src/app-opentui/adapters/common.d.ts +3 -0
  4. package/dist/src/app-opentui/adapters/common.js +4 -0
  5. package/dist/src/app-opentui/adapters/doctor.js +458 -46
  6. package/dist/src/app-opentui/adapters/family.js +701 -151
  7. package/dist/src/app-opentui/adapters/fleet.js +477 -46
  8. package/dist/src/app-opentui/adapters/inbox.js +477 -46
  9. package/dist/src/app-opentui/adapters/init.js +497 -74
  10. package/dist/src/app-opentui/adapters/inspect.js +477 -46
  11. package/dist/src/app-opentui/adapters/pi-attach.d.ts +7 -0
  12. package/dist/src/app-opentui/adapters/pi-attach.js +1004 -519
  13. package/dist/src/app-opentui/adapters/run-detail.js +477 -46
  14. package/dist/src/app-opentui/adapters/server.d.ts +26 -0
  15. package/dist/src/app-opentui/adapters/server.js +676 -59
  16. package/dist/src/app-opentui/adapters/tasks.js +621 -549
  17. package/dist/src/app-opentui/autocomplete.js +4 -2
  18. package/dist/src/app-opentui/bootstrap.js +1376 -861
  19. package/dist/src/app-opentui/command-palette.js +37 -10
  20. package/dist/src/app-opentui/index.js +632 -528
  21. package/dist/src/app-opentui/intent.js +33 -8
  22. package/dist/src/app-opentui/keymap.js +43 -414
  23. package/dist/src/app-opentui/pi-host-child.js +496 -57
  24. package/dist/src/app-opentui/pi-pty-host.d.ts +14 -64
  25. package/dist/src/app-opentui/pi-pty-host.js +3 -397
  26. package/dist/src/app-opentui/react/App.js +144 -469
  27. package/dist/src/app-opentui/react/ChromeHost.js +44 -415
  28. package/dist/src/app-opentui/react/launch.js +659 -552
  29. package/dist/src/app-opentui/react/nav.js +1 -1
  30. package/dist/src/app-opentui/registry.js +1181 -742
  31. package/dist/src/app-opentui/remote-link.d.ts +10 -0
  32. package/dist/src/app-opentui/remote-link.js +47 -0
  33. package/dist/src/app-opentui/render/terminal-handoff.d.ts +16 -0
  34. package/dist/src/app-opentui/render/terminal-handoff.js +14 -0
  35. package/dist/src/app-opentui/runtime.js +632 -528
  36. package/dist/src/app-opentui/scenes/doctor.js +1 -1
  37. package/dist/src/app-opentui/scenes/error.js +50 -4
  38. package/dist/src/app-opentui/scenes/family.js +60 -6
  39. package/dist/src/app-opentui/scenes/fleet.js +65 -13
  40. package/dist/src/app-opentui/scenes/help.js +4 -2
  41. package/dist/src/app-opentui/scenes/init.js +12 -12
  42. package/dist/src/app-opentui/scenes/main.js +7 -7
  43. package/dist/src/app-opentui/scenes/server.js +83 -11
  44. package/dist/src/app-opentui/scenes/tasks.js +79 -16
  45. package/dist/src/app-opentui/state.js +25 -5
  46. package/dist/src/app-opentui/surface-catalog.js +4 -2
  47. package/dist/src/app-opentui/types.d.ts +1 -1
  48. package/dist/src/commands/_cli-format.d.ts +10 -1
  49. package/dist/src/commands/_cli-format.js +5 -2
  50. package/dist/src/commands/_connection-state.d.ts +11 -1
  51. package/dist/src/commands/_connection-state.js +50 -5
  52. package/dist/src/commands/_doctor-checks.js +458 -46
  53. package/dist/src/commands/_help-catalog.js +4 -2
  54. package/dist/src/commands/_json-output.js +4 -0
  55. package/dist/src/commands/_operator-view.js +496 -57
  56. package/dist/src/commands/_pi-frontend.d.ts +25 -0
  57. package/dist/src/commands/_pi-frontend.js +497 -57
  58. package/dist/src/commands/_preflight.js +509 -72
  59. package/dist/src/commands/_server-client.d.ts +33 -0
  60. package/dist/src/commands/_server-client.js +477 -46
  61. package/dist/src/commands/_server-events.js +446 -41
  62. package/dist/src/commands/_snapshot-upload.js +460 -48
  63. package/dist/src/commands/connect.js +620 -15
  64. package/dist/src/commands/doctor.js +458 -46
  65. package/dist/src/commands/github.js +462 -50
  66. package/dist/src/commands/inbox.js +458 -46
  67. package/dist/src/commands/init.js +497 -74
  68. package/dist/src/commands/inspect.js +458 -46
  69. package/dist/src/commands/run.js +496 -57
  70. package/dist/src/commands/server.js +647 -163
  71. package/dist/src/commands/setup.js +463 -51
  72. package/dist/src/commands/stats.js +462 -48
  73. package/dist/src/commands/task-run-driver.js +464 -52
  74. package/dist/src/commands/task.js +551 -85
  75. package/dist/src/commands.js +701 -151
  76. package/dist/src/index.js +705 -151
  77. package/dist/src/launcher.js +4 -0
  78. package/package.json +8 -8
@@ -210,16 +210,31 @@ function taskViewIntent(argv, command = "", rest = [], raw) {
210
210
  const { payload, label } = taskViewPayload(command, rest);
211
211
  return intent("tasks", argv, "refresh", payload, label, raw);
212
212
  }
213
- function routeServer(argv, command, raw, checkingLabel) {
214
- if (!command || command === "status") {
213
+ function routeServer(argv, command, rest, raw, checkingLabel) {
214
+ if (!command || command === "status" || command === "list") {
215
215
  return intent("server", argv, "refresh", undefined, command ? checkingLabel : "Loading server", raw);
216
216
  }
217
+ if (command === "use") {
218
+ const alias = firstNonOption(rest);
219
+ if (alias === "local")
220
+ return intent("server", argv, "server-use-local", undefined, "Use local server", raw);
221
+ if (alias)
222
+ return intent("server", argv, "server-use-remote", { alias }, `Use ${alias}`, raw);
223
+ return intent("server", argv, "refresh", undefined, "Select a remote alias in Server", raw);
224
+ }
225
+ if (command === "add")
226
+ return intent("server", argv, "server-add-remote", { argv: [...argv] }, "Add remote server", raw);
227
+ if (command === "repair-link")
228
+ return intent("server", argv, "remote-link-repair", undefined, "Repair remote link", raw);
217
229
  return commandRunIntent(argv, raw);
218
230
  }
219
231
  function routeGithub(argv, command, rest, raw) {
220
232
  if (command === "auth" && (rest[0]?.toLowerCase() ?? "status") === "status" && rest.length <= 1) {
221
233
  return intent("server", argv, "refresh", undefined, "Checking GitHub auth", raw);
222
234
  }
235
+ if (command === "auth" && rest[0]?.toLowerCase() === "import-gh" && rest.length <= 1) {
236
+ return intent("server", argv, "github-auth-import", undefined, "Import GitHub auth", raw);
237
+ }
223
238
  return commandRunIntent(argv, raw);
224
239
  }
225
240
  function routeDoctor(argv, command, raw) {
@@ -268,11 +283,16 @@ function intentFromArgv(argv) {
268
283
  return commandRunIntent(argv);
269
284
  }
270
285
  if (normalizedGroup === "server")
271
- return routeServer(argv, normalizedCommand, undefined, "Checking server");
286
+ return routeServer(argv, normalizedCommand, rest, undefined, "Checking server");
272
287
  if (normalizedGroup === "github")
273
288
  return routeGithub(argv, normalizedCommand, rest);
274
- if (normalizedGroup === "init")
275
- return commandRunIntent(argv);
289
+ if (normalizedGroup === "init") {
290
+ if (!normalizedCommand)
291
+ return intent("init", argv, "refresh", undefined, "Open init");
292
+ if (rest.includes("--yes") || normalizedCommand === "--yes")
293
+ return intent("init", argv, "init-start", undefined, "Run init");
294
+ return intent("init", argv, "refresh", undefined, "Open init");
295
+ }
276
296
  if (normalizedGroup === "doctor")
277
297
  return routeDoctor(argv, normalizedCommand);
278
298
  if (normalizedGroup === "inbox")
@@ -335,12 +355,17 @@ function intentFromTypeBar(value) {
335
355
  return commandRunIntent(parts, value);
336
356
  return intent("tasks", parts, "refresh", undefined, "Select a task, then press Enter; or use run next", value);
337
357
  }
338
- if (first === "init")
339
- return commandRunIntent(parts, value);
358
+ if (first === "init") {
359
+ if (!second)
360
+ return intent("init", parts, "refresh", undefined, "Open init", value);
361
+ if (parts.includes("--yes"))
362
+ return intent("init", parts, "init-start", undefined, "Run init", value);
363
+ return intent("init", parts, "refresh", undefined, "Open init", value);
364
+ }
340
365
  if (first === "doctor")
341
366
  return routeDoctor(parts, second, value);
342
367
  if (first === "server")
343
- return routeServer(parts, second, value, "Loading server");
368
+ return routeServer(parts, second, rest, value, "Loading server");
344
369
  if (first === "github")
345
370
  return routeGithub(parts, second, rest, value);
346
371
  if (first === "inbox")
@@ -402,7 +427,7 @@ function truncateText(text, width) {
402
427
  // packages/cli/src/app-opentui/runtime.ts
403
428
  import { existsSync as existsSync3 } from "fs";
404
429
  import { resolve as resolve3 } from "path";
405
- import { BoxRenderable as BoxRenderable3, RGBA as RGBA8, StyledText as StyledText4, TextRenderable as TextRenderable4, createCliRenderer } from "@opentui/core";
430
+ import { BoxRenderable as BoxRenderable3, RGBA as RGBA7, StyledText as StyledText3, TextRenderable as TextRenderable4, createCliRenderer } from "@opentui/core";
406
431
 
407
432
  // packages/cli/src/app-opentui/focus-manager.ts
408
433
  class AppFocusManager {
@@ -727,12 +752,13 @@ var PRIMARY_GROUPS = [
727
752
  {
728
753
  name: "server",
729
754
  summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
730
- usage: ["rig server <status|list|add|use|start> [options]"],
755
+ usage: ["rig server <status|list|add|use|repair-link|start> [options]"],
731
756
  commands: [
732
- { command: "status", description: "Show the selected server for this repo.", primary: true },
757
+ { command: "status", description: "Show the selected server and remote project-root link for this repo.", primary: true },
733
758
  { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
734
759
  { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
735
760
  { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
761
+ { command: "repair-link [--prepare|--backfill-only] [--repo owner/repo]", description: "Backfill or prepare the selected remote's server-host checkout link.", primary: true },
736
762
  { command: "list", description: "List saved local/remote server aliases.", primary: true },
737
763
  { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
738
764
  ],
@@ -740,6 +766,7 @@ var PRIMARY_GROUPS = [
740
766
  "rig server status",
741
767
  "rig server add prod https://where.rig-does.work",
742
768
  "rig server use prod",
769
+ "rig server repair-link --repo owner/repo",
743
770
  "rig server use local",
744
771
  "rig server start --port 3773"
745
772
  ],
@@ -1244,397 +1271,6 @@ function cycleCompletion(value, state, candidates = commandCandidates()) {
1244
1271
  return { value: matches[nextIndex], state: { base, index: nextIndex } };
1245
1272
  }
1246
1273
 
1247
- // packages/cli/src/app-opentui/pi-pty-host.ts
1248
- import { fileURLToPath as fileURLToPath2 } from "url";
1249
- import { basename as basename2 } from "path";
1250
- import { RGBA, StyledText, TextAttributes } from "@opentui/core";
1251
- import { Terminal as XtermTerminal2 } from "@xterm/headless";
1252
- var MIN_COLS2 = 40;
1253
- var MIN_ROWS2 = 12;
1254
- var MAX_ROWS2 = 300;
1255
- var MAX_SNAPSHOT_LINES2 = 360;
1256
- var STYLED_SNAPSHOT_MARGIN = 6;
1257
- var SNAPSHOT_DELAY_MS2 = 120;
1258
- var fallbackChildScriptPath = fileURLToPath2(new URL("./pi-host-child.ts", import.meta.url));
1259
- var activeHost2 = null;
1260
- function clampCols2(cols) {
1261
- return Math.max(MIN_COLS2, Math.trunc(cols || 100));
1262
- }
1263
- function clampRows2(rows) {
1264
- return Math.max(MIN_ROWS2, Math.min(MAX_ROWS2, Math.trunc(rows || 35)));
1265
- }
1266
- var XTERM_COLOR_MODE_INDEXED_16 = 16777216;
1267
- var XTERM_COLOR_MODE_INDEXED_256 = 33554432;
1268
- var XTERM_COLOR_MODE_RGB = 50331648;
1269
- function rgbaFromXtermColor(mode, value) {
1270
- if (mode === 1 || mode === 2 || mode === XTERM_COLOR_MODE_INDEXED_16 || mode === XTERM_COLOR_MODE_INDEXED_256) {
1271
- return RGBA.fromIndex(value);
1272
- }
1273
- if (mode === 3 || mode === XTERM_COLOR_MODE_RGB) {
1274
- return RGBA.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255);
1275
- }
1276
- return;
1277
- }
1278
- function textAttributesFromCell(cell) {
1279
- let attributes = TextAttributes.NONE;
1280
- if (cell.isBold())
1281
- attributes |= TextAttributes.BOLD;
1282
- if (cell.isDim())
1283
- attributes |= TextAttributes.DIM;
1284
- if (cell.isItalic())
1285
- attributes |= TextAttributes.ITALIC;
1286
- if (cell.isUnderline())
1287
- attributes |= TextAttributes.UNDERLINE;
1288
- if (cell.isBlink())
1289
- attributes |= TextAttributes.BLINK;
1290
- if (cell.isInverse())
1291
- attributes |= TextAttributes.INVERSE;
1292
- if (cell.isInvisible())
1293
- attributes |= TextAttributes.HIDDEN;
1294
- if (cell.isStrikethrough())
1295
- attributes |= TextAttributes.STRIKETHROUGH;
1296
- return attributes;
1297
- }
1298
- function sameRgba(a, b) {
1299
- if (!a && !b)
1300
- return true;
1301
- return Boolean(a && b && a.equals(b));
1302
- }
1303
- function sameStyle(a, b) {
1304
- return sameRgba(a.fg, b.fg) && sameRgba(a.bg, b.bg) && (a.attributes ?? 0) === (b.attributes ?? 0);
1305
- }
1306
- function styleFromCell(cell) {
1307
- return {
1308
- fg: rgbaFromXtermColor(cell.getFgColorMode(), cell.getFgColor()),
1309
- bg: rgbaFromXtermColor(cell.getBgColorMode(), cell.getBgColor()),
1310
- attributes: textAttributesFromCell(cell)
1311
- };
1312
- }
1313
- function lineToStyledText(line, cols) {
1314
- if (!line)
1315
- return new StyledText([{ __isChunk: true, text: "" }]);
1316
- const chunks = [];
1317
- let run = "";
1318
- let runStyle = null;
1319
- const flush = () => {
1320
- if (!run)
1321
- return;
1322
- chunks.push({
1323
- __isChunk: true,
1324
- text: run,
1325
- ...runStyle?.fg ? { fg: runStyle.fg } : {},
1326
- ...runStyle?.bg ? { bg: runStyle.bg } : {},
1327
- ...(runStyle?.attributes ?? 0) !== 0 ? { attributes: runStyle.attributes } : {}
1328
- });
1329
- run = "";
1330
- };
1331
- for (let index = 0;index < cols; index += 1) {
1332
- const cell = line.getCell(index);
1333
- if (!cell) {
1334
- if (runStyle !== null)
1335
- flush();
1336
- runStyle = null;
1337
- run += " ";
1338
- continue;
1339
- }
1340
- if (cell.getWidth() === 0)
1341
- continue;
1342
- const style = styleFromCell(cell);
1343
- if (!runStyle || !sameStyle(runStyle, style)) {
1344
- flush();
1345
- runStyle = style;
1346
- }
1347
- run += cell.getChars() || " ";
1348
- }
1349
- flush();
1350
- return new StyledText(chunks.length > 0 ? chunks : [{ __isChunk: true, text: "" }]);
1351
- }
1352
- function childCommandPrefix2() {
1353
- const execName = basename2(process.execPath).toLowerCase();
1354
- const currentEntry = process.argv[1];
1355
- if (execName === "bun" || execName === "bun.exe") {
1356
- return currentEntry ? [process.execPath, currentEntry, "__opentui-pi-host"] : [process.execPath, fallbackChildScriptPath];
1357
- }
1358
- return [process.execPath, "__opentui-pi-host"];
1359
- }
1360
- function withEnv2(base) {
1361
- const env = {};
1362
- for (const [key, value] of Object.entries(base ?? process.env)) {
1363
- if (key === "RIG_PLAIN" || key === "RIG_CLI_PLAIN_HELP" || key === "NO_COLOR")
1364
- continue;
1365
- if (typeof value === "string")
1366
- env[key] = value;
1367
- }
1368
- return {
1369
- ...env,
1370
- TERM: "xterm-256color",
1371
- COLORTERM: "truecolor",
1372
- FORCE_COLOR: env.FORCE_COLOR ?? "1",
1373
- RIG_OPENTUI_PI_HOST: "1"
1374
- };
1375
- }
1376
- function getActivePiHost() {
1377
- return activeHost2 && !activeHost2.disposed ? activeHost2 : null;
1378
- }
1379
- function stopActivePiHost(reason = "detach") {
1380
- activeHost2?.dispose(reason);
1381
- activeHost2 = null;
1382
- }
1383
-
1384
- class PiPtyHost {
1385
- runId;
1386
- projectRoot;
1387
- onSnapshot;
1388
- onExit;
1389
- onError;
1390
- terminal;
1391
- disposables = [];
1392
- decoder = new TextDecoder("utf-8");
1393
- proc = null;
1394
- pty = null;
1395
- status = "starting";
1396
- cols;
1397
- rows;
1398
- message = "starting bundled Pi";
1399
- lastResizeError = null;
1400
- exitCode;
1401
- signal;
1402
- notifyTimer = null;
1403
- lastStreamKey = "";
1404
- _disposed = false;
1405
- constructor(options) {
1406
- this.runId = options.runId;
1407
- this.projectRoot = options.projectRoot;
1408
- this.cols = clampCols2(options.cols);
1409
- this.rows = clampRows2(options.rows);
1410
- this.onSnapshot = options.onSnapshot;
1411
- this.onExit = options.onExit;
1412
- this.onError = options.onError;
1413
- this.terminal = new XtermTerminal2({
1414
- allowProposedApi: true,
1415
- cols: this.cols,
1416
- rows: this.rows,
1417
- scrollback: 1000
1418
- });
1419
- this.registerTerminalResponders();
1420
- this.disposables.push(this.terminal.onWriteParsed(() => {
1421
- if (this._disposed)
1422
- return;
1423
- const snapshot = this.createSnapshot();
1424
- const key = snapshot.lines.join(`
1425
- `);
1426
- if (key === this.lastStreamKey)
1427
- return;
1428
- this.lastStreamKey = key;
1429
- this.onSnapshot?.(snapshot);
1430
- }));
1431
- }
1432
- get disposed() {
1433
- return this._disposed;
1434
- }
1435
- get snapshot() {
1436
- return this.createSnapshot();
1437
- }
1438
- async start() {
1439
- if (this._disposed)
1440
- throw new Error("Pi PTY host is disposed.");
1441
- if (typeof Bun.Terminal !== "function") {
1442
- throw new Error("Bun native PTY is unavailable in this runtime. Pi host requires Bun.Terminal.");
1443
- }
1444
- const spawnOptions = {
1445
- cwd: this.projectRoot,
1446
- env: withEnv2(process.env),
1447
- terminal: {
1448
- cols: this.cols,
1449
- rows: this.rows,
1450
- name: "xterm-256color",
1451
- data: (_terminal, data) => this.handlePtyData(data)
1452
- }
1453
- };
1454
- const proc = Bun.spawn([
1455
- ...childCommandPrefix2(),
1456
- "--run-id",
1457
- this.runId,
1458
- "--project-root",
1459
- this.projectRoot
1460
- ], spawnOptions);
1461
- if (!proc.terminal)
1462
- throw new Error("Bun did not attach a terminal to the bundled Pi child process.");
1463
- this.proc = proc;
1464
- this.pty = proc.terminal;
1465
- this.status = "running";
1466
- this.message = "bundled Pi running inside this app";
1467
- this.emitSnapshotSoon(0);
1468
- proc.exited.then((exitCode) => {
1469
- if (this._disposed)
1470
- return;
1471
- this.status = exitCode === 0 ? "exited" : "failed";
1472
- this.exitCode = exitCode;
1473
- this.signal = null;
1474
- this.message = exitCode === 0 ? "bundled Pi exited" : `bundled Pi exited with code ${exitCode}`;
1475
- const snapshot = this.createSnapshot();
1476
- this.onSnapshot?.(snapshot);
1477
- this.onExit?.(snapshot);
1478
- if (activeHost2 === this)
1479
- activeHost2 = null;
1480
- this.dispose("exit", { kill: false, notify: false });
1481
- }).catch((error) => {
1482
- if (this._disposed)
1483
- return;
1484
- this.status = "failed";
1485
- this.message = error instanceof Error ? error.message : String(error);
1486
- const snapshot = this.createSnapshot();
1487
- this.onSnapshot?.(snapshot);
1488
- this.onError?.(error, snapshot);
1489
- if (activeHost2 === this)
1490
- activeHost2 = null;
1491
- this.dispose("error", { kill: false, notify: false });
1492
- });
1493
- }
1494
- write(data) {
1495
- if (this._disposed || !this.pty)
1496
- return;
1497
- try {
1498
- this.pty.write(data);
1499
- } catch (error) {
1500
- this.status = "failed";
1501
- this.message = error instanceof Error ? error.message : String(error);
1502
- const snapshot = this.createSnapshot();
1503
- this.onSnapshot?.(snapshot);
1504
- this.onError?.(error, snapshot);
1505
- }
1506
- }
1507
- resize(cols, rows) {
1508
- const nextCols = clampCols2(cols);
1509
- const nextRows = clampRows2(rows);
1510
- if (nextCols === this.cols && nextRows === this.rows)
1511
- return;
1512
- this.cols = nextCols;
1513
- this.rows = nextRows;
1514
- this.terminal.resize(nextCols, nextRows);
1515
- try {
1516
- this.pty?.resize(nextCols, nextRows);
1517
- this.lastResizeError = null;
1518
- } catch (error) {
1519
- this.lastResizeError = error instanceof Error ? error.message : String(error);
1520
- }
1521
- this.emitSnapshotSoon(0);
1522
- }
1523
- detach() {
1524
- this.dispose("detach");
1525
- return this.createSnapshot("detached from bundled Pi");
1526
- }
1527
- dispose(reason = "dispose", options = {}) {
1528
- if (this._disposed)
1529
- return;
1530
- this._disposed = true;
1531
- if (this.notifyTimer)
1532
- clearTimeout(this.notifyTimer);
1533
- this.notifyTimer = null;
1534
- for (const disposable of this.disposables.splice(0)) {
1535
- try {
1536
- disposable.dispose();
1537
- } catch {}
1538
- }
1539
- if (options.kill !== false) {
1540
- try {
1541
- this.proc?.kill("SIGTERM");
1542
- } catch {}
1543
- }
1544
- try {
1545
- this.pty?.close();
1546
- } catch {}
1547
- try {
1548
- this.terminal.dispose();
1549
- } catch {}
1550
- if (activeHost2 === this)
1551
- activeHost2 = null;
1552
- if (options.notify) {
1553
- this.message = reason;
1554
- this.onSnapshot?.(this.createSnapshot(reason));
1555
- }
1556
- }
1557
- handlePtyData(data) {
1558
- if (this._disposed)
1559
- return;
1560
- const text = this.decoder.decode(data, { stream: true });
1561
- this.respondToRawTerminalQueries(text);
1562
- this.terminal.write(data);
1563
- }
1564
- emitSnapshotSoon(delayMs = SNAPSHOT_DELAY_MS2) {
1565
- if (this._disposed || this.notifyTimer)
1566
- return;
1567
- this.notifyTimer = setTimeout(() => {
1568
- this.notifyTimer = null;
1569
- if (this._disposed)
1570
- return;
1571
- this.onSnapshot?.(this.createSnapshot());
1572
- }, delayMs);
1573
- }
1574
- createSnapshot(message = this.message) {
1575
- const buffer = this.terminal.buffer.active;
1576
- const end = buffer.length;
1577
- const start = Math.max(0, end - MAX_SNAPSHOT_LINES2);
1578
- const styledStart = Math.max(start, end - this.rows - STYLED_SNAPSHOT_MARGIN);
1579
- const lines = [];
1580
- const styledLines = [];
1581
- for (let row = start;row < end; row += 1) {
1582
- const line = buffer.getLine(row);
1583
- lines.push((line?.translateToString(false) ?? "").slice(0, this.cols));
1584
- if (row >= styledStart)
1585
- styledLines[lines.length - 1] = lineToStyledText(line, this.cols);
1586
- }
1587
- while (lines.length < this.rows) {
1588
- lines.push("");
1589
- styledLines[lines.length - 1] = new StyledText([{ __isChunk: true, text: "" }]);
1590
- }
1591
- const resolvedMessage = this.lastResizeError ? `resize degraded: ${this.lastResizeError}` : message;
1592
- return {
1593
- runId: this.runId,
1594
- status: this.status,
1595
- cols: this.cols,
1596
- rows: this.rows,
1597
- lines,
1598
- styledLines,
1599
- message: resolvedMessage,
1600
- ...this.lastResizeError ? { resizeError: this.lastResizeError } : {},
1601
- ...this.exitCode !== undefined ? { exitCode: this.exitCode } : {},
1602
- ...this.signal !== undefined ? { signal: this.signal } : {}
1603
- };
1604
- }
1605
- registerTerminalResponders() {
1606
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "c" }, (params) => {
1607
- if (params.length === 0 || params[0] === 0)
1608
- this.write("\x1B[?62;22c");
1609
- return false;
1610
- }));
1611
- this.disposables.push(this.terminal.parser.registerCsiHandler({ prefix: ">", final: "c" }, (params) => {
1612
- if (params.length === 0 || params[0] === 0)
1613
- this.write("\x1B[>0;0;0c");
1614
- return false;
1615
- }));
1616
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "n" }, (params) => {
1617
- if (params[0] === 5) {
1618
- this.write("\x1B[0n");
1619
- } else if (params[0] === 6) {
1620
- const row = this.terminal.buffer.active.cursorY + 1;
1621
- const col = this.terminal.buffer.active.cursorX + 1;
1622
- this.write(`\x1B[${row};${col}R`);
1623
- }
1624
- return false;
1625
- }));
1626
- }
1627
- respondToRawTerminalQueries(text) {
1628
- if (!text)
1629
- return;
1630
- const decrqm = /\x1b\[\?(\d+)\$p/g;
1631
- let match;
1632
- while ((match = decrqm.exec(text)) !== null) {
1633
- this.write(`\x1B[?${match[1]};2$y`);
1634
- }
1635
- }
1636
- }
1637
-
1638
1274
  // packages/cli/src/app-opentui/keymap.ts
1639
1275
  var autocompleteState;
1640
1276
  function clearTypeBar(context, message) {
@@ -1644,22 +1280,15 @@ function clearTypeBar(context, message) {
1644
1280
  context.emitTypeBarPatch({ value: "", mode: "nav", prompt: undefined, message });
1645
1281
  }
1646
1282
  function handleEmbeddedTerminalKey(context, key) {
1647
- const state = context.getState();
1648
- const piHost = getActivePiHost();
1649
- const commandHost = getActiveCommandHost();
1650
- const host = state.scene === "handoff" ? piHost : state.scene === "command" ? commandHost : null;
1283
+ if (context.getState().scene !== "command")
1284
+ return false;
1285
+ const host = getActiveCommandHost();
1651
1286
  if (!host)
1652
1287
  return false;
1653
1288
  if (key.ctrl && key.name === "]") {
1654
- if (state.scene === "handoff") {
1655
- stopActivePiHost("operator detach");
1656
- clearTypeBar(context, "detached from Pi");
1657
- context.runAppAction("Opening runs", () => context.runtime.runIntent({ scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } }));
1658
- } else {
1659
- stopActiveCommandHost("operator detach");
1660
- clearTypeBar(context, "closed command");
1661
- context.runAppAction("Project menu", () => context.runtime.runIntent({ scene: "main", argv: ["main"], action: { kind: "none", label: "Project menu" } }));
1662
- }
1289
+ stopActiveCommandHost("operator detach");
1290
+ clearTypeBar(context, "closed command");
1291
+ context.runAppAction("Project menu", () => context.runtime.runIntent({ scene: "main", argv: ["main"], action: { kind: "none", label: "Project menu" } }));
1663
1292
  return true;
1664
1293
  }
1665
1294
  const sequence = key.raw || key.sequence;
@@ -1928,8 +1557,8 @@ import { WsTransport } from "@rig/client";
1928
1557
  import { RIG_WS_CHANNELS } from "@rig/contracts";
1929
1558
 
1930
1559
  // packages/cli/src/commands/_server-client.ts
1931
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1932
- import { resolve as resolve2 } from "path";
1560
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
1561
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
1933
1562
 
1934
1563
  // packages/cli/src/runner.ts
1935
1564
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
@@ -2021,12 +1650,28 @@ function readRepoConnection(projectRoot) {
2021
1650
  selected,
2022
1651
  project: typeof record.project === "string" ? record.project : undefined,
2023
1652
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
2024
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
1653
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
1654
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
1655
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
2025
1656
  };
2026
1657
  }
2027
1658
  function writeRepoConnection(projectRoot, state) {
2028
1659
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
2029
1660
  }
1661
+ function rootAllowedForSelection(repo, connection) {
1662
+ const root = repo.serverProjectRoot?.trim();
1663
+ if (!root)
1664
+ return;
1665
+ if (connection.kind === "remote") {
1666
+ if (repo.serverProjectRootAlias !== repo.selected)
1667
+ return;
1668
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
1669
+ return;
1670
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
1671
+ return;
1672
+ }
1673
+ return root;
1674
+ }
2030
1675
  function resolveSelectedConnection(projectRoot, options = {}) {
2031
1676
  const repo = readRepoConnection(projectRoot);
2032
1677
  if (!repo)
@@ -2038,13 +1683,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
2038
1683
  if (!connection) {
2039
1684
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
2040
1685
  }
2041
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
1686
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
1687
+ }
1688
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
1689
+ const repo = readRepoConnection(projectRoot);
1690
+ if (!repo)
1691
+ return;
1692
+ let inferred = metadata;
1693
+ if (!inferred.alias || !inferred.baseUrl) {
1694
+ try {
1695
+ const selected = resolveSelectedConnection(projectRoot);
1696
+ if (selected?.connection.kind === "remote") {
1697
+ inferred = {
1698
+ alias: inferred.alias ?? selected.alias,
1699
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
1700
+ };
1701
+ }
1702
+ } catch {}
1703
+ }
1704
+ writeRepoConnection(projectRoot, {
1705
+ ...repo,
1706
+ ...metadata.project ? { project: metadata.project } : {},
1707
+ serverProjectRoot,
1708
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
1709
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
1710
+ });
2042
1711
  }
2043
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
1712
+ function clearRepoServerProjectRoot(projectRoot) {
2044
1713
  const repo = readRepoConnection(projectRoot);
2045
1714
  if (!repo)
2046
1715
  return;
2047
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
1716
+ writeRepoConnection(projectRoot, {
1717
+ selected: repo.selected,
1718
+ ...repo.project ? { project: repo.project } : {},
1719
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
1720
+ });
2048
1721
  }
2049
1722
 
2050
1723
  // packages/cli/src/commands/_server-client.ts
@@ -2085,11 +1758,10 @@ function readStoredGitHubAuthToken(projectRoot) {
2085
1758
  const parsed = readRemoteAuthState(projectRoot);
2086
1759
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
2087
1760
  }
2088
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
2089
- const repo = readRepoConnection(projectRoot);
2090
- const slug = repo?.project?.trim();
2091
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
1761
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
1762
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
2092
1763
  return null;
1764
+ const repo = readRepoConnection(projectRoot);
2093
1765
  const auth = readRemoteAuthState(projectRoot);
2094
1766
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
2095
1767
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -2098,25 +1770,413 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
2098
1770
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
2099
1771
  if (!checkoutBaseDir)
2100
1772
  return null;
2101
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
2102
- writeRepoServerProjectRoot(projectRoot, inferred);
2103
- return inferred;
1773
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
2104
1774
  }
2105
1775
  function readLocalConnectionFallbackToken(projectRoot) {
2106
1776
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
2107
1777
  }
1778
+ function normalizeRepoSlug(value) {
1779
+ const slug = value?.trim();
1780
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
1781
+ }
1782
+ function readProjectLinkSlug(projectRoot) {
1783
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
1784
+ if (!existsSync2(path))
1785
+ return null;
1786
+ try {
1787
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
1788
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1789
+ return null;
1790
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
1791
+ } catch {
1792
+ return null;
1793
+ }
1794
+ }
1795
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
1796
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
1797
+ mkdirSync2(dirname2(path), { recursive: true });
1798
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
1799
+ `, "utf8");
1800
+ }
1801
+ function remoteLinkRepairCommand(repoSlug) {
1802
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
1803
+ }
1804
+ function formatRemoteProjectLinkHint(resolution) {
1805
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
1806
+ if (resolution.status === "auth_required") {
1807
+ return `Authenticate the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}, then run \`${repair}\`. Use \`rig github auth import-gh\` or \`rig init --repair --server remote --github-auth device${resolution.repoSlug ? ` --repo ${resolution.repoSlug}` : ""}\`.`;
1808
+ }
1809
+ if (resolution.status === "missing_project") {
1810
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
1811
+ }
1812
+ if (resolution.status === "not_remote")
1813
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
1814
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
1815
+ }
1816
+ function remoteProjectLinkFailure(input) {
1817
+ const partial = {
1818
+ status: input.status,
1819
+ alias: input.alias,
1820
+ baseUrl: input.baseUrl,
1821
+ repoSlug: input.repoSlug
1822
+ };
1823
+ return {
1824
+ ok: false,
1825
+ ...input,
1826
+ hint: formatRemoteProjectLinkHint(partial),
1827
+ next: remoteLinkRepairCommand(input.repoSlug)
1828
+ };
1829
+ }
1830
+ function remoteProjectLinkSuccess(input) {
1831
+ return {
1832
+ ok: true,
1833
+ status: input.status,
1834
+ alias: input.alias,
1835
+ baseUrl: input.baseUrl,
1836
+ repoSlug: input.repoSlug,
1837
+ serverProjectRoot: input.serverProjectRoot,
1838
+ source: input.source,
1839
+ prepared: input.prepared ?? input.status === "prepared",
1840
+ validated: input.validated ?? false,
1841
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
1842
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
1843
+ next: "rig task list"
1844
+ };
1845
+ }
1846
+ function localCheckoutPathCandidate(projectRoot, candidate) {
1847
+ try {
1848
+ const local = resolve2(projectRoot);
1849
+ const resolved = resolve2(candidate);
1850
+ return resolved === local || resolved.startsWith(`${local}/`);
1851
+ } catch {
1852
+ return false;
1853
+ }
1854
+ }
1855
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
1856
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
1857
+ if (authToken && queryAuthFallbackEnabled())
1858
+ requestUrl.searchParams.set("rt", authToken);
1859
+ const response = await fetch(requestUrl, {
1860
+ ...init,
1861
+ headers: mergeHeaders(init.headers, authToken)
1862
+ });
1863
+ const text = await response.text();
1864
+ const payload = text.trim().length > 0 ? (() => {
1865
+ try {
1866
+ return JSON.parse(text);
1867
+ } catch {
1868
+ return null;
1869
+ }
1870
+ })() : null;
1871
+ return { ok: response.ok, status: response.status, payload, text };
1872
+ }
1873
+ function payloadError(payload, fallback) {
1874
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
1875
+ const record = payload;
1876
+ const value = record.error ?? record.message ?? record.reason;
1877
+ if (typeof value === "string" && value.trim())
1878
+ return value.trim();
1879
+ }
1880
+ return fallback;
1881
+ }
1882
+ function checkoutPathsFromProjectPayload(payload) {
1883
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1884
+ return [];
1885
+ const project = payload.project;
1886
+ if (!project || typeof project !== "object" || Array.isArray(project))
1887
+ return [];
1888
+ const checkouts = project.checkouts;
1889
+ if (!Array.isArray(checkouts))
1890
+ return [];
1891
+ return [...checkouts].reverse().flatMap((entry) => {
1892
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
1893
+ return [];
1894
+ const path = entry.path;
1895
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
1896
+ });
1897
+ }
1898
+ function checkoutPathFromPreparePayload(payload) {
1899
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1900
+ return null;
1901
+ const checkout = payload.checkout;
1902
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
1903
+ return null;
1904
+ const path = checkout.path;
1905
+ return typeof path === "string" && path.trim() ? path.trim() : null;
1906
+ }
1907
+ async function validateAndPersistRemoteRoot(input) {
1908
+ const candidate = input.candidate.trim();
1909
+ if (!candidate || !isAbsolute(candidate)) {
1910
+ return remoteProjectLinkFailure({
1911
+ status: "invalid_root",
1912
+ alias: input.alias,
1913
+ baseUrl: input.baseUrl,
1914
+ repoSlug: input.repoSlug,
1915
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
1916
+ });
1917
+ }
1918
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
1919
+ return remoteProjectLinkFailure({
1920
+ status: "invalid_root",
1921
+ alias: input.alias,
1922
+ baseUrl: input.baseUrl,
1923
+ repoSlug: input.repoSlug,
1924
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
1925
+ });
1926
+ }
1927
+ let response;
1928
+ try {
1929
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
1930
+ method: "POST",
1931
+ headers: { "content-type": "application/json" },
1932
+ body: JSON.stringify({ projectRoot: candidate })
1933
+ });
1934
+ } catch (error) {
1935
+ return remoteProjectLinkFailure({
1936
+ status: "error",
1937
+ alias: input.alias,
1938
+ baseUrl: input.baseUrl,
1939
+ repoSlug: input.repoSlug,
1940
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
1941
+ });
1942
+ }
1943
+ if (response.status === 401 || response.status === 403) {
1944
+ return remoteProjectLinkFailure({
1945
+ status: "auth_required",
1946
+ alias: input.alias,
1947
+ baseUrl: input.baseUrl,
1948
+ repoSlug: input.repoSlug,
1949
+ statusCode: response.status,
1950
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
1951
+ });
1952
+ }
1953
+ if (!response.ok) {
1954
+ return remoteProjectLinkFailure({
1955
+ status: "invalid_root",
1956
+ alias: input.alias,
1957
+ baseUrl: input.baseUrl,
1958
+ repoSlug: input.repoSlug,
1959
+ statusCode: response.status,
1960
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
1961
+ });
1962
+ }
1963
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
1964
+ if (record.ok !== true) {
1965
+ return remoteProjectLinkFailure({
1966
+ status: "invalid_root",
1967
+ alias: input.alias,
1968
+ baseUrl: input.baseUrl,
1969
+ repoSlug: input.repoSlug,
1970
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
1971
+ });
1972
+ }
1973
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
1974
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
1975
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
1976
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
1977
+ return remoteProjectLinkSuccess({
1978
+ status,
1979
+ alias: input.alias,
1980
+ baseUrl: input.baseUrl,
1981
+ repoSlug: input.repoSlug,
1982
+ serverProjectRoot: accepted,
1983
+ source: input.source,
1984
+ prepared: input.prepared,
1985
+ validated: true,
1986
+ message: status === "ready" ? `Remote project link already points to ${accepted} and was validated on ${input.alias}.` : input.prepared ? `Prepared and linked remote checkout ${accepted} for ${input.repoSlug}.` : `Backfilled remote checkout ${accepted} for ${input.repoSlug}.`
1987
+ });
1988
+ }
1989
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
1990
+ let selected;
1991
+ try {
1992
+ selected = resolveSelectedConnection(projectRoot);
1993
+ } catch (error) {
1994
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
1995
+ }
1996
+ if (!selected || selected.connection.kind !== "remote") {
1997
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
1998
+ }
1999
+ const repo = readRepoConnection(projectRoot);
2000
+ const explicitRepoRequested = options.repoSlug !== undefined;
2001
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
2002
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
2003
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
2004
+ const alias = selected.alias;
2005
+ const baseUrl = selected.connection.baseUrl;
2006
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
2007
+ const mode = options.mode ?? "backfill-only";
2008
+ if (explicitRepoRequested && !explicitRepoSlug) {
2009
+ return remoteProjectLinkFailure({
2010
+ status: "missing_project",
2011
+ alias,
2012
+ baseUrl,
2013
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
2014
+ });
2015
+ }
2016
+ if (!repoSlug) {
2017
+ return remoteProjectLinkFailure({
2018
+ status: "missing_project",
2019
+ alias,
2020
+ baseUrl,
2021
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
2022
+ });
2023
+ }
2024
+ const skippedCandidates = [];
2025
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
2026
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
2027
+ if (storedRoot && storedRootMatchesResolvedRepo) {
2028
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
2029
+ clearRepoServerProjectRoot(projectRoot);
2030
+ skippedCandidates.push(storedRoot);
2031
+ } else {
2032
+ const storedResult = await validateAndPersistRemoteRoot({
2033
+ projectRoot,
2034
+ alias,
2035
+ baseUrl,
2036
+ authToken,
2037
+ repoSlug,
2038
+ candidate: storedRoot,
2039
+ source: "stored",
2040
+ status: "ready"
2041
+ });
2042
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
2043
+ return storedResult;
2044
+ clearRepoServerProjectRoot(projectRoot);
2045
+ skippedCandidates.push(storedRoot);
2046
+ }
2047
+ } else if (storedRoot) {
2048
+ skippedCandidates.push(storedRoot);
2049
+ }
2050
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
2051
+ if (authCandidate) {
2052
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
2053
+ if (authResult.ok || authResult.status === "auth_required")
2054
+ return authResult;
2055
+ }
2056
+ let registryResponse;
2057
+ try {
2058
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
2059
+ } catch (error) {
2060
+ return remoteProjectLinkFailure({
2061
+ status: "error",
2062
+ alias,
2063
+ baseUrl,
2064
+ repoSlug,
2065
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
2066
+ });
2067
+ }
2068
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
2069
+ return remoteProjectLinkFailure({
2070
+ status: "auth_required",
2071
+ alias,
2072
+ baseUrl,
2073
+ repoSlug,
2074
+ statusCode: registryResponse.status,
2075
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
2076
+ });
2077
+ }
2078
+ if (registryResponse.ok) {
2079
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
2080
+ for (const candidate of candidates) {
2081
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
2082
+ if (result.ok || result.status === "auth_required")
2083
+ return result;
2084
+ skippedCandidates.push(candidate);
2085
+ }
2086
+ if (mode === "backfill-only") {
2087
+ return remoteProjectLinkFailure({
2088
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
2089
+ alias,
2090
+ baseUrl,
2091
+ repoSlug,
2092
+ message: candidates.length > 0 ? `Remote registry has checkout candidates for ${repoSlug}, but none validated for ${alias}.` : `Remote registry has ${repoSlug}, but no server checkout path is linked yet.`,
2093
+ skippedCandidates
2094
+ });
2095
+ }
2096
+ } else if (registryResponse.status === 404) {
2097
+ if (mode === "backfill-only") {
2098
+ return remoteProjectLinkFailure({
2099
+ status: "project_not_registered",
2100
+ alias,
2101
+ baseUrl,
2102
+ repoSlug,
2103
+ statusCode: registryResponse.status,
2104
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
2105
+ });
2106
+ }
2107
+ } else {
2108
+ return remoteProjectLinkFailure({
2109
+ status: "error",
2110
+ alias,
2111
+ baseUrl,
2112
+ repoSlug,
2113
+ statusCode: registryResponse.status,
2114
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
2115
+ skippedCandidates
2116
+ });
2117
+ }
2118
+ let prepareResponse;
2119
+ try {
2120
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
2121
+ method: "POST",
2122
+ headers: { "content-type": "application/json" },
2123
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
2124
+ });
2125
+ } catch (error) {
2126
+ return remoteProjectLinkFailure({
2127
+ status: "error",
2128
+ alias,
2129
+ baseUrl,
2130
+ repoSlug,
2131
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
2132
+ });
2133
+ }
2134
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
2135
+ return remoteProjectLinkFailure({
2136
+ status: "auth_required",
2137
+ alias,
2138
+ baseUrl,
2139
+ repoSlug,
2140
+ statusCode: prepareResponse.status,
2141
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
2142
+ });
2143
+ }
2144
+ if (!prepareResponse.ok) {
2145
+ return remoteProjectLinkFailure({
2146
+ status: "error",
2147
+ alias,
2148
+ baseUrl,
2149
+ repoSlug,
2150
+ statusCode: prepareResponse.status,
2151
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
2152
+ skippedCandidates
2153
+ });
2154
+ }
2155
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
2156
+ if (!preparedPath) {
2157
+ return remoteProjectLinkFailure({
2158
+ status: "invalid_root",
2159
+ alias,
2160
+ baseUrl,
2161
+ repoSlug,
2162
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
2163
+ skippedCandidates
2164
+ });
2165
+ }
2166
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
2167
+ }
2108
2168
  async function ensureServerForCli(projectRoot) {
2109
2169
  try {
2110
2170
  const selected = resolveSelectedConnection(projectRoot);
2111
2171
  if (selected?.connection.kind === "remote") {
2112
2172
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
2113
2173
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
2114
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
2174
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
2115
2175
  return {
2116
2176
  baseUrl: selected.connection.baseUrl,
2117
2177
  authToken,
2118
2178
  connectionKind: "remote",
2119
- serverProjectRoot
2179
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
2120
2180
  };
2121
2181
  }
2122
2182
  reportServerPhase("Starting local Rig server\u2026");
@@ -2134,32 +2194,6 @@ async function ensureServerForCli(projectRoot) {
2134
2194
  throw error;
2135
2195
  }
2136
2196
  }
2137
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
2138
- const repo = readRepoConnection(projectRoot);
2139
- const slug = repo?.project?.trim();
2140
- if (!slug)
2141
- return null;
2142
- try {
2143
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
2144
- if (authToken && queryAuthFallbackEnabled())
2145
- url.searchParams.set("rt", authToken);
2146
- const response = await fetch(url, {
2147
- headers: mergeHeaders(undefined, authToken)
2148
- });
2149
- if (!response.ok)
2150
- return null;
2151
- const payload = await response.json();
2152
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
2153
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
2154
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
2155
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
2156
- if (path)
2157
- writeRepoServerProjectRoot(projectRoot, path);
2158
- return path;
2159
- } catch {
2160
- return null;
2161
- }
2162
- }
2163
2197
  function mergeCookie(existing, name, value) {
2164
2198
  const encoded = `${name}=${encodeURIComponent(value)}`;
2165
2199
  if (!existing?.trim())
@@ -2235,7 +2269,7 @@ import {
2235
2269
  dim as otuiDim,
2236
2270
  fg as otuiFg,
2237
2271
  t,
2238
- TextAttributes as TextAttributes2
2272
+ TextAttributes
2239
2273
  } from "@opentui/core";
2240
2274
  var RIG_UI = {
2241
2275
  bg: "#070809",
@@ -2298,7 +2332,7 @@ function statusColor(status) {
2298
2332
  }
2299
2333
 
2300
2334
  // packages/cli/src/app-opentui/drone.ts
2301
- import { RGBA as RGBA2, StyledText as StyledText2, TextAttributes as TextAttributes3 } from "@opentui/core";
2335
+ import { RGBA, StyledText, TextAttributes as TextAttributes2 } from "@opentui/core";
2302
2336
  var MINI_DRONE = [
2303
2337
  "(!!!) (!!!)",
2304
2338
  " \\%==%/ ",
@@ -2314,13 +2348,13 @@ var LEAD_MARK = [
2314
2348
  var BLADE_FRAMES = ["---", "\\\\\\", "|||", "///"];
2315
2349
  var EYE_FRAMES = ["o", "@", "\u2022", "."];
2316
2350
  var COLOR = {
2317
- body: RGBA2.fromHex(RIG_UI.lime),
2318
- mini: RGBA2.fromHex(RIG_UI.limeDim),
2319
- rotor: RGBA2.fromHex(RIG_UI.cyan),
2320
- path: RGBA2.fromHex(RIG_UI.cyan),
2321
- eye: RGBA2.fromHex(RIG_UI.ink),
2322
- dim: RGBA2.fromHex(RIG_UI.ink4),
2323
- ink: RGBA2.fromHex(RIG_UI.ink2)
2351
+ body: RGBA.fromHex(RIG_UI.lime),
2352
+ mini: RGBA.fromHex(RIG_UI.limeDim),
2353
+ rotor: RGBA.fromHex(RIG_UI.cyan),
2354
+ path: RGBA.fromHex(RIG_UI.cyan),
2355
+ eye: RGBA.fromHex(RIG_UI.ink),
2356
+ dim: RGBA.fromHex(RIG_UI.ink4),
2357
+ ink: RGBA.fromHex(RIG_UI.ink2)
2324
2358
  };
2325
2359
  function bladeForTick(tick, phase = 0) {
2326
2360
  return BLADE_FRAMES[(Math.floor(tick / 3) + phase) % BLADE_FRAMES.length];
@@ -2330,12 +2364,12 @@ function eyeForTick(tick, phase = 0) {
2330
2364
  return pulse > 0.55 ? EYE_FRAMES[1] : pulse > 0.1 ? EYE_FRAMES[0] : pulse > -0.45 ? EYE_FRAMES[2] : EYE_FRAMES[3];
2331
2365
  }
2332
2366
  function chunk(text, fg, bold = false, dim = false) {
2333
- let attributes = TextAttributes3.NONE;
2367
+ let attributes = TextAttributes2.NONE;
2334
2368
  if (bold)
2335
- attributes |= TextAttributes3.BOLD;
2369
+ attributes |= TextAttributes2.BOLD;
2336
2370
  if (dim)
2337
- attributes |= TextAttributes3.DIM;
2338
- return { __isChunk: true, text, fg, ...attributes !== TextAttributes3.NONE ? { attributes } : {} };
2371
+ attributes |= TextAttributes2.DIM;
2372
+ return { __isChunk: true, text, fg, ...attributes !== TextAttributes2.NONE ? { attributes } : {} };
2339
2373
  }
2340
2374
  function styledLine(text, colorFor) {
2341
2375
  const chunks = [];
@@ -2356,7 +2390,7 @@ function styledLine(text, colorFor) {
2356
2390
  run += char;
2357
2391
  }
2358
2392
  flush();
2359
- return new StyledText2(chunks.length > 0 ? chunks : [chunk("", COLOR.ink)]);
2393
+ return new StyledText(chunks.length > 0 ? chunks : [chunk("", COLOR.ink)]);
2360
2394
  }
2361
2395
  function droneColor(char) {
2362
2396
  if (char === "?" || char === "o" || char === "@" || char === "\u2022")
@@ -2666,7 +2700,7 @@ function reduceAppEvent(state, event) {
2666
2700
  }
2667
2701
 
2668
2702
  // packages/cli/src/app-opentui/render/graphics.ts
2669
- import { FrameBufferRenderable, RGBA as RGBA3 } from "@opentui/core";
2703
+ import { FrameBufferRenderable, RGBA as RGBA2 } from "@opentui/core";
2670
2704
 
2671
2705
  // packages/cli/src/app-opentui/render/ascii-fleet.ts
2672
2706
  var LEAD_DRONE = [
@@ -2810,13 +2844,13 @@ var GLOW_FALLOFF_EXP_ASCII = 2.2;
2810
2844
  // packages/cli/src/app-opentui/render/graphics.ts
2811
2845
  var BRAILLE_SAMPLES_X = 2;
2812
2846
  var BRAILLE_SAMPLES_Y = 4;
2813
- var TRANSPARENT = RGBA3.fromValues(0, 0, 0, 0);
2814
- var BACKDROP = RGBA3.fromHex(RIG_UI.bg);
2815
- var PANEL_BG = RGBA3.fromInts(16, 17, 21, 184);
2816
- var PANEL_HEADER_BG = RGBA3.fromInts(16, 17, 21, 188);
2817
- var PANEL_LINE = RGBA3.fromInts(255, 255, 255, 20);
2818
- var PANEL_LINE_DIM = RGBA3.fromInts(255, 255, 255, 8);
2819
- var PANEL_TEXT_DIM = RGBA3.fromInts(108, 110, 121, 255);
2847
+ var TRANSPARENT = RGBA2.fromValues(0, 0, 0, 0);
2848
+ var BACKDROP = RGBA2.fromHex(RIG_UI.bg);
2849
+ var PANEL_BG = RGBA2.fromInts(16, 17, 21, 184);
2850
+ var PANEL_HEADER_BG = RGBA2.fromInts(16, 17, 21, 188);
2851
+ var PANEL_LINE = RGBA2.fromInts(255, 255, 255, 20);
2852
+ var PANEL_LINE_DIM = RGBA2.fromInts(255, 255, 255, 8);
2853
+ var PANEL_TEXT_DIM = RGBA2.fromInts(108, 110, 121, 255);
2820
2854
  var AC_RGB = [204, 255, 77];
2821
2855
  var C2_RGB = [86, 216, 255];
2822
2856
  var MG_RGB = [255, 121, 176];
@@ -2921,7 +2955,7 @@ function paletteColor(ac, c2, mg, ink) {
2921
2955
  const b = (AC_RGB[2] * ac + C2_RGB[2] * c2 + MG_RGB[2] * mg + INK_RGB[2] * ink) / total;
2922
2956
  const intensity = Math.min(1, total / 4);
2923
2957
  const lift = 0.34 + intensity * 0.66;
2924
- return RGBA3.fromInts(Math.round(r * lift), Math.round(g * lift), Math.round(b * lift), 255);
2958
+ return RGBA2.fromInts(Math.round(r * lift), Math.round(g * lift), Math.round(b * lift), 255);
2925
2959
  }
2926
2960
  function clearCanvas(canvas) {
2927
2961
  canvas.ac.fill(0);
@@ -3276,8 +3310,8 @@ function staticFleetTick(scene) {
3276
3310
  }
3277
3311
  function withAlpha(hex, alpha) {
3278
3312
  const a = Math.max(0, Math.min(255, Math.round(alpha * 255)));
3279
- const [r, g, b] = RGBA3.fromHex(hex).toInts();
3280
- return RGBA3.fromInts(r, g, b, a);
3313
+ const [r, g, b] = RGBA2.fromHex(hex).toInts();
3314
+ return RGBA2.fromInts(r, g, b, a);
3281
3315
  }
3282
3316
  function asciiFleetColor(char, row, alpha) {
3283
3317
  if (char === "@" || char === "$" || char === "o")
@@ -3285,7 +3319,7 @@ function asciiFleetColor(char, row, alpha) {
3285
3319
  if (char === "%" || char === "!" || char === "/" || char === "\\" || char === "|")
3286
3320
  return withAlpha(RIG_UI.cyan, alpha);
3287
3321
  if (char === "." || char === "'" || char === "_" || row < 3 || row > FLEET_GRID_HEIGHT - 4) {
3288
- return RGBA3.fromInts(108, 110, 121, Math.min(170, Math.max(0, Math.min(255, Math.round(alpha * 255)))));
3322
+ return RGBA2.fromInts(108, 110, 121, Math.min(170, Math.max(0, Math.min(255, Math.round(alpha * 255)))));
3289
3323
  }
3290
3324
  return withAlpha(RIG_UI.limeDim, alpha);
3291
3325
  }
@@ -3398,7 +3432,7 @@ function sparklineString(values, width) {
3398
3432
  }
3399
3433
 
3400
3434
  // packages/cli/src/app-opentui/render/text.ts
3401
- import { RGBA as RGBA4, TextAttributes as TextAttributes4, TextRenderable } from "@opentui/core";
3435
+ import { RGBA as RGBA3, TextAttributes as TextAttributes3, TextRenderable } from "@opentui/core";
3402
3436
 
3403
3437
  // packages/cli/src/app-opentui/render/hover.ts
3404
3438
  var hoveredId;
@@ -3425,8 +3459,8 @@ function subscribeHover(listener) {
3425
3459
  }
3426
3460
 
3427
3461
  // packages/cli/src/app-opentui/render/text.ts
3428
- var TRANSPARENT2 = RGBA4.fromInts(0, 0, 0, 0);
3429
- var HOVER_BG = RGBA4.fromHex(RIG_UI.hover);
3462
+ var TRANSPARENT2 = RGBA3.fromInts(0, 0, 0, 0);
3463
+ var HOVER_BG = RGBA3.fromHex(RIG_UI.hover);
3430
3464
  function lineIsClickable(line2) {
3431
3465
  return line2?.selectable !== undefined || line2?.selectableIndex !== undefined;
3432
3466
  }
@@ -3435,7 +3469,7 @@ function lineSelectableId(line2) {
3435
3469
  }
3436
3470
  function lineBackground(line2) {
3437
3471
  if (line2?.bg)
3438
- return RGBA4.fromHex(line2.bg);
3472
+ return RGBA3.fromHex(line2.bg);
3439
3473
  const id = lineSelectableId(line2);
3440
3474
  if (id !== undefined && isHovered(id))
3441
3475
  return HOVER_BG;
@@ -3504,7 +3538,7 @@ function applyTextLine(renderable, line2, top, left, width) {
3504
3538
  renderable.content = line2?.styledText ?? line2?.text ?? "";
3505
3539
  renderable.fg = line2?.fg ?? RIG_UI.ink2;
3506
3540
  renderable.bg = lineBackground(line2);
3507
- renderable.attributes = line2?.bold ? TextAttributes4.BOLD : line2?.dim ? TextAttributes4.DIM : 0;
3541
+ renderable.attributes = line2?.bold ? TextAttributes3.BOLD : line2?.dim ? TextAttributes3.DIM : 0;
3508
3542
  }
3509
3543
  function applyFlowTextLine(renderable, line2, width) {
3510
3544
  renderable.setRigSceneLine?.(line2);
@@ -3514,7 +3548,7 @@ function applyFlowTextLine(renderable, line2, width) {
3514
3548
  renderable.content = line2?.styledText ?? line2?.text ?? "";
3515
3549
  renderable.fg = line2?.fg ?? RIG_UI.ink2;
3516
3550
  renderable.bg = lineBackground(line2);
3517
- renderable.attributes = line2?.bold ? TextAttributes4.BOLD : line2?.dim ? TextAttributes4.DIM : 0;
3551
+ renderable.attributes = line2?.bold ? TextAttributes3.BOLD : line2?.dim ? TextAttributes3.DIM : 0;
3518
3552
  }
3519
3553
  function clearTextLines(renderables, from = 0) {
3520
3554
  for (let index = from;index < renderables.length; index += 1) {
@@ -3528,9 +3562,20 @@ function clearTextLines(renderables, from = 0) {
3528
3562
  }
3529
3563
  }
3530
3564
 
3565
+ // packages/cli/src/app-opentui/render/terminal-handoff.ts
3566
+ function resumeRendererClean(renderer) {
3567
+ try {
3568
+ renderer.pendingSuspendedTerminalSetup = true;
3569
+ } catch {}
3570
+ renderer.resume();
3571
+ try {
3572
+ renderer.requestRender?.();
3573
+ } catch {}
3574
+ }
3575
+
3531
3576
  // packages/cli/src/app-opentui/render/panels.ts
3532
- import { RGBA as RGBA5, ScrollBoxRenderable } from "@opentui/core";
3533
- var TRANSPARENT3 = RGBA5.fromInts(0, 0, 0, 0);
3577
+ import { RGBA as RGBA4, ScrollBoxRenderable } from "@opentui/core";
3578
+ var TRANSPARENT3 = RGBA4.fromInts(0, 0, 0, 0);
3534
3579
  var MAX_PANEL_LINES = 420;
3535
3580
  var PANEL_OPAQUE_ALPHA = 255;
3536
3581
  var PANEL_BORDER = hexToRgba(RIG_UI.border, 255);
@@ -3539,8 +3584,8 @@ function hexToRgba(hex, alpha) {
3539
3584
  const full = clean.length === 3 ? clean.split("").map((part) => `${part}${part}`).join("") : clean;
3540
3585
  const value = Number.parseInt(full, 16);
3541
3586
  if (!Number.isFinite(value))
3542
- return RGBA5.fromInts(14, 15, 17, alpha);
3543
- return RGBA5.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255, alpha);
3587
+ return RGBA4.fromInts(14, 15, 17, alpha);
3588
+ return RGBA4.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255, alpha);
3544
3589
  }
3545
3590
  function panelBackground(panel) {
3546
3591
  return hexToRgba(panel.backgroundColor ?? RIG_UI.panel, PANEL_OPAQUE_ALPHA);
@@ -3655,9 +3700,9 @@ function applyScrollPanels(panels, layout, scenePanels) {
3655
3700
  }
3656
3701
 
3657
3702
  // packages/cli/src/app-opentui/render/type-bar.ts
3658
- import { BoxRenderable, InputRenderable, InputRenderableEvents, RGBA as RGBA6, StyledText as StyledText3, TextRenderable as TextRenderable2 } from "@opentui/core";
3659
- var TYPEBAR_BG = RGBA6.fromInts(20, 25, 14, 224);
3660
- var TYPEBAR_BORDER = RGBA6.fromInts(204, 255, 77, 92);
3703
+ import { BoxRenderable, InputRenderable, InputRenderableEvents, RGBA as RGBA5, StyledText as StyledText2, TextRenderable as TextRenderable2 } from "@opentui/core";
3704
+ var TYPEBAR_BG = RGBA5.fromInts(20, 25, 14, 224);
3705
+ var TYPEBAR_BORDER = RGBA5.fromInts(204, 255, 77, 92);
3661
3706
  function createTypeBar(renderer) {
3662
3707
  const background = new BoxRenderable(renderer, {
3663
3708
  id: "typebar-card",
@@ -3805,7 +3850,7 @@ function formatFooter(footer, width) {
3805
3850
  chunks.push(cell.style(text));
3806
3851
  used += visibleWidth(text);
3807
3852
  });
3808
- return new StyledText3(chunks);
3853
+ return new StyledText2(chunks);
3809
3854
  }
3810
3855
 
3811
3856
  // packages/cli/src/app-opentui/render/native-host.ts
@@ -3813,7 +3858,7 @@ import {
3813
3858
  BoxRenderable as BoxRenderable2,
3814
3859
  CodeRenderable,
3815
3860
  DiffRenderable,
3816
- RGBA as RGBA7,
3861
+ RGBA as RGBA6,
3817
3862
  ScrollBoxRenderable as ScrollBoxRenderable2,
3818
3863
  SyntaxStyle,
3819
3864
  TextRenderable as TextRenderable3,
@@ -3824,19 +3869,19 @@ function rigSyntaxStyle() {
3824
3869
  if (syntaxStyle)
3825
3870
  return syntaxStyle;
3826
3871
  syntaxStyle = SyntaxStyle.fromStyles({
3827
- keyword: { fg: RGBA7.fromHex(RIG_UI.magenta), bold: true },
3828
- string: { fg: RGBA7.fromHex(RIG_UI.lime) },
3829
- number: { fg: RGBA7.fromHex(RIG_UI.cyan) },
3830
- comment: { fg: RGBA7.fromHex(RIG_UI.ink4), italic: true },
3831
- function: { fg: RGBA7.fromHex(RIG_UI.cyan) },
3832
- type: { fg: RGBA7.fromHex(RIG_UI.limeDim) },
3833
- constant: { fg: RGBA7.fromHex(RIG_UI.yellow) },
3834
- default: { fg: RGBA7.fromHex(RIG_UI.ink2) }
3872
+ keyword: { fg: RGBA6.fromHex(RIG_UI.magenta), bold: true },
3873
+ string: { fg: RGBA6.fromHex(RIG_UI.lime) },
3874
+ number: { fg: RGBA6.fromHex(RIG_UI.cyan) },
3875
+ comment: { fg: RGBA6.fromHex(RIG_UI.ink4), italic: true },
3876
+ function: { fg: RGBA6.fromHex(RIG_UI.cyan) },
3877
+ type: { fg: RGBA6.fromHex(RIG_UI.limeDim) },
3878
+ constant: { fg: RGBA6.fromHex(RIG_UI.yellow) },
3879
+ default: { fg: RGBA6.fromHex(RIG_UI.ink2) }
3835
3880
  });
3836
3881
  return syntaxStyle;
3837
3882
  }
3838
3883
  function tableContent(rows) {
3839
- return rows.map((row, rowIndex) => row.map((cell) => [{ __isChunk: true, text: cell, fg: RGBA7.fromHex(rowIndex === 0 ? RIG_UI.ink3 : RIG_UI.ink2) }]));
3884
+ return rows.map((row, rowIndex) => row.map((cell) => [{ __isChunk: true, text: cell, fg: RGBA6.fromHex(rowIndex === 0 ? RIG_UI.ink3 : RIG_UI.ink2) }]));
3840
3885
  }
3841
3886
  function createNativeHost(renderer) {
3842
3887
  try {
@@ -3977,6 +4022,48 @@ function renderAsciiPreloaderFrame(scene, layout, tick) {
3977
4022
  };
3978
4023
  }
3979
4024
 
4025
+ // packages/cli/src/app-opentui/remote-link.ts
4026
+ var REPAIRABLE_REMOTE_LINK_STATUSES = new Set([
4027
+ "auth_required",
4028
+ "project_not_registered",
4029
+ "no_server_checkout",
4030
+ "invalid_root",
4031
+ "needs_prepare",
4032
+ "error"
4033
+ ]);
4034
+ function remoteProjectLinkError(message) {
4035
+ return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(message ?? "");
4036
+ }
4037
+ function serverRecordForRemoteLink(state) {
4038
+ const server = state.data.server;
4039
+ return server && typeof server === "object" && !Array.isArray(server) ? server : null;
4040
+ }
4041
+ function remoteProjectLinkState(state) {
4042
+ const serverRecord = serverRecordForRemoteLink(state);
4043
+ if (!serverRecord || serverRecord.kind !== "remote")
4044
+ return null;
4045
+ const link = serverRecord.remoteProjectLink;
4046
+ if (link && typeof link === "object" && !Array.isArray(link))
4047
+ return link;
4048
+ const direct = state.data.remoteProjectLink;
4049
+ if (direct && typeof direct === "object" && !Array.isArray(direct))
4050
+ return direct;
4051
+ return null;
4052
+ }
4053
+ function shouldOfferRemoteLinkRepair(state, message) {
4054
+ const link = remoteProjectLinkState(state);
4055
+ if (link) {
4056
+ if (link.ok === true)
4057
+ return false;
4058
+ const status = link.status ?? "";
4059
+ return REPAIRABLE_REMOTE_LINK_STATUSES.has(status);
4060
+ }
4061
+ const serverRecord = serverRecordForRemoteLink(state);
4062
+ if (serverRecord && serverRecord.kind !== "remote")
4063
+ return false;
4064
+ return remoteProjectLinkError(message ?? state.error?.message);
4065
+ }
4066
+
3980
4067
  // packages/cli/src/app-opentui/selectable.ts
3981
4068
  function selectableDeckRow(deck, item) {
3982
4069
  return { ...deckRow({ ...deck, activateOnClick: true }), selectable: item };
@@ -3986,13 +4073,17 @@ function selectableDeckRow(deck, item) {
3986
4073
  var ERROR_ACTIONS = [
3987
4074
  { detail: "return to dashboard", item: { id: "main", label: "main", intent: { scene: "main", argv: [], action: { kind: "refresh", label: "Back to dashboard" } }, message: "back to dashboard" } },
3988
4075
  { detail: "run diagnostics", item: { id: "doctor", label: "doctor", intent: { scene: "doctor", argv: ["doctor"], action: { kind: "doctor-run", label: "Run doctor" } }, message: "run diagnostics" } },
3989
- { detail: "open server controls", item: { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Open server controls" } }, message: "open server controls" } },
3990
- { detail: "repair project/server/auth link", item: { id: "repair", label: "repair", intent: { scene: "command", argv: ["init", "--repair"], action: { kind: "command-run", label: "Repair project link" } }, message: "repair project link" } }
4076
+ { detail: "open server controls", item: { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Open server controls" } }, message: "open server controls" } }
3991
4077
  ];
4078
+ var ERROR_REPAIR_LINK_ACTION = { detail: "backfill or prepare selected remote project-root link", item: { id: "repair-link", label: "repair link", intent: { scene: "server", argv: ["server", "repair-link"], action: { kind: "remote-link-repair", label: "Repair remote link", payload: { returnScene: "server" } } }, message: "repair remote project link" } };
4079
+ function errorActions(state) {
4080
+ return shouldOfferRemoteLinkRepair(state, state.error?.message) ? [...ERROR_ACTIONS, ERROR_REPAIR_LINK_ACTION] : ERROR_ACTIONS;
4081
+ }
3992
4082
  function renderErrorScene(state) {
3993
4083
  const message = state.error?.message ?? "Unknown app error";
3994
4084
  const hint = state.error?.hint ?? "Use the actions below to recover.";
3995
- const selected = Math.max(0, Math.min(3, state.selection.index));
4085
+ const actions = errorActions(state);
4086
+ const selected = Math.max(0, Math.min(actions.length - 1, state.selection.index));
3996
4087
  return makeSceneFrame({
3997
4088
  scene: "error",
3998
4089
  title: "Error",
@@ -4010,7 +4101,7 @@ function renderErrorScene(state) {
4010
4101
  ...hint ? [line(hint, { fg: RIG_UI.yellow })] : [],
4011
4102
  line("", { fg: RIG_UI.ink3 }),
4012
4103
  line("ACTIONS", { fg: RIG_UI.ink3, bold: true }),
4013
- ...ERROR_ACTIONS.map(({ detail, item }, index) => selectableDeckRow({ label: item.label, detail, index, active: selected === index }, item))
4104
+ ...actions.map(({ detail, item }, index) => selectableDeckRow({ label: item.label, detail, index, active: selected === index }, item))
4014
4105
  ],
4015
4106
  backgroundColor: RIG_UI.panel,
4016
4107
  backgroundAlpha: 184,
@@ -4138,7 +4229,7 @@ function renderHelpScene(state, layout) {
4138
4229
 
4139
4230
  // packages/cli/src/app-opentui/scenes/main.ts
4140
4231
  var CONFIGURED_MENU = [
4141
- ["init", "setup, reconfigure, repair project state", { id: "init", label: "init", intent: { scene: "command", argv: ["init"], action: { kind: "command-run", label: "Run init" } }, message: "run setup/reconfigure flow" }],
4232
+ ["init", "guided setup, reconfigure, repair project state", { id: "init", label: "init", intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Open init" } }, message: "open native init flow" }],
4142
4233
  ["server", "local/remote target, auth, linkage", { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Checking server" } }, message: "check selected server" }],
4143
4234
  ["github", "auth, selected repo, stored token", { id: "github", label: "github", intent: { scene: "server", argv: ["github", "auth", "status"], action: { kind: "refresh", label: "Checking GitHub auth" } }, message: "check GitHub auth" }],
4144
4235
  ["tasks", "browse, filter, dispatch, attach active work", { id: "tasks", label: "tasks", intent: { scene: "tasks", argv: ["tasks"], action: { kind: "refresh", label: "Opening tasks" } }, message: "selected tasks" }],
@@ -4157,10 +4248,10 @@ var CONFIGURED_MENU = [
4157
4248
  ["help", "all actions, shortcuts, mouse controls", { id: "help", label: "help", intent: { scene: "help", argv: ["help"], action: { kind: "none", label: "Opening help" } }, message: "selected help" }]
4158
4249
  ];
4159
4250
  var ONBOARD_PRIMARY = {
4160
- id: "onboard-setup",
4161
- label: "Start guided setup",
4162
- intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Setup" } },
4163
- message: "open the guided setup checklist"
4251
+ id: "onboard-init",
4252
+ label: "Start guided init",
4253
+ intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Init" } },
4254
+ message: "open the native init checklist"
4164
4255
  };
4165
4256
  var ONBOARD_SECONDARY = [
4166
4257
  ["server", "select a local or remote target", { id: "server", label: "server", intent: { scene: "server", argv: ["server", "status"], action: { kind: "refresh", label: "Checking server" } }, message: "check selected server" }],
@@ -4223,7 +4314,7 @@ function configuredMenuRows(selectedIndex) {
4223
4314
  }));
4224
4315
  }
4225
4316
  function onboardingRows(selectedIndex) {
4226
- const primary = selectableDeckRow({ label: "setup", detail: "Start guided setup \u2014 recommended", active: selectedIndex === 0 }, ONBOARD_PRIMARY);
4317
+ const primary = selectableDeckRow({ label: "init", detail: "Start guided init \u2014 recommended", active: selectedIndex === 0 }, ONBOARD_PRIMARY);
4227
4318
  const secondary = ONBOARD_SECONDARY.map(([label, detail, item], index) => ({
4228
4319
  ...deckRow({ label, detail, index: index + 1, active: selectedIndex === index + 1, activateOnClick: true }),
4229
4320
  selectable: item
@@ -4287,7 +4378,7 @@ function renderMainScene(state, layout) {
4287
4378
  statusLine(state)
4288
4379
  ] : [
4289
4380
  line("WELCOME", { fg: RIG_UI.ink, bold: true }),
4290
- line("This project isn't set up yet. One guided flow gets you running.", { fg: RIG_UI.ink2 }),
4381
+ line("This project isn't initialized yet. One native init flow gets you running.", { fg: RIG_UI.ink2 }),
4291
4382
  blank(),
4292
4383
  line("GET STARTED", { fg: RIG_UI.ink, bold: true }),
4293
4384
  ...onboardingRows(actionSelected),
@@ -4322,11 +4413,17 @@ function renderMainScene(state, layout) {
4322
4413
  });
4323
4414
  }
4324
4415
 
4416
+ // packages/cli/src/app-opentui/pi-pty-host.ts
4417
+ function getActivePiHost() {
4418
+ return null;
4419
+ }
4420
+ function stopActivePiHost(_reason) {}
4421
+
4325
4422
  // packages/cli/src/app-opentui/runtime.ts
4326
4423
  var MAX_SCENE_LINES = 200;
4327
4424
  var MAX_SCENE_PANELS = 5;
4328
4425
  var ANIMATION_SLOWDOWN = 1;
4329
- var PRELOADER_BACKDROP = RGBA8.fromHex(RIG_UI.bg);
4426
+ var PRELOADER_BACKDROP = RGBA7.fromHex(RIG_UI.bg);
4330
4427
  function inboxPendingCount(state) {
4331
4428
  const inbox = state.data.inbox;
4332
4429
  if (!inbox || typeof inbox !== "object" || Array.isArray(inbox))
@@ -4342,7 +4439,7 @@ var PRIMARY_NAV = [
4342
4439
  { id: "tasks", label: "Tasks", scene: "tasks", argv: ["tasks"], enterLabel: "Tasks", member: ["tasks"] },
4343
4440
  { id: "inbox", label: "Inbox", scene: "inbox", argv: ["inbox"], enterLabel: "Inbox", member: ["inbox"], badge: inboxPendingCount },
4344
4441
  { id: "stats", label: "Stats", scene: "family", argv: ["stats"], enterLabel: "Stats", member: ["family"] },
4345
- { id: "setup", label: "Setup", scene: "init", argv: ["init"], enterLabel: "Setup", member: ["init", "doctor", "server", "pi", "plugin", "repo", "workspace"] },
4442
+ { id: "init", label: "Init", scene: "init", argv: ["init"], enterLabel: "Init", member: ["init", "doctor", "server", "pi", "plugin", "repo", "workspace"] },
4346
4443
  { id: "help", label: "Help", scene: "help", argv: ["help"], enterLabel: "Help", member: ["help"] }
4347
4444
  ];
4348
4445
  function navSectionIntent(section) {
@@ -4382,7 +4479,7 @@ function entryIntentForScene(scene) {
4382
4479
  case "doctor":
4383
4480
  return { scene, argv: ["doctor"], action: { kind: "doctor-run", label: "Doctor" } };
4384
4481
  case "init":
4385
- return { scene, argv: ["init"], action: { kind: "refresh", label: "Setup" } };
4482
+ return { scene, argv: ["init"], action: { kind: "refresh", label: "Init" } };
4386
4483
  case "run-detail":
4387
4484
  return { scene, argv: ["run", "status"], action: { kind: "refresh", label: "Run" } };
4388
4485
  case "pi":
@@ -4498,7 +4595,7 @@ function sceneSectionLabel(scene) {
4498
4595
  handoff: "pi console",
4499
4596
  server: "server",
4500
4597
  doctor: "doctor",
4501
- init: "setup",
4598
+ init: "init",
4502
4599
  pi: "pi",
4503
4600
  plugin: "plugins",
4504
4601
  repo: "repo",
@@ -4531,7 +4628,7 @@ function buildNavStrip(state) {
4531
4628
  chunks.push(otuiBold(styles.yellow(String(badgeCount))));
4532
4629
  }
4533
4630
  });
4534
- return new StyledText4(chunks);
4631
+ return new StyledText3(chunks);
4535
4632
  }
4536
4633
  function requestRender(renderer) {
4537
4634
  renderer.requestRender?.();
@@ -4729,7 +4826,8 @@ async function launchRigOpenTuiApp(options) {
4729
4826
  },
4730
4827
  suspend: () => renderer?.suspend(),
4731
4828
  resume: () => {
4732
- renderer?.resume();
4829
+ if (renderer)
4830
+ resumeRendererClean(renderer);
4733
4831
  renderApp();
4734
4832
  },
4735
4833
  destroy: () => renderer?.destroy()
@@ -4957,7 +5055,7 @@ async function launchRigOpenTuiApp(options) {
4957
5055
  }
4958
5056
  for (const adapter of options.adapters ?? [])
4959
5057
  await adapter.start?.(runtime);
4960
- liveEvents = await connectRigServerEvents(options.projectRoot, {
5058
+ connectRigServerEvents(options.projectRoot, {
4961
5059
  onSnapshotInvalidated: () => refreshCurrentDataScene(),
4962
5060
  onRunLogAppended: () => {
4963
5061
  const scene = store.getState().scene;
@@ -4965,11 +5063,17 @@ async function launchRigOpenTuiApp(options) {
4965
5063
  refreshCurrentDataScene();
4966
5064
  },
4967
5065
  onStatus: (status) => store.patch({ footer: { live: liveLinkLabel(status) } })
4968
- }).catch(() => null);
4969
- if (!liveEvents)
4970
- store.patch({ footer: { live: liveLinkLabel("disconnected") } });
4971
- if (liveEvents)
5066
+ }).then((subscription) => {
5067
+ if (destroyed) {
5068
+ subscription.close();
5069
+ return;
5070
+ }
5071
+ liveEvents = subscription;
4972
5072
  resources.add(() => liveEvents?.close());
5073
+ }).catch(() => {
5074
+ if (!destroyed)
5075
+ store.patch({ footer: { live: liveLinkLabel("disconnected") } });
5076
+ });
4973
5077
  await runtime.runIntent(store.getState().intent);
4974
5078
  } catch (error) {
4975
5079
  const normalized = normalizeError(error);