@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
@@ -2,7 +2,7 @@
2
2
  // packages/cli/src/app-opentui/runtime.ts
3
3
  import { existsSync as existsSync3 } from "fs";
4
4
  import { resolve as resolve3 } from "path";
5
- import { BoxRenderable as BoxRenderable3, RGBA as RGBA8, StyledText as StyledText4, TextRenderable as TextRenderable4, createCliRenderer } from "@opentui/core";
5
+ import { BoxRenderable as BoxRenderable3, RGBA as RGBA7, StyledText as StyledText3, TextRenderable as TextRenderable4, createCliRenderer } from "@opentui/core";
6
6
 
7
7
  // packages/cli/src/app-opentui/events.ts
8
8
  function createAppEventBus() {
@@ -351,12 +351,13 @@ var PRIMARY_GROUPS = [
351
351
  {
352
352
  name: "server",
353
353
  summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
354
- usage: ["rig server <status|list|add|use|start> [options]"],
354
+ usage: ["rig server <status|list|add|use|repair-link|start> [options]"],
355
355
  commands: [
356
- { command: "status", description: "Show the selected server for this repo.", primary: true },
356
+ { command: "status", description: "Show the selected server and remote project-root link for this repo.", primary: true },
357
357
  { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
358
358
  { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
359
359
  { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
360
+ { command: "repair-link [--prepare|--backfill-only] [--repo owner/repo]", description: "Backfill or prepare the selected remote's server-host checkout link.", primary: true },
360
361
  { command: "list", description: "List saved local/remote server aliases.", primary: true },
361
362
  { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
362
363
  ],
@@ -364,6 +365,7 @@ var PRIMARY_GROUPS = [
364
365
  "rig server status",
365
366
  "rig server add prod https://where.rig-does.work",
366
367
  "rig server use prod",
368
+ "rig server repair-link --repo owner/repo",
367
369
  "rig server use local",
368
370
  "rig server start --port 3773"
369
371
  ],
@@ -1056,16 +1058,31 @@ function taskViewIntent(argv, command = "", rest = [], raw) {
1056
1058
  const { payload, label } = taskViewPayload(command, rest);
1057
1059
  return intent("tasks", argv, "refresh", payload, label, raw);
1058
1060
  }
1059
- function routeServer(argv, command, raw, checkingLabel) {
1060
- if (!command || command === "status") {
1061
+ function routeServer(argv, command, rest, raw, checkingLabel) {
1062
+ if (!command || command === "status" || command === "list") {
1061
1063
  return intent("server", argv, "refresh", undefined, command ? checkingLabel : "Loading server", raw);
1062
1064
  }
1065
+ if (command === "use") {
1066
+ const alias = firstNonOption(rest);
1067
+ if (alias === "local")
1068
+ return intent("server", argv, "server-use-local", undefined, "Use local server", raw);
1069
+ if (alias)
1070
+ return intent("server", argv, "server-use-remote", { alias }, `Use ${alias}`, raw);
1071
+ return intent("server", argv, "refresh", undefined, "Select a remote alias in Server", raw);
1072
+ }
1073
+ if (command === "add")
1074
+ return intent("server", argv, "server-add-remote", { argv: [...argv] }, "Add remote server", raw);
1075
+ if (command === "repair-link")
1076
+ return intent("server", argv, "remote-link-repair", undefined, "Repair remote link", raw);
1063
1077
  return commandRunIntent(argv, raw);
1064
1078
  }
1065
1079
  function routeGithub(argv, command, rest, raw) {
1066
1080
  if (command === "auth" && (rest[0]?.toLowerCase() ?? "status") === "status" && rest.length <= 1) {
1067
1081
  return intent("server", argv, "refresh", undefined, "Checking GitHub auth", raw);
1068
1082
  }
1083
+ if (command === "auth" && rest[0]?.toLowerCase() === "import-gh" && rest.length <= 1) {
1084
+ return intent("server", argv, "github-auth-import", undefined, "Import GitHub auth", raw);
1085
+ }
1069
1086
  return commandRunIntent(argv, raw);
1070
1087
  }
1071
1088
  function routeDoctor(argv, command, raw) {
@@ -1114,11 +1131,16 @@ function intentFromArgv(argv) {
1114
1131
  return commandRunIntent(argv);
1115
1132
  }
1116
1133
  if (normalizedGroup === "server")
1117
- return routeServer(argv, normalizedCommand, undefined, "Checking server");
1134
+ return routeServer(argv, normalizedCommand, rest, undefined, "Checking server");
1118
1135
  if (normalizedGroup === "github")
1119
1136
  return routeGithub(argv, normalizedCommand, rest);
1120
- if (normalizedGroup === "init")
1121
- return commandRunIntent(argv);
1137
+ if (normalizedGroup === "init") {
1138
+ if (!normalizedCommand)
1139
+ return intent("init", argv, "refresh", undefined, "Open init");
1140
+ if (rest.includes("--yes") || normalizedCommand === "--yes")
1141
+ return intent("init", argv, "init-start", undefined, "Run init");
1142
+ return intent("init", argv, "refresh", undefined, "Open init");
1143
+ }
1122
1144
  if (normalizedGroup === "doctor")
1123
1145
  return routeDoctor(argv, normalizedCommand);
1124
1146
  if (normalizedGroup === "inbox")
@@ -1181,12 +1203,17 @@ function intentFromTypeBar(value) {
1181
1203
  return commandRunIntent(parts, value);
1182
1204
  return intent("tasks", parts, "refresh", undefined, "Select a task, then press Enter; or use run next", value);
1183
1205
  }
1184
- if (first === "init")
1185
- return commandRunIntent(parts, value);
1206
+ if (first === "init") {
1207
+ if (!second)
1208
+ return intent("init", parts, "refresh", undefined, "Open init", value);
1209
+ if (parts.includes("--yes"))
1210
+ return intent("init", parts, "init-start", undefined, "Run init", value);
1211
+ return intent("init", parts, "refresh", undefined, "Open init", value);
1212
+ }
1186
1213
  if (first === "doctor")
1187
1214
  return routeDoctor(parts, second, value);
1188
1215
  if (first === "server")
1189
- return routeServer(parts, second, value, "Loading server");
1216
+ return routeServer(parts, second, rest, value, "Loading server");
1190
1217
  if (first === "github")
1191
1218
  return routeGithub(parts, second, rest, value);
1192
1219
  if (first === "inbox")
@@ -1204,397 +1231,6 @@ function intentFromTypeBar(value) {
1204
1231
  return intentFromArgv(parts);
1205
1232
  }
1206
1233
 
1207
- // packages/cli/src/app-opentui/pi-pty-host.ts
1208
- import { fileURLToPath as fileURLToPath2 } from "url";
1209
- import { basename as basename2 } from "path";
1210
- import { RGBA, StyledText, TextAttributes } from "@opentui/core";
1211
- import { Terminal as XtermTerminal2 } from "@xterm/headless";
1212
- var MIN_COLS2 = 40;
1213
- var MIN_ROWS2 = 12;
1214
- var MAX_ROWS2 = 300;
1215
- var MAX_SNAPSHOT_LINES2 = 360;
1216
- var STYLED_SNAPSHOT_MARGIN = 6;
1217
- var SNAPSHOT_DELAY_MS2 = 120;
1218
- var fallbackChildScriptPath = fileURLToPath2(new URL("./pi-host-child.ts", import.meta.url));
1219
- var activeHost2 = null;
1220
- function clampCols2(cols) {
1221
- return Math.max(MIN_COLS2, Math.trunc(cols || 100));
1222
- }
1223
- function clampRows2(rows) {
1224
- return Math.max(MIN_ROWS2, Math.min(MAX_ROWS2, Math.trunc(rows || 35)));
1225
- }
1226
- var XTERM_COLOR_MODE_INDEXED_16 = 16777216;
1227
- var XTERM_COLOR_MODE_INDEXED_256 = 33554432;
1228
- var XTERM_COLOR_MODE_RGB = 50331648;
1229
- function rgbaFromXtermColor(mode, value) {
1230
- if (mode === 1 || mode === 2 || mode === XTERM_COLOR_MODE_INDEXED_16 || mode === XTERM_COLOR_MODE_INDEXED_256) {
1231
- return RGBA.fromIndex(value);
1232
- }
1233
- if (mode === 3 || mode === XTERM_COLOR_MODE_RGB) {
1234
- return RGBA.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255);
1235
- }
1236
- return;
1237
- }
1238
- function textAttributesFromCell(cell) {
1239
- let attributes = TextAttributes.NONE;
1240
- if (cell.isBold())
1241
- attributes |= TextAttributes.BOLD;
1242
- if (cell.isDim())
1243
- attributes |= TextAttributes.DIM;
1244
- if (cell.isItalic())
1245
- attributes |= TextAttributes.ITALIC;
1246
- if (cell.isUnderline())
1247
- attributes |= TextAttributes.UNDERLINE;
1248
- if (cell.isBlink())
1249
- attributes |= TextAttributes.BLINK;
1250
- if (cell.isInverse())
1251
- attributes |= TextAttributes.INVERSE;
1252
- if (cell.isInvisible())
1253
- attributes |= TextAttributes.HIDDEN;
1254
- if (cell.isStrikethrough())
1255
- attributes |= TextAttributes.STRIKETHROUGH;
1256
- return attributes;
1257
- }
1258
- function sameRgba(a, b) {
1259
- if (!a && !b)
1260
- return true;
1261
- return Boolean(a && b && a.equals(b));
1262
- }
1263
- function sameStyle(a, b) {
1264
- return sameRgba(a.fg, b.fg) && sameRgba(a.bg, b.bg) && (a.attributes ?? 0) === (b.attributes ?? 0);
1265
- }
1266
- function styleFromCell(cell) {
1267
- return {
1268
- fg: rgbaFromXtermColor(cell.getFgColorMode(), cell.getFgColor()),
1269
- bg: rgbaFromXtermColor(cell.getBgColorMode(), cell.getBgColor()),
1270
- attributes: textAttributesFromCell(cell)
1271
- };
1272
- }
1273
- function lineToStyledText(line, cols) {
1274
- if (!line)
1275
- return new StyledText([{ __isChunk: true, text: "" }]);
1276
- const chunks = [];
1277
- let run = "";
1278
- let runStyle = null;
1279
- const flush = () => {
1280
- if (!run)
1281
- return;
1282
- chunks.push({
1283
- __isChunk: true,
1284
- text: run,
1285
- ...runStyle?.fg ? { fg: runStyle.fg } : {},
1286
- ...runStyle?.bg ? { bg: runStyle.bg } : {},
1287
- ...(runStyle?.attributes ?? 0) !== 0 ? { attributes: runStyle.attributes } : {}
1288
- });
1289
- run = "";
1290
- };
1291
- for (let index = 0;index < cols; index += 1) {
1292
- const cell = line.getCell(index);
1293
- if (!cell) {
1294
- if (runStyle !== null)
1295
- flush();
1296
- runStyle = null;
1297
- run += " ";
1298
- continue;
1299
- }
1300
- if (cell.getWidth() === 0)
1301
- continue;
1302
- const style = styleFromCell(cell);
1303
- if (!runStyle || !sameStyle(runStyle, style)) {
1304
- flush();
1305
- runStyle = style;
1306
- }
1307
- run += cell.getChars() || " ";
1308
- }
1309
- flush();
1310
- return new StyledText(chunks.length > 0 ? chunks : [{ __isChunk: true, text: "" }]);
1311
- }
1312
- function childCommandPrefix2() {
1313
- const execName = basename2(process.execPath).toLowerCase();
1314
- const currentEntry = process.argv[1];
1315
- if (execName === "bun" || execName === "bun.exe") {
1316
- return currentEntry ? [process.execPath, currentEntry, "__opentui-pi-host"] : [process.execPath, fallbackChildScriptPath];
1317
- }
1318
- return [process.execPath, "__opentui-pi-host"];
1319
- }
1320
- function withEnv2(base) {
1321
- const env = {};
1322
- for (const [key, value] of Object.entries(base ?? process.env)) {
1323
- if (key === "RIG_PLAIN" || key === "RIG_CLI_PLAIN_HELP" || key === "NO_COLOR")
1324
- continue;
1325
- if (typeof value === "string")
1326
- env[key] = value;
1327
- }
1328
- return {
1329
- ...env,
1330
- TERM: "xterm-256color",
1331
- COLORTERM: "truecolor",
1332
- FORCE_COLOR: env.FORCE_COLOR ?? "1",
1333
- RIG_OPENTUI_PI_HOST: "1"
1334
- };
1335
- }
1336
- function getActivePiHost() {
1337
- return activeHost2 && !activeHost2.disposed ? activeHost2 : null;
1338
- }
1339
- function stopActivePiHost(reason = "detach") {
1340
- activeHost2?.dispose(reason);
1341
- activeHost2 = null;
1342
- }
1343
-
1344
- class PiPtyHost {
1345
- runId;
1346
- projectRoot;
1347
- onSnapshot;
1348
- onExit;
1349
- onError;
1350
- terminal;
1351
- disposables = [];
1352
- decoder = new TextDecoder("utf-8");
1353
- proc = null;
1354
- pty = null;
1355
- status = "starting";
1356
- cols;
1357
- rows;
1358
- message = "starting bundled Pi";
1359
- lastResizeError = null;
1360
- exitCode;
1361
- signal;
1362
- notifyTimer = null;
1363
- lastStreamKey = "";
1364
- _disposed = false;
1365
- constructor(options) {
1366
- this.runId = options.runId;
1367
- this.projectRoot = options.projectRoot;
1368
- this.cols = clampCols2(options.cols);
1369
- this.rows = clampRows2(options.rows);
1370
- this.onSnapshot = options.onSnapshot;
1371
- this.onExit = options.onExit;
1372
- this.onError = options.onError;
1373
- this.terminal = new XtermTerminal2({
1374
- allowProposedApi: true,
1375
- cols: this.cols,
1376
- rows: this.rows,
1377
- scrollback: 1000
1378
- });
1379
- this.registerTerminalResponders();
1380
- this.disposables.push(this.terminal.onWriteParsed(() => {
1381
- if (this._disposed)
1382
- return;
1383
- const snapshot = this.createSnapshot();
1384
- const key = snapshot.lines.join(`
1385
- `);
1386
- if (key === this.lastStreamKey)
1387
- return;
1388
- this.lastStreamKey = key;
1389
- this.onSnapshot?.(snapshot);
1390
- }));
1391
- }
1392
- get disposed() {
1393
- return this._disposed;
1394
- }
1395
- get snapshot() {
1396
- return this.createSnapshot();
1397
- }
1398
- async start() {
1399
- if (this._disposed)
1400
- throw new Error("Pi PTY host is disposed.");
1401
- if (typeof Bun.Terminal !== "function") {
1402
- throw new Error("Bun native PTY is unavailable in this runtime. Pi host requires Bun.Terminal.");
1403
- }
1404
- const spawnOptions = {
1405
- cwd: this.projectRoot,
1406
- env: withEnv2(process.env),
1407
- terminal: {
1408
- cols: this.cols,
1409
- rows: this.rows,
1410
- name: "xterm-256color",
1411
- data: (_terminal, data) => this.handlePtyData(data)
1412
- }
1413
- };
1414
- const proc = Bun.spawn([
1415
- ...childCommandPrefix2(),
1416
- "--run-id",
1417
- this.runId,
1418
- "--project-root",
1419
- this.projectRoot
1420
- ], spawnOptions);
1421
- if (!proc.terminal)
1422
- throw new Error("Bun did not attach a terminal to the bundled Pi child process.");
1423
- this.proc = proc;
1424
- this.pty = proc.terminal;
1425
- this.status = "running";
1426
- this.message = "bundled Pi running inside this app";
1427
- this.emitSnapshotSoon(0);
1428
- proc.exited.then((exitCode) => {
1429
- if (this._disposed)
1430
- return;
1431
- this.status = exitCode === 0 ? "exited" : "failed";
1432
- this.exitCode = exitCode;
1433
- this.signal = null;
1434
- this.message = exitCode === 0 ? "bundled Pi exited" : `bundled Pi exited with code ${exitCode}`;
1435
- const snapshot = this.createSnapshot();
1436
- this.onSnapshot?.(snapshot);
1437
- this.onExit?.(snapshot);
1438
- if (activeHost2 === this)
1439
- activeHost2 = null;
1440
- this.dispose("exit", { kill: false, notify: false });
1441
- }).catch((error) => {
1442
- if (this._disposed)
1443
- return;
1444
- this.status = "failed";
1445
- this.message = error instanceof Error ? error.message : String(error);
1446
- const snapshot = this.createSnapshot();
1447
- this.onSnapshot?.(snapshot);
1448
- this.onError?.(error, snapshot);
1449
- if (activeHost2 === this)
1450
- activeHost2 = null;
1451
- this.dispose("error", { kill: false, notify: false });
1452
- });
1453
- }
1454
- write(data) {
1455
- if (this._disposed || !this.pty)
1456
- return;
1457
- try {
1458
- this.pty.write(data);
1459
- } catch (error) {
1460
- this.status = "failed";
1461
- this.message = error instanceof Error ? error.message : String(error);
1462
- const snapshot = this.createSnapshot();
1463
- this.onSnapshot?.(snapshot);
1464
- this.onError?.(error, snapshot);
1465
- }
1466
- }
1467
- resize(cols, rows) {
1468
- const nextCols = clampCols2(cols);
1469
- const nextRows = clampRows2(rows);
1470
- if (nextCols === this.cols && nextRows === this.rows)
1471
- return;
1472
- this.cols = nextCols;
1473
- this.rows = nextRows;
1474
- this.terminal.resize(nextCols, nextRows);
1475
- try {
1476
- this.pty?.resize(nextCols, nextRows);
1477
- this.lastResizeError = null;
1478
- } catch (error) {
1479
- this.lastResizeError = error instanceof Error ? error.message : String(error);
1480
- }
1481
- this.emitSnapshotSoon(0);
1482
- }
1483
- detach() {
1484
- this.dispose("detach");
1485
- return this.createSnapshot("detached from bundled Pi");
1486
- }
1487
- dispose(reason = "dispose", options = {}) {
1488
- if (this._disposed)
1489
- return;
1490
- this._disposed = true;
1491
- if (this.notifyTimer)
1492
- clearTimeout(this.notifyTimer);
1493
- this.notifyTimer = null;
1494
- for (const disposable of this.disposables.splice(0)) {
1495
- try {
1496
- disposable.dispose();
1497
- } catch {}
1498
- }
1499
- if (options.kill !== false) {
1500
- try {
1501
- this.proc?.kill("SIGTERM");
1502
- } catch {}
1503
- }
1504
- try {
1505
- this.pty?.close();
1506
- } catch {}
1507
- try {
1508
- this.terminal.dispose();
1509
- } catch {}
1510
- if (activeHost2 === this)
1511
- activeHost2 = null;
1512
- if (options.notify) {
1513
- this.message = reason;
1514
- this.onSnapshot?.(this.createSnapshot(reason));
1515
- }
1516
- }
1517
- handlePtyData(data) {
1518
- if (this._disposed)
1519
- return;
1520
- const text = this.decoder.decode(data, { stream: true });
1521
- this.respondToRawTerminalQueries(text);
1522
- this.terminal.write(data);
1523
- }
1524
- emitSnapshotSoon(delayMs = SNAPSHOT_DELAY_MS2) {
1525
- if (this._disposed || this.notifyTimer)
1526
- return;
1527
- this.notifyTimer = setTimeout(() => {
1528
- this.notifyTimer = null;
1529
- if (this._disposed)
1530
- return;
1531
- this.onSnapshot?.(this.createSnapshot());
1532
- }, delayMs);
1533
- }
1534
- createSnapshot(message = this.message) {
1535
- const buffer = this.terminal.buffer.active;
1536
- const end = buffer.length;
1537
- const start = Math.max(0, end - MAX_SNAPSHOT_LINES2);
1538
- const styledStart = Math.max(start, end - this.rows - STYLED_SNAPSHOT_MARGIN);
1539
- const lines = [];
1540
- const styledLines = [];
1541
- for (let row = start;row < end; row += 1) {
1542
- const line = buffer.getLine(row);
1543
- lines.push((line?.translateToString(false) ?? "").slice(0, this.cols));
1544
- if (row >= styledStart)
1545
- styledLines[lines.length - 1] = lineToStyledText(line, this.cols);
1546
- }
1547
- while (lines.length < this.rows) {
1548
- lines.push("");
1549
- styledLines[lines.length - 1] = new StyledText([{ __isChunk: true, text: "" }]);
1550
- }
1551
- const resolvedMessage = this.lastResizeError ? `resize degraded: ${this.lastResizeError}` : message;
1552
- return {
1553
- runId: this.runId,
1554
- status: this.status,
1555
- cols: this.cols,
1556
- rows: this.rows,
1557
- lines,
1558
- styledLines,
1559
- message: resolvedMessage,
1560
- ...this.lastResizeError ? { resizeError: this.lastResizeError } : {},
1561
- ...this.exitCode !== undefined ? { exitCode: this.exitCode } : {},
1562
- ...this.signal !== undefined ? { signal: this.signal } : {}
1563
- };
1564
- }
1565
- registerTerminalResponders() {
1566
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "c" }, (params) => {
1567
- if (params.length === 0 || params[0] === 0)
1568
- this.write("\x1B[?62;22c");
1569
- return false;
1570
- }));
1571
- this.disposables.push(this.terminal.parser.registerCsiHandler({ prefix: ">", final: "c" }, (params) => {
1572
- if (params.length === 0 || params[0] === 0)
1573
- this.write("\x1B[>0;0;0c");
1574
- return false;
1575
- }));
1576
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "n" }, (params) => {
1577
- if (params[0] === 5) {
1578
- this.write("\x1B[0n");
1579
- } else if (params[0] === 6) {
1580
- const row = this.terminal.buffer.active.cursorY + 1;
1581
- const col = this.terminal.buffer.active.cursorX + 1;
1582
- this.write(`\x1B[${row};${col}R`);
1583
- }
1584
- return false;
1585
- }));
1586
- }
1587
- respondToRawTerminalQueries(text) {
1588
- if (!text)
1589
- return;
1590
- const decrqm = /\x1b\[\?(\d+)\$p/g;
1591
- let match;
1592
- while ((match = decrqm.exec(text)) !== null) {
1593
- this.write(`\x1B[?${match[1]};2$y`);
1594
- }
1595
- }
1596
- }
1597
-
1598
1234
  // packages/cli/src/app-opentui/keymap.ts
1599
1235
  var autocompleteState;
1600
1236
  function clearTypeBar(context, message) {
@@ -1604,22 +1240,15 @@ function clearTypeBar(context, message) {
1604
1240
  context.emitTypeBarPatch({ value: "", mode: "nav", prompt: undefined, message });
1605
1241
  }
1606
1242
  function handleEmbeddedTerminalKey(context, key) {
1607
- const state = context.getState();
1608
- const piHost = getActivePiHost();
1609
- const commandHost = getActiveCommandHost();
1610
- const host = state.scene === "handoff" ? piHost : state.scene === "command" ? commandHost : null;
1243
+ if (context.getState().scene !== "command")
1244
+ return false;
1245
+ const host = getActiveCommandHost();
1611
1246
  if (!host)
1612
1247
  return false;
1613
1248
  if (key.ctrl && key.name === "]") {
1614
- if (state.scene === "handoff") {
1615
- stopActivePiHost("operator detach");
1616
- clearTypeBar(context, "detached from Pi");
1617
- context.runAppAction("Opening runs", () => context.runtime.runIntent({ scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } }));
1618
- } else {
1619
- stopActiveCommandHost("operator detach");
1620
- clearTypeBar(context, "closed command");
1621
- context.runAppAction("Project menu", () => context.runtime.runIntent({ scene: "main", argv: ["main"], action: { kind: "none", label: "Project menu" } }));
1622
- }
1249
+ stopActiveCommandHost("operator detach");
1250
+ clearTypeBar(context, "closed command");
1251
+ context.runAppAction("Project menu", () => context.runtime.runIntent({ scene: "main", argv: ["main"], action: { kind: "none", label: "Project menu" } }));
1623
1252
  return true;
1624
1253
  }
1625
1254
  const sequence = key.raw || key.sequence;
@@ -1931,8 +1560,8 @@ import { WsTransport } from "@rig/client";
1931
1560
  import { RIG_WS_CHANNELS } from "@rig/contracts";
1932
1561
 
1933
1562
  // packages/cli/src/commands/_server-client.ts
1934
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1935
- import { resolve as resolve2 } from "path";
1563
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
1564
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
1936
1565
 
1937
1566
  // packages/cli/src/runner.ts
1938
1567
  import { EventBus } from "@rig/runtime/control-plane/runtime/events";
@@ -2024,12 +1653,28 @@ function readRepoConnection(projectRoot) {
2024
1653
  selected,
2025
1654
  project: typeof record.project === "string" ? record.project : undefined,
2026
1655
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
2027
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
1656
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
1657
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
1658
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
2028
1659
  };
2029
1660
  }
2030
1661
  function writeRepoConnection(projectRoot, state) {
2031
1662
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
2032
1663
  }
1664
+ function rootAllowedForSelection(repo, connection) {
1665
+ const root = repo.serverProjectRoot?.trim();
1666
+ if (!root)
1667
+ return;
1668
+ if (connection.kind === "remote") {
1669
+ if (repo.serverProjectRootAlias !== repo.selected)
1670
+ return;
1671
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
1672
+ return;
1673
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
1674
+ return;
1675
+ }
1676
+ return root;
1677
+ }
2033
1678
  function resolveSelectedConnection(projectRoot, options = {}) {
2034
1679
  const repo = readRepoConnection(projectRoot);
2035
1680
  if (!repo)
@@ -2041,13 +1686,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
2041
1686
  if (!connection) {
2042
1687
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
2043
1688
  }
2044
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
1689
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
1690
+ }
1691
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
1692
+ const repo = readRepoConnection(projectRoot);
1693
+ if (!repo)
1694
+ return;
1695
+ let inferred = metadata;
1696
+ if (!inferred.alias || !inferred.baseUrl) {
1697
+ try {
1698
+ const selected = resolveSelectedConnection(projectRoot);
1699
+ if (selected?.connection.kind === "remote") {
1700
+ inferred = {
1701
+ alias: inferred.alias ?? selected.alias,
1702
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
1703
+ };
1704
+ }
1705
+ } catch {}
1706
+ }
1707
+ writeRepoConnection(projectRoot, {
1708
+ ...repo,
1709
+ ...metadata.project ? { project: metadata.project } : {},
1710
+ serverProjectRoot,
1711
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
1712
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
1713
+ });
2045
1714
  }
2046
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
1715
+ function clearRepoServerProjectRoot(projectRoot) {
2047
1716
  const repo = readRepoConnection(projectRoot);
2048
1717
  if (!repo)
2049
1718
  return;
2050
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
1719
+ writeRepoConnection(projectRoot, {
1720
+ selected: repo.selected,
1721
+ ...repo.project ? { project: repo.project } : {},
1722
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
1723
+ });
2051
1724
  }
2052
1725
 
2053
1726
  // packages/cli/src/commands/_server-client.ts
@@ -2088,11 +1761,10 @@ function readStoredGitHubAuthToken(projectRoot) {
2088
1761
  const parsed = readRemoteAuthState(projectRoot);
2089
1762
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
2090
1763
  }
2091
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
2092
- const repo = readRepoConnection(projectRoot);
2093
- const slug = repo?.project?.trim();
2094
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
1764
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
1765
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
2095
1766
  return null;
1767
+ const repo = readRepoConnection(projectRoot);
2096
1768
  const auth = readRemoteAuthState(projectRoot);
2097
1769
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
2098
1770
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -2101,25 +1773,413 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
2101
1773
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
2102
1774
  if (!checkoutBaseDir)
2103
1775
  return null;
2104
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
2105
- writeRepoServerProjectRoot(projectRoot, inferred);
2106
- return inferred;
1776
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
2107
1777
  }
2108
1778
  function readLocalConnectionFallbackToken(projectRoot) {
2109
1779
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
2110
1780
  }
1781
+ function normalizeRepoSlug(value) {
1782
+ const slug = value?.trim();
1783
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
1784
+ }
1785
+ function readProjectLinkSlug(projectRoot) {
1786
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
1787
+ if (!existsSync2(path))
1788
+ return null;
1789
+ try {
1790
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
1791
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1792
+ return null;
1793
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
1794
+ } catch {
1795
+ return null;
1796
+ }
1797
+ }
1798
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
1799
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
1800
+ mkdirSync2(dirname2(path), { recursive: true });
1801
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
1802
+ `, "utf8");
1803
+ }
1804
+ function remoteLinkRepairCommand(repoSlug) {
1805
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
1806
+ }
1807
+ function formatRemoteProjectLinkHint(resolution) {
1808
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
1809
+ if (resolution.status === "auth_required") {
1810
+ 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}` : ""}\`.`;
1811
+ }
1812
+ if (resolution.status === "missing_project") {
1813
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
1814
+ }
1815
+ if (resolution.status === "not_remote")
1816
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
1817
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
1818
+ }
1819
+ function remoteProjectLinkFailure(input) {
1820
+ const partial = {
1821
+ status: input.status,
1822
+ alias: input.alias,
1823
+ baseUrl: input.baseUrl,
1824
+ repoSlug: input.repoSlug
1825
+ };
1826
+ return {
1827
+ ok: false,
1828
+ ...input,
1829
+ hint: formatRemoteProjectLinkHint(partial),
1830
+ next: remoteLinkRepairCommand(input.repoSlug)
1831
+ };
1832
+ }
1833
+ function remoteProjectLinkSuccess(input) {
1834
+ return {
1835
+ ok: true,
1836
+ status: input.status,
1837
+ alias: input.alias,
1838
+ baseUrl: input.baseUrl,
1839
+ repoSlug: input.repoSlug,
1840
+ serverProjectRoot: input.serverProjectRoot,
1841
+ source: input.source,
1842
+ prepared: input.prepared ?? input.status === "prepared",
1843
+ validated: input.validated ?? false,
1844
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
1845
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
1846
+ next: "rig task list"
1847
+ };
1848
+ }
1849
+ function localCheckoutPathCandidate(projectRoot, candidate) {
1850
+ try {
1851
+ const local = resolve2(projectRoot);
1852
+ const resolved = resolve2(candidate);
1853
+ return resolved === local || resolved.startsWith(`${local}/`);
1854
+ } catch {
1855
+ return false;
1856
+ }
1857
+ }
1858
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
1859
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
1860
+ if (authToken && queryAuthFallbackEnabled())
1861
+ requestUrl.searchParams.set("rt", authToken);
1862
+ const response = await fetch(requestUrl, {
1863
+ ...init,
1864
+ headers: mergeHeaders(init.headers, authToken)
1865
+ });
1866
+ const text = await response.text();
1867
+ const payload = text.trim().length > 0 ? (() => {
1868
+ try {
1869
+ return JSON.parse(text);
1870
+ } catch {
1871
+ return null;
1872
+ }
1873
+ })() : null;
1874
+ return { ok: response.ok, status: response.status, payload, text };
1875
+ }
1876
+ function payloadError(payload, fallback) {
1877
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
1878
+ const record = payload;
1879
+ const value = record.error ?? record.message ?? record.reason;
1880
+ if (typeof value === "string" && value.trim())
1881
+ return value.trim();
1882
+ }
1883
+ return fallback;
1884
+ }
1885
+ function checkoutPathsFromProjectPayload(payload) {
1886
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1887
+ return [];
1888
+ const project = payload.project;
1889
+ if (!project || typeof project !== "object" || Array.isArray(project))
1890
+ return [];
1891
+ const checkouts = project.checkouts;
1892
+ if (!Array.isArray(checkouts))
1893
+ return [];
1894
+ return [...checkouts].reverse().flatMap((entry) => {
1895
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
1896
+ return [];
1897
+ const path = entry.path;
1898
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
1899
+ });
1900
+ }
1901
+ function checkoutPathFromPreparePayload(payload) {
1902
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
1903
+ return null;
1904
+ const checkout = payload.checkout;
1905
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
1906
+ return null;
1907
+ const path = checkout.path;
1908
+ return typeof path === "string" && path.trim() ? path.trim() : null;
1909
+ }
1910
+ async function validateAndPersistRemoteRoot(input) {
1911
+ const candidate = input.candidate.trim();
1912
+ if (!candidate || !isAbsolute(candidate)) {
1913
+ return remoteProjectLinkFailure({
1914
+ status: "invalid_root",
1915
+ alias: input.alias,
1916
+ baseUrl: input.baseUrl,
1917
+ repoSlug: input.repoSlug,
1918
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
1919
+ });
1920
+ }
1921
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
1922
+ return remoteProjectLinkFailure({
1923
+ status: "invalid_root",
1924
+ alias: input.alias,
1925
+ baseUrl: input.baseUrl,
1926
+ repoSlug: input.repoSlug,
1927
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
1928
+ });
1929
+ }
1930
+ let response;
1931
+ try {
1932
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
1933
+ method: "POST",
1934
+ headers: { "content-type": "application/json" },
1935
+ body: JSON.stringify({ projectRoot: candidate })
1936
+ });
1937
+ } catch (error) {
1938
+ return remoteProjectLinkFailure({
1939
+ status: "error",
1940
+ alias: input.alias,
1941
+ baseUrl: input.baseUrl,
1942
+ repoSlug: input.repoSlug,
1943
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
1944
+ });
1945
+ }
1946
+ if (response.status === 401 || response.status === 403) {
1947
+ return remoteProjectLinkFailure({
1948
+ status: "auth_required",
1949
+ alias: input.alias,
1950
+ baseUrl: input.baseUrl,
1951
+ repoSlug: input.repoSlug,
1952
+ statusCode: response.status,
1953
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
1954
+ });
1955
+ }
1956
+ if (!response.ok) {
1957
+ return remoteProjectLinkFailure({
1958
+ status: "invalid_root",
1959
+ alias: input.alias,
1960
+ baseUrl: input.baseUrl,
1961
+ repoSlug: input.repoSlug,
1962
+ statusCode: response.status,
1963
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
1964
+ });
1965
+ }
1966
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
1967
+ if (record.ok !== true) {
1968
+ return remoteProjectLinkFailure({
1969
+ status: "invalid_root",
1970
+ alias: input.alias,
1971
+ baseUrl: input.baseUrl,
1972
+ repoSlug: input.repoSlug,
1973
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
1974
+ });
1975
+ }
1976
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
1977
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
1978
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
1979
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
1980
+ return remoteProjectLinkSuccess({
1981
+ status,
1982
+ alias: input.alias,
1983
+ baseUrl: input.baseUrl,
1984
+ repoSlug: input.repoSlug,
1985
+ serverProjectRoot: accepted,
1986
+ source: input.source,
1987
+ prepared: input.prepared,
1988
+ validated: true,
1989
+ 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}.`
1990
+ });
1991
+ }
1992
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
1993
+ let selected;
1994
+ try {
1995
+ selected = resolveSelectedConnection(projectRoot);
1996
+ } catch (error) {
1997
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
1998
+ }
1999
+ if (!selected || selected.connection.kind !== "remote") {
2000
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
2001
+ }
2002
+ const repo = readRepoConnection(projectRoot);
2003
+ const explicitRepoRequested = options.repoSlug !== undefined;
2004
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
2005
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
2006
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
2007
+ const alias = selected.alias;
2008
+ const baseUrl = selected.connection.baseUrl;
2009
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
2010
+ const mode = options.mode ?? "backfill-only";
2011
+ if (explicitRepoRequested && !explicitRepoSlug) {
2012
+ return remoteProjectLinkFailure({
2013
+ status: "missing_project",
2014
+ alias,
2015
+ baseUrl,
2016
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
2017
+ });
2018
+ }
2019
+ if (!repoSlug) {
2020
+ return remoteProjectLinkFailure({
2021
+ status: "missing_project",
2022
+ alias,
2023
+ baseUrl,
2024
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
2025
+ });
2026
+ }
2027
+ const skippedCandidates = [];
2028
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
2029
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
2030
+ if (storedRoot && storedRootMatchesResolvedRepo) {
2031
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
2032
+ clearRepoServerProjectRoot(projectRoot);
2033
+ skippedCandidates.push(storedRoot);
2034
+ } else {
2035
+ const storedResult = await validateAndPersistRemoteRoot({
2036
+ projectRoot,
2037
+ alias,
2038
+ baseUrl,
2039
+ authToken,
2040
+ repoSlug,
2041
+ candidate: storedRoot,
2042
+ source: "stored",
2043
+ status: "ready"
2044
+ });
2045
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
2046
+ return storedResult;
2047
+ clearRepoServerProjectRoot(projectRoot);
2048
+ skippedCandidates.push(storedRoot);
2049
+ }
2050
+ } else if (storedRoot) {
2051
+ skippedCandidates.push(storedRoot);
2052
+ }
2053
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
2054
+ if (authCandidate) {
2055
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
2056
+ if (authResult.ok || authResult.status === "auth_required")
2057
+ return authResult;
2058
+ }
2059
+ let registryResponse;
2060
+ try {
2061
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
2062
+ } catch (error) {
2063
+ return remoteProjectLinkFailure({
2064
+ status: "error",
2065
+ alias,
2066
+ baseUrl,
2067
+ repoSlug,
2068
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
2069
+ });
2070
+ }
2071
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
2072
+ return remoteProjectLinkFailure({
2073
+ status: "auth_required",
2074
+ alias,
2075
+ baseUrl,
2076
+ repoSlug,
2077
+ statusCode: registryResponse.status,
2078
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
2079
+ });
2080
+ }
2081
+ if (registryResponse.ok) {
2082
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
2083
+ for (const candidate of candidates) {
2084
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
2085
+ if (result.ok || result.status === "auth_required")
2086
+ return result;
2087
+ skippedCandidates.push(candidate);
2088
+ }
2089
+ if (mode === "backfill-only") {
2090
+ return remoteProjectLinkFailure({
2091
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
2092
+ alias,
2093
+ baseUrl,
2094
+ repoSlug,
2095
+ 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.`,
2096
+ skippedCandidates
2097
+ });
2098
+ }
2099
+ } else if (registryResponse.status === 404) {
2100
+ if (mode === "backfill-only") {
2101
+ return remoteProjectLinkFailure({
2102
+ status: "project_not_registered",
2103
+ alias,
2104
+ baseUrl,
2105
+ repoSlug,
2106
+ statusCode: registryResponse.status,
2107
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
2108
+ });
2109
+ }
2110
+ } else {
2111
+ return remoteProjectLinkFailure({
2112
+ status: "error",
2113
+ alias,
2114
+ baseUrl,
2115
+ repoSlug,
2116
+ statusCode: registryResponse.status,
2117
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
2118
+ skippedCandidates
2119
+ });
2120
+ }
2121
+ let prepareResponse;
2122
+ try {
2123
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
2124
+ method: "POST",
2125
+ headers: { "content-type": "application/json" },
2126
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
2127
+ });
2128
+ } catch (error) {
2129
+ return remoteProjectLinkFailure({
2130
+ status: "error",
2131
+ alias,
2132
+ baseUrl,
2133
+ repoSlug,
2134
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
2135
+ });
2136
+ }
2137
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
2138
+ return remoteProjectLinkFailure({
2139
+ status: "auth_required",
2140
+ alias,
2141
+ baseUrl,
2142
+ repoSlug,
2143
+ statusCode: prepareResponse.status,
2144
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
2145
+ });
2146
+ }
2147
+ if (!prepareResponse.ok) {
2148
+ return remoteProjectLinkFailure({
2149
+ status: "error",
2150
+ alias,
2151
+ baseUrl,
2152
+ repoSlug,
2153
+ statusCode: prepareResponse.status,
2154
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
2155
+ skippedCandidates
2156
+ });
2157
+ }
2158
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
2159
+ if (!preparedPath) {
2160
+ return remoteProjectLinkFailure({
2161
+ status: "invalid_root",
2162
+ alias,
2163
+ baseUrl,
2164
+ repoSlug,
2165
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
2166
+ skippedCandidates
2167
+ });
2168
+ }
2169
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
2170
+ }
2111
2171
  async function ensureServerForCli(projectRoot) {
2112
2172
  try {
2113
2173
  const selected = resolveSelectedConnection(projectRoot);
2114
2174
  if (selected?.connection.kind === "remote") {
2115
2175
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
2116
2176
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
2117
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
2177
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
2118
2178
  return {
2119
2179
  baseUrl: selected.connection.baseUrl,
2120
2180
  authToken,
2121
2181
  connectionKind: "remote",
2122
- serverProjectRoot
2182
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
2123
2183
  };
2124
2184
  }
2125
2185
  reportServerPhase("Starting local Rig server\u2026");
@@ -2137,32 +2197,6 @@ async function ensureServerForCli(projectRoot) {
2137
2197
  throw error;
2138
2198
  }
2139
2199
  }
2140
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
2141
- const repo = readRepoConnection(projectRoot);
2142
- const slug = repo?.project?.trim();
2143
- if (!slug)
2144
- return null;
2145
- try {
2146
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
2147
- if (authToken && queryAuthFallbackEnabled())
2148
- url.searchParams.set("rt", authToken);
2149
- const response = await fetch(url, {
2150
- headers: mergeHeaders(undefined, authToken)
2151
- });
2152
- if (!response.ok)
2153
- return null;
2154
- const payload = await response.json();
2155
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
2156
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
2157
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
2158
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
2159
- if (path)
2160
- writeRepoServerProjectRoot(projectRoot, path);
2161
- return path;
2162
- } catch {
2163
- return null;
2164
- }
2165
- }
2166
2200
  function mergeCookie(existing, name, value) {
2167
2201
  const encoded = `${name}=${encodeURIComponent(value)}`;
2168
2202
  if (!existing?.trim())
@@ -2238,7 +2272,7 @@ import {
2238
2272
  dim as otuiDim,
2239
2273
  fg as otuiFg,
2240
2274
  t,
2241
- TextAttributes as TextAttributes2
2275
+ TextAttributes
2242
2276
  } from "@opentui/core";
2243
2277
  var RIG_UI = {
2244
2278
  bg: "#070809",
@@ -2274,7 +2308,7 @@ var styles = {
2274
2308
  };
2275
2309
 
2276
2310
  // packages/cli/src/app-opentui/drone.ts
2277
- import { RGBA as RGBA2, StyledText as StyledText2, TextAttributes as TextAttributes3 } from "@opentui/core";
2311
+ import { RGBA, StyledText, TextAttributes as TextAttributes2 } from "@opentui/core";
2278
2312
  var MINI_DRONE = [
2279
2313
  "(!!!) (!!!)",
2280
2314
  " \\%==%/ ",
@@ -2290,13 +2324,13 @@ var LEAD_MARK = [
2290
2324
  var BLADE_FRAMES = ["---", "\\\\\\", "|||", "///"];
2291
2325
  var EYE_FRAMES = ["o", "@", "\u2022", "."];
2292
2326
  var COLOR = {
2293
- body: RGBA2.fromHex(RIG_UI.lime),
2294
- mini: RGBA2.fromHex(RIG_UI.limeDim),
2295
- rotor: RGBA2.fromHex(RIG_UI.cyan),
2296
- path: RGBA2.fromHex(RIG_UI.cyan),
2297
- eye: RGBA2.fromHex(RIG_UI.ink),
2298
- dim: RGBA2.fromHex(RIG_UI.ink4),
2299
- ink: RGBA2.fromHex(RIG_UI.ink2)
2327
+ body: RGBA.fromHex(RIG_UI.lime),
2328
+ mini: RGBA.fromHex(RIG_UI.limeDim),
2329
+ rotor: RGBA.fromHex(RIG_UI.cyan),
2330
+ path: RGBA.fromHex(RIG_UI.cyan),
2331
+ eye: RGBA.fromHex(RIG_UI.ink),
2332
+ dim: RGBA.fromHex(RIG_UI.ink4),
2333
+ ink: RGBA.fromHex(RIG_UI.ink2)
2300
2334
  };
2301
2335
  function bladeForTick(tick, phase = 0) {
2302
2336
  return BLADE_FRAMES[(Math.floor(tick / 3) + phase) % BLADE_FRAMES.length];
@@ -2306,12 +2340,12 @@ function eyeForTick(tick, phase = 0) {
2306
2340
  return pulse > 0.55 ? EYE_FRAMES[1] : pulse > 0.1 ? EYE_FRAMES[0] : pulse > -0.45 ? EYE_FRAMES[2] : EYE_FRAMES[3];
2307
2341
  }
2308
2342
  function chunk(text, fg, bold = false, dim = false) {
2309
- let attributes = TextAttributes3.NONE;
2343
+ let attributes = TextAttributes2.NONE;
2310
2344
  if (bold)
2311
- attributes |= TextAttributes3.BOLD;
2345
+ attributes |= TextAttributes2.BOLD;
2312
2346
  if (dim)
2313
- attributes |= TextAttributes3.DIM;
2314
- return { __isChunk: true, text, fg, ...attributes !== TextAttributes3.NONE ? { attributes } : {} };
2347
+ attributes |= TextAttributes2.DIM;
2348
+ return { __isChunk: true, text, fg, ...attributes !== TextAttributes2.NONE ? { attributes } : {} };
2315
2349
  }
2316
2350
  function styledLine(text, colorFor) {
2317
2351
  const chunks = [];
@@ -2332,7 +2366,7 @@ function styledLine(text, colorFor) {
2332
2366
  run += char;
2333
2367
  }
2334
2368
  flush();
2335
- return new StyledText2(chunks.length > 0 ? chunks : [chunk("", COLOR.ink)]);
2369
+ return new StyledText(chunks.length > 0 ? chunks : [chunk("", COLOR.ink)]);
2336
2370
  }
2337
2371
  function droneColor(char) {
2338
2372
  if (char === "?" || char === "o" || char === "@" || char === "\u2022")
@@ -2612,7 +2646,7 @@ function reduceAppEvent(state, event) {
2612
2646
  }
2613
2647
 
2614
2648
  // packages/cli/src/app-opentui/render/graphics.ts
2615
- import { FrameBufferRenderable, RGBA as RGBA3 } from "@opentui/core";
2649
+ import { FrameBufferRenderable, RGBA as RGBA2 } from "@opentui/core";
2616
2650
 
2617
2651
  // packages/cli/src/app-opentui/render/ascii-fleet.ts
2618
2652
  var LEAD_DRONE = [
@@ -2756,13 +2790,13 @@ var GLOW_FALLOFF_EXP_ASCII = 2.2;
2756
2790
  // packages/cli/src/app-opentui/render/graphics.ts
2757
2791
  var BRAILLE_SAMPLES_X = 2;
2758
2792
  var BRAILLE_SAMPLES_Y = 4;
2759
- var TRANSPARENT = RGBA3.fromValues(0, 0, 0, 0);
2760
- var BACKDROP = RGBA3.fromHex(RIG_UI.bg);
2761
- var PANEL_BG = RGBA3.fromInts(16, 17, 21, 184);
2762
- var PANEL_HEADER_BG = RGBA3.fromInts(16, 17, 21, 188);
2763
- var PANEL_LINE = RGBA3.fromInts(255, 255, 255, 20);
2764
- var PANEL_LINE_DIM = RGBA3.fromInts(255, 255, 255, 8);
2765
- var PANEL_TEXT_DIM = RGBA3.fromInts(108, 110, 121, 255);
2793
+ var TRANSPARENT = RGBA2.fromValues(0, 0, 0, 0);
2794
+ var BACKDROP = RGBA2.fromHex(RIG_UI.bg);
2795
+ var PANEL_BG = RGBA2.fromInts(16, 17, 21, 184);
2796
+ var PANEL_HEADER_BG = RGBA2.fromInts(16, 17, 21, 188);
2797
+ var PANEL_LINE = RGBA2.fromInts(255, 255, 255, 20);
2798
+ var PANEL_LINE_DIM = RGBA2.fromInts(255, 255, 255, 8);
2799
+ var PANEL_TEXT_DIM = RGBA2.fromInts(108, 110, 121, 255);
2766
2800
  var AC_RGB = [204, 255, 77];
2767
2801
  var C2_RGB = [86, 216, 255];
2768
2802
  var MG_RGB = [255, 121, 176];
@@ -2867,7 +2901,7 @@ function paletteColor(ac, c2, mg, ink) {
2867
2901
  const b = (AC_RGB[2] * ac + C2_RGB[2] * c2 + MG_RGB[2] * mg + INK_RGB[2] * ink) / total;
2868
2902
  const intensity = Math.min(1, total / 4);
2869
2903
  const lift = 0.34 + intensity * 0.66;
2870
- return RGBA3.fromInts(Math.round(r * lift), Math.round(g * lift), Math.round(b * lift), 255);
2904
+ return RGBA2.fromInts(Math.round(r * lift), Math.round(g * lift), Math.round(b * lift), 255);
2871
2905
  }
2872
2906
  function clearCanvas(canvas) {
2873
2907
  canvas.ac.fill(0);
@@ -3222,8 +3256,8 @@ function staticFleetTick(scene) {
3222
3256
  }
3223
3257
  function withAlpha(hex, alpha) {
3224
3258
  const a = Math.max(0, Math.min(255, Math.round(alpha * 255)));
3225
- const [r, g, b] = RGBA3.fromHex(hex).toInts();
3226
- return RGBA3.fromInts(r, g, b, a);
3259
+ const [r, g, b] = RGBA2.fromHex(hex).toInts();
3260
+ return RGBA2.fromInts(r, g, b, a);
3227
3261
  }
3228
3262
  function asciiFleetColor(char, row, alpha) {
3229
3263
  if (char === "@" || char === "$" || char === "o")
@@ -3231,7 +3265,7 @@ function asciiFleetColor(char, row, alpha) {
3231
3265
  if (char === "%" || char === "!" || char === "/" || char === "\\" || char === "|")
3232
3266
  return withAlpha(RIG_UI.cyan, alpha);
3233
3267
  if (char === "." || char === "'" || char === "_" || row < 3 || row > FLEET_GRID_HEIGHT - 4) {
3234
- return RGBA3.fromInts(108, 110, 121, Math.min(170, Math.max(0, Math.min(255, Math.round(alpha * 255)))));
3268
+ return RGBA2.fromInts(108, 110, 121, Math.min(170, Math.max(0, Math.min(255, Math.round(alpha * 255)))));
3235
3269
  }
3236
3270
  return withAlpha(RIG_UI.limeDim, alpha);
3237
3271
  }
@@ -3344,7 +3378,7 @@ function sparklineString(values, width) {
3344
3378
  }
3345
3379
 
3346
3380
  // packages/cli/src/app-opentui/render/text.ts
3347
- import { RGBA as RGBA4, TextAttributes as TextAttributes4, TextRenderable } from "@opentui/core";
3381
+ import { RGBA as RGBA3, TextAttributes as TextAttributes3, TextRenderable } from "@opentui/core";
3348
3382
 
3349
3383
  // packages/cli/src/app-opentui/render/hover.ts
3350
3384
  var hoveredId;
@@ -3371,8 +3405,8 @@ function subscribeHover(listener) {
3371
3405
  }
3372
3406
 
3373
3407
  // packages/cli/src/app-opentui/render/text.ts
3374
- var TRANSPARENT2 = RGBA4.fromInts(0, 0, 0, 0);
3375
- var HOVER_BG = RGBA4.fromHex(RIG_UI.hover);
3408
+ var TRANSPARENT2 = RGBA3.fromInts(0, 0, 0, 0);
3409
+ var HOVER_BG = RGBA3.fromHex(RIG_UI.hover);
3376
3410
  function lineIsClickable(line2) {
3377
3411
  return line2?.selectable !== undefined || line2?.selectableIndex !== undefined;
3378
3412
  }
@@ -3381,7 +3415,7 @@ function lineSelectableId(line2) {
3381
3415
  }
3382
3416
  function lineBackground(line2) {
3383
3417
  if (line2?.bg)
3384
- return RGBA4.fromHex(line2.bg);
3418
+ return RGBA3.fromHex(line2.bg);
3385
3419
  const id = lineSelectableId(line2);
3386
3420
  if (id !== undefined && isHovered(id))
3387
3421
  return HOVER_BG;
@@ -3450,7 +3484,7 @@ function applyTextLine(renderable, line2, top, left, width) {
3450
3484
  renderable.content = line2?.styledText ?? line2?.text ?? "";
3451
3485
  renderable.fg = line2?.fg ?? RIG_UI.ink2;
3452
3486
  renderable.bg = lineBackground(line2);
3453
- renderable.attributes = line2?.bold ? TextAttributes4.BOLD : line2?.dim ? TextAttributes4.DIM : 0;
3487
+ renderable.attributes = line2?.bold ? TextAttributes3.BOLD : line2?.dim ? TextAttributes3.DIM : 0;
3454
3488
  }
3455
3489
  function applyFlowTextLine(renderable, line2, width) {
3456
3490
  renderable.setRigSceneLine?.(line2);
@@ -3460,7 +3494,7 @@ function applyFlowTextLine(renderable, line2, width) {
3460
3494
  renderable.content = line2?.styledText ?? line2?.text ?? "";
3461
3495
  renderable.fg = line2?.fg ?? RIG_UI.ink2;
3462
3496
  renderable.bg = lineBackground(line2);
3463
- renderable.attributes = line2?.bold ? TextAttributes4.BOLD : line2?.dim ? TextAttributes4.DIM : 0;
3497
+ renderable.attributes = line2?.bold ? TextAttributes3.BOLD : line2?.dim ? TextAttributes3.DIM : 0;
3464
3498
  }
3465
3499
  function clearTextLines(renderables, from = 0) {
3466
3500
  for (let index = from;index < renderables.length; index += 1) {
@@ -3474,9 +3508,20 @@ function clearTextLines(renderables, from = 0) {
3474
3508
  }
3475
3509
  }
3476
3510
 
3511
+ // packages/cli/src/app-opentui/render/terminal-handoff.ts
3512
+ function resumeRendererClean(renderer) {
3513
+ try {
3514
+ renderer.pendingSuspendedTerminalSetup = true;
3515
+ } catch {}
3516
+ renderer.resume();
3517
+ try {
3518
+ renderer.requestRender?.();
3519
+ } catch {}
3520
+ }
3521
+
3477
3522
  // packages/cli/src/app-opentui/render/panels.ts
3478
- import { RGBA as RGBA5, ScrollBoxRenderable } from "@opentui/core";
3479
- var TRANSPARENT3 = RGBA5.fromInts(0, 0, 0, 0);
3523
+ import { RGBA as RGBA4, ScrollBoxRenderable } from "@opentui/core";
3524
+ var TRANSPARENT3 = RGBA4.fromInts(0, 0, 0, 0);
3480
3525
  var MAX_PANEL_LINES = 420;
3481
3526
  var PANEL_OPAQUE_ALPHA = 255;
3482
3527
  var PANEL_BORDER = hexToRgba(RIG_UI.border, 255);
@@ -3485,8 +3530,8 @@ function hexToRgba(hex, alpha) {
3485
3530
  const full = clean.length === 3 ? clean.split("").map((part) => `${part}${part}`).join("") : clean;
3486
3531
  const value = Number.parseInt(full, 16);
3487
3532
  if (!Number.isFinite(value))
3488
- return RGBA5.fromInts(14, 15, 17, alpha);
3489
- return RGBA5.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255, alpha);
3533
+ return RGBA4.fromInts(14, 15, 17, alpha);
3534
+ return RGBA4.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255, alpha);
3490
3535
  }
3491
3536
  function panelBackground(panel) {
3492
3537
  return hexToRgba(panel.backgroundColor ?? RIG_UI.panel, PANEL_OPAQUE_ALPHA);
@@ -3601,9 +3646,9 @@ function applyScrollPanels(panels, layout, scenePanels) {
3601
3646
  }
3602
3647
 
3603
3648
  // packages/cli/src/app-opentui/render/type-bar.ts
3604
- import { BoxRenderable, InputRenderable, InputRenderableEvents, RGBA as RGBA6, StyledText as StyledText3, TextRenderable as TextRenderable2 } from "@opentui/core";
3605
- var TYPEBAR_BG = RGBA6.fromInts(20, 25, 14, 224);
3606
- var TYPEBAR_BORDER = RGBA6.fromInts(204, 255, 77, 92);
3649
+ import { BoxRenderable, InputRenderable, InputRenderableEvents, RGBA as RGBA5, StyledText as StyledText2, TextRenderable as TextRenderable2 } from "@opentui/core";
3650
+ var TYPEBAR_BG = RGBA5.fromInts(20, 25, 14, 224);
3651
+ var TYPEBAR_BORDER = RGBA5.fromInts(204, 255, 77, 92);
3607
3652
  function createTypeBar(renderer) {
3608
3653
  const background = new BoxRenderable(renderer, {
3609
3654
  id: "typebar-card",
@@ -3751,7 +3796,7 @@ function formatFooter(footer, width) {
3751
3796
  chunks.push(cell.style(text));
3752
3797
  used += visibleWidth(text);
3753
3798
  });
3754
- return new StyledText3(chunks);
3799
+ return new StyledText2(chunks);
3755
3800
  }
3756
3801
 
3757
3802
  // packages/cli/src/app-opentui/render/native-host.ts
@@ -3759,7 +3804,7 @@ import {
3759
3804
  BoxRenderable as BoxRenderable2,
3760
3805
  CodeRenderable,
3761
3806
  DiffRenderable,
3762
- RGBA as RGBA7,
3807
+ RGBA as RGBA6,
3763
3808
  ScrollBoxRenderable as ScrollBoxRenderable2,
3764
3809
  SyntaxStyle,
3765
3810
  TextRenderable as TextRenderable3,
@@ -3770,19 +3815,19 @@ function rigSyntaxStyle() {
3770
3815
  if (syntaxStyle)
3771
3816
  return syntaxStyle;
3772
3817
  syntaxStyle = SyntaxStyle.fromStyles({
3773
- keyword: { fg: RGBA7.fromHex(RIG_UI.magenta), bold: true },
3774
- string: { fg: RGBA7.fromHex(RIG_UI.lime) },
3775
- number: { fg: RGBA7.fromHex(RIG_UI.cyan) },
3776
- comment: { fg: RGBA7.fromHex(RIG_UI.ink4), italic: true },
3777
- function: { fg: RGBA7.fromHex(RIG_UI.cyan) },
3778
- type: { fg: RGBA7.fromHex(RIG_UI.limeDim) },
3779
- constant: { fg: RGBA7.fromHex(RIG_UI.yellow) },
3780
- default: { fg: RGBA7.fromHex(RIG_UI.ink2) }
3818
+ keyword: { fg: RGBA6.fromHex(RIG_UI.magenta), bold: true },
3819
+ string: { fg: RGBA6.fromHex(RIG_UI.lime) },
3820
+ number: { fg: RGBA6.fromHex(RIG_UI.cyan) },
3821
+ comment: { fg: RGBA6.fromHex(RIG_UI.ink4), italic: true },
3822
+ function: { fg: RGBA6.fromHex(RIG_UI.cyan) },
3823
+ type: { fg: RGBA6.fromHex(RIG_UI.limeDim) },
3824
+ constant: { fg: RGBA6.fromHex(RIG_UI.yellow) },
3825
+ default: { fg: RGBA6.fromHex(RIG_UI.ink2) }
3781
3826
  });
3782
3827
  return syntaxStyle;
3783
3828
  }
3784
3829
  function tableContent(rows) {
3785
- return rows.map((row, rowIndex) => row.map((cell) => [{ __isChunk: true, text: cell, fg: RGBA7.fromHex(rowIndex === 0 ? RIG_UI.ink3 : RIG_UI.ink2) }]));
3830
+ return rows.map((row, rowIndex) => row.map((cell) => [{ __isChunk: true, text: cell, fg: RGBA6.fromHex(rowIndex === 0 ? RIG_UI.ink3 : RIG_UI.ink2) }]));
3786
3831
  }
3787
3832
  function createNativeHost(renderer) {
3788
3833
  try {
@@ -3923,6 +3968,48 @@ function renderAsciiPreloaderFrame(scene, layout, tick) {
3923
3968
  };
3924
3969
  }
3925
3970
 
3971
+ // packages/cli/src/app-opentui/remote-link.ts
3972
+ var REPAIRABLE_REMOTE_LINK_STATUSES = new Set([
3973
+ "auth_required",
3974
+ "project_not_registered",
3975
+ "no_server_checkout",
3976
+ "invalid_root",
3977
+ "needs_prepare",
3978
+ "error"
3979
+ ]);
3980
+ function remoteProjectLinkError(message) {
3981
+ return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(message ?? "");
3982
+ }
3983
+ function serverRecordForRemoteLink(state) {
3984
+ const server = state.data.server;
3985
+ return server && typeof server === "object" && !Array.isArray(server) ? server : null;
3986
+ }
3987
+ function remoteProjectLinkState(state) {
3988
+ const serverRecord = serverRecordForRemoteLink(state);
3989
+ if (!serverRecord || serverRecord.kind !== "remote")
3990
+ return null;
3991
+ const link = serverRecord.remoteProjectLink;
3992
+ if (link && typeof link === "object" && !Array.isArray(link))
3993
+ return link;
3994
+ const direct = state.data.remoteProjectLink;
3995
+ if (direct && typeof direct === "object" && !Array.isArray(direct))
3996
+ return direct;
3997
+ return null;
3998
+ }
3999
+ function shouldOfferRemoteLinkRepair(state, message) {
4000
+ const link = remoteProjectLinkState(state);
4001
+ if (link) {
4002
+ if (link.ok === true)
4003
+ return false;
4004
+ const status = link.status ?? "";
4005
+ return REPAIRABLE_REMOTE_LINK_STATUSES.has(status);
4006
+ }
4007
+ const serverRecord = serverRecordForRemoteLink(state);
4008
+ if (serverRecord && serverRecord.kind !== "remote")
4009
+ return false;
4010
+ return remoteProjectLinkError(message ?? state.error?.message);
4011
+ }
4012
+
3926
4013
  // packages/cli/src/app-opentui/selectable.ts
3927
4014
  function selectableDeckRow(deck, item) {
3928
4015
  return { ...deckRow({ ...deck, activateOnClick: true }), selectable: item };
@@ -3932,13 +4019,17 @@ function selectableDeckRow(deck, item) {
3932
4019
  var ERROR_ACTIONS = [
3933
4020
  { detail: "return to dashboard", item: { id: "main", label: "main", intent: { scene: "main", argv: [], action: { kind: "refresh", label: "Back to dashboard" } }, message: "back to dashboard" } },
3934
4021
  { detail: "run diagnostics", item: { id: "doctor", label: "doctor", intent: { scene: "doctor", argv: ["doctor"], action: { kind: "doctor-run", label: "Run doctor" } }, message: "run diagnostics" } },
3935
- { 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" } },
3936
- { 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" } }
4022
+ { 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" } }
3937
4023
  ];
4024
+ 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" } };
4025
+ function errorActions(state) {
4026
+ return shouldOfferRemoteLinkRepair(state, state.error?.message) ? [...ERROR_ACTIONS, ERROR_REPAIR_LINK_ACTION] : ERROR_ACTIONS;
4027
+ }
3938
4028
  function renderErrorScene(state) {
3939
4029
  const message = state.error?.message ?? "Unknown app error";
3940
4030
  const hint = state.error?.hint ?? "Use the actions below to recover.";
3941
- const selected = Math.max(0, Math.min(3, state.selection.index));
4031
+ const actions = errorActions(state);
4032
+ const selected = Math.max(0, Math.min(actions.length - 1, state.selection.index));
3942
4033
  return makeSceneFrame({
3943
4034
  scene: "error",
3944
4035
  title: "Error",
@@ -3956,7 +4047,7 @@ function renderErrorScene(state) {
3956
4047
  ...hint ? [line(hint, { fg: RIG_UI.yellow })] : [],
3957
4048
  line("", { fg: RIG_UI.ink3 }),
3958
4049
  line("ACTIONS", { fg: RIG_UI.ink3, bold: true }),
3959
- ...ERROR_ACTIONS.map(({ detail, item }, index) => selectableDeckRow({ label: item.label, detail, index, active: selected === index }, item))
4050
+ ...actions.map(({ detail, item }, index) => selectableDeckRow({ label: item.label, detail, index, active: selected === index }, item))
3960
4051
  ],
3961
4052
  backgroundColor: RIG_UI.panel,
3962
4053
  backgroundAlpha: 184,
@@ -4084,7 +4175,7 @@ function renderHelpScene(state, layout) {
4084
4175
 
4085
4176
  // packages/cli/src/app-opentui/scenes/main.ts
4086
4177
  var CONFIGURED_MENU = [
4087
- ["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" }],
4178
+ ["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" }],
4088
4179
  ["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" }],
4089
4180
  ["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" }],
4090
4181
  ["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" }],
@@ -4103,10 +4194,10 @@ var CONFIGURED_MENU = [
4103
4194
  ["help", "all actions, shortcuts, mouse controls", { id: "help", label: "help", intent: { scene: "help", argv: ["help"], action: { kind: "none", label: "Opening help" } }, message: "selected help" }]
4104
4195
  ];
4105
4196
  var ONBOARD_PRIMARY = {
4106
- id: "onboard-setup",
4107
- label: "Start guided setup",
4108
- intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Setup" } },
4109
- message: "open the guided setup checklist"
4197
+ id: "onboard-init",
4198
+ label: "Start guided init",
4199
+ intent: { scene: "init", argv: ["init"], action: { kind: "refresh", label: "Init" } },
4200
+ message: "open the native init checklist"
4110
4201
  };
4111
4202
  var ONBOARD_SECONDARY = [
4112
4203
  ["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" }],
@@ -4169,7 +4260,7 @@ function configuredMenuRows(selectedIndex) {
4169
4260
  }));
4170
4261
  }
4171
4262
  function onboardingRows(selectedIndex) {
4172
- const primary = selectableDeckRow({ label: "setup", detail: "Start guided setup \u2014 recommended", active: selectedIndex === 0 }, ONBOARD_PRIMARY);
4263
+ const primary = selectableDeckRow({ label: "init", detail: "Start guided init \u2014 recommended", active: selectedIndex === 0 }, ONBOARD_PRIMARY);
4173
4264
  const secondary = ONBOARD_SECONDARY.map(([label, detail, item], index) => ({
4174
4265
  ...deckRow({ label, detail, index: index + 1, active: selectedIndex === index + 1, activateOnClick: true }),
4175
4266
  selectable: item
@@ -4233,7 +4324,7 @@ function renderMainScene(state, layout) {
4233
4324
  statusLine(state)
4234
4325
  ] : [
4235
4326
  line("WELCOME", { fg: RIG_UI.ink, bold: true }),
4236
- line("This project isn't set up yet. One guided flow gets you running.", { fg: RIG_UI.ink2 }),
4327
+ line("This project isn't initialized yet. One native init flow gets you running.", { fg: RIG_UI.ink2 }),
4237
4328
  blank(),
4238
4329
  line("GET STARTED", { fg: RIG_UI.ink, bold: true }),
4239
4330
  ...onboardingRows(actionSelected),
@@ -4268,11 +4359,17 @@ function renderMainScene(state, layout) {
4268
4359
  });
4269
4360
  }
4270
4361
 
4362
+ // packages/cli/src/app-opentui/pi-pty-host.ts
4363
+ function getActivePiHost() {
4364
+ return null;
4365
+ }
4366
+ function stopActivePiHost(_reason) {}
4367
+
4271
4368
  // packages/cli/src/app-opentui/runtime.ts
4272
4369
  var MAX_SCENE_LINES = 200;
4273
4370
  var MAX_SCENE_PANELS = 5;
4274
4371
  var ANIMATION_SLOWDOWN = 1;
4275
- var PRELOADER_BACKDROP = RGBA8.fromHex(RIG_UI.bg);
4372
+ var PRELOADER_BACKDROP = RGBA7.fromHex(RIG_UI.bg);
4276
4373
  function inboxPendingCount(state) {
4277
4374
  const inbox = state.data.inbox;
4278
4375
  if (!inbox || typeof inbox !== "object" || Array.isArray(inbox))
@@ -4288,7 +4385,7 @@ var PRIMARY_NAV = [
4288
4385
  { id: "tasks", label: "Tasks", scene: "tasks", argv: ["tasks"], enterLabel: "Tasks", member: ["tasks"] },
4289
4386
  { id: "inbox", label: "Inbox", scene: "inbox", argv: ["inbox"], enterLabel: "Inbox", member: ["inbox"], badge: inboxPendingCount },
4290
4387
  { id: "stats", label: "Stats", scene: "family", argv: ["stats"], enterLabel: "Stats", member: ["family"] },
4291
- { id: "setup", label: "Setup", scene: "init", argv: ["init"], enterLabel: "Setup", member: ["init", "doctor", "server", "pi", "plugin", "repo", "workspace"] },
4388
+ { id: "init", label: "Init", scene: "init", argv: ["init"], enterLabel: "Init", member: ["init", "doctor", "server", "pi", "plugin", "repo", "workspace"] },
4292
4389
  { id: "help", label: "Help", scene: "help", argv: ["help"], enterLabel: "Help", member: ["help"] }
4293
4390
  ];
4294
4391
  function navSectionIntent(section) {
@@ -4328,7 +4425,7 @@ function entryIntentForScene(scene) {
4328
4425
  case "doctor":
4329
4426
  return { scene, argv: ["doctor"], action: { kind: "doctor-run", label: "Doctor" } };
4330
4427
  case "init":
4331
- return { scene, argv: ["init"], action: { kind: "refresh", label: "Setup" } };
4428
+ return { scene, argv: ["init"], action: { kind: "refresh", label: "Init" } };
4332
4429
  case "run-detail":
4333
4430
  return { scene, argv: ["run", "status"], action: { kind: "refresh", label: "Run" } };
4334
4431
  case "pi":
@@ -4444,7 +4541,7 @@ function sceneSectionLabel(scene) {
4444
4541
  handoff: "pi console",
4445
4542
  server: "server",
4446
4543
  doctor: "doctor",
4447
- init: "setup",
4544
+ init: "init",
4448
4545
  pi: "pi",
4449
4546
  plugin: "plugins",
4450
4547
  repo: "repo",
@@ -4477,7 +4574,7 @@ function buildNavStrip(state) {
4477
4574
  chunks.push(otuiBold(styles.yellow(String(badgeCount))));
4478
4575
  }
4479
4576
  });
4480
- return new StyledText4(chunks);
4577
+ return new StyledText3(chunks);
4481
4578
  }
4482
4579
  function requestRender(renderer) {
4483
4580
  renderer.requestRender?.();
@@ -4706,7 +4803,8 @@ async function launchRigOpenTuiApp(options) {
4706
4803
  },
4707
4804
  suspend: () => renderer?.suspend(),
4708
4805
  resume: () => {
4709
- renderer?.resume();
4806
+ if (renderer)
4807
+ resumeRendererClean(renderer);
4710
4808
  renderApp();
4711
4809
  },
4712
4810
  destroy: () => renderer?.destroy()
@@ -4934,7 +5032,7 @@ async function launchRigOpenTuiApp(options) {
4934
5032
  }
4935
5033
  for (const adapter of options.adapters ?? [])
4936
5034
  await adapter.start?.(runtime);
4937
- liveEvents = await connectRigServerEvents(options.projectRoot, {
5035
+ connectRigServerEvents(options.projectRoot, {
4938
5036
  onSnapshotInvalidated: () => refreshCurrentDataScene(),
4939
5037
  onRunLogAppended: () => {
4940
5038
  const scene = store.getState().scene;
@@ -4942,11 +5040,17 @@ async function launchRigOpenTuiApp(options) {
4942
5040
  refreshCurrentDataScene();
4943
5041
  },
4944
5042
  onStatus: (status) => store.patch({ footer: { live: liveLinkLabel(status) } })
4945
- }).catch(() => null);
4946
- if (!liveEvents)
4947
- store.patch({ footer: { live: liveLinkLabel("disconnected") } });
4948
- if (liveEvents)
5043
+ }).then((subscription) => {
5044
+ if (destroyed) {
5045
+ subscription.close();
5046
+ return;
5047
+ }
5048
+ liveEvents = subscription;
4949
5049
  resources.add(() => liveEvents?.close());
5050
+ }).catch(() => {
5051
+ if (!destroyed)
5052
+ store.patch({ footer: { live: liveLinkLabel("disconnected") } });
5053
+ });
4950
5054
  await runtime.runIntent(store.getState().intent);
4951
5055
  } catch (error) {
4952
5056
  const normalized = normalizeError(error);