@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
@@ -65,6 +65,21 @@ function patchData(ctx, data) {
65
65
  function patchFooter(ctx, footer) {
66
66
  ctx.emit({ type: "footer.patch", footer });
67
67
  }
68
+ async function releaseRendererForExternalTui(ctx) {
69
+ const renderer = ctx.renderer;
70
+ if (!renderer)
71
+ return;
72
+ if (renderer.suspend) {
73
+ await renderer.suspend();
74
+ return;
75
+ }
76
+ if (renderer.destroy) {
77
+ await renderer.destroy();
78
+ }
79
+ }
80
+ async function resumeRendererAfterExternalTui(ctx) {
81
+ await ctx.renderer?.resume?.();
82
+ }
68
83
  function arrayFromPayload(value) {
69
84
  if (Array.isArray(value)) {
70
85
  return value.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
@@ -230,12 +245,28 @@ function readRepoConnection(projectRoot) {
230
245
  selected,
231
246
  project: typeof record.project === "string" ? record.project : undefined,
232
247
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
233
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
248
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
249
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
250
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
234
251
  };
235
252
  }
236
253
  function writeRepoConnection(projectRoot, state) {
237
254
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
238
255
  }
256
+ function rootAllowedForSelection(repo, connection) {
257
+ const root = repo.serverProjectRoot?.trim();
258
+ if (!root)
259
+ return;
260
+ if (connection.kind === "remote") {
261
+ if (repo.serverProjectRootAlias !== repo.selected)
262
+ return;
263
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
264
+ return;
265
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
266
+ return;
267
+ }
268
+ return root;
269
+ }
239
270
  function resolveSelectedConnection(projectRoot, options = {}) {
240
271
  const repo = readRepoConnection(projectRoot);
241
272
  if (!repo)
@@ -247,13 +278,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
247
278
  if (!connection) {
248
279
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
249
280
  }
250
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
281
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
282
+ }
283
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
284
+ const repo = readRepoConnection(projectRoot);
285
+ if (!repo)
286
+ return;
287
+ let inferred = metadata;
288
+ if (!inferred.alias || !inferred.baseUrl) {
289
+ try {
290
+ const selected = resolveSelectedConnection(projectRoot);
291
+ if (selected?.connection.kind === "remote") {
292
+ inferred = {
293
+ alias: inferred.alias ?? selected.alias,
294
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
295
+ };
296
+ }
297
+ } catch {}
298
+ }
299
+ writeRepoConnection(projectRoot, {
300
+ ...repo,
301
+ ...metadata.project ? { project: metadata.project } : {},
302
+ serverProjectRoot,
303
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
304
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
305
+ });
251
306
  }
252
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
307
+ function clearRepoServerProjectRoot(projectRoot) {
253
308
  const repo = readRepoConnection(projectRoot);
254
309
  if (!repo)
255
310
  return;
256
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
311
+ writeRepoConnection(projectRoot, {
312
+ selected: repo.selected,
313
+ ...repo.project ? { project: repo.project } : {},
314
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
315
+ });
257
316
  }
258
317
  var init__connection_state = __esm(() => {
259
318
  init_runner();
@@ -277,12 +336,16 @@ __export(exports__server_client, {
277
336
  respondRunPiExtensionUiViaServer: () => respondRunPiExtensionUiViaServer,
278
337
  resolveServerConnectionLabel: () => resolveServerConnectionLabel,
279
338
  requestServerJson: () => requestServerJson,
339
+ repairRemoteProjectRootLink: () => repairRemoteProjectRootLink,
280
340
  registerProjectViaServer: () => registerProjectViaServer,
281
341
  prepareRemoteCheckoutViaServer: () => prepareRemoteCheckoutViaServer,
282
342
  postGitHubTokenViaServer: () => postGitHubTokenViaServer,
343
+ normalizeRepoSlug: () => normalizeRepoSlug,
283
344
  listWorkspaceTasksViaServer: () => listWorkspaceTasksViaServer,
284
345
  listRunsViaServer: () => listRunsViaServer,
285
346
  listGitHubProjectsViaServer: () => listGitHubProjectsViaServer,
347
+ isRemoteProjectRootLinkError: () => isRemoteProjectRootLinkError,
348
+ inspectRemoteProjectLink: () => inspectRemoteProjectLink,
286
349
  getWorkspaceTaskViaServer: () => getWorkspaceTaskViaServer,
287
350
  getRunTimelineViaServer: () => getRunTimelineViaServer,
288
351
  getRunPiStatusViaServer: () => getRunPiStatusViaServer,
@@ -294,13 +357,15 @@ __export(exports__server_client, {
294
357
  getRunDetailsViaServer: () => getRunDetailsViaServer,
295
358
  getGitHubProjectStatusFieldViaServer: () => getGitHubProjectStatusFieldViaServer,
296
359
  getGitHubAuthStatusViaServer: () => getGitHubAuthStatusViaServer,
360
+ formatRemoteProjectLinkHint: () => formatRemoteProjectLinkHint,
297
361
  ensureTaskLabelsViaServer: () => ensureTaskLabelsViaServer,
298
362
  ensureServerForCli: () => ensureServerForCli,
363
+ ensureRemoteProjectRootLink: () => ensureRemoteProjectRootLink,
299
364
  buildRunPiEventsWebSocketUrl: () => buildRunPiEventsWebSocketUrl,
300
365
  abortRunPiViaServer: () => abortRunPiViaServer
301
366
  });
302
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
303
- import { resolve as resolve2 } from "path";
367
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
368
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
304
369
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
305
370
  function setServerPhaseListener(listener) {
306
371
  const previous = serverPhaseListener;
@@ -346,11 +411,10 @@ function readStoredGitHubAuthToken(projectRoot) {
346
411
  const parsed = readRemoteAuthState(projectRoot);
347
412
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
348
413
  }
349
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
350
- const repo = readRepoConnection(projectRoot);
351
- const slug = repo?.project?.trim();
352
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
414
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
415
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
353
416
  return null;
417
+ const repo = readRepoConnection(projectRoot);
354
418
  const auth = readRemoteAuthState(projectRoot);
355
419
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
356
420
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -359,25 +423,426 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
359
423
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
360
424
  if (!checkoutBaseDir)
361
425
  return null;
362
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
363
- writeRepoServerProjectRoot(projectRoot, inferred);
364
- return inferred;
426
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
365
427
  }
366
428
  function readLocalConnectionFallbackToken(projectRoot) {
367
429
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
368
430
  }
431
+ function normalizeRepoSlug(value) {
432
+ const slug = value?.trim();
433
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
434
+ }
435
+ function readProjectLinkSlug(projectRoot) {
436
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
437
+ if (!existsSync2(path))
438
+ return null;
439
+ try {
440
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
441
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
442
+ return null;
443
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
444
+ } catch {
445
+ return null;
446
+ }
447
+ }
448
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
449
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
450
+ mkdirSync2(dirname2(path), { recursive: true });
451
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
452
+ `, "utf8");
453
+ }
454
+ function remoteLinkRepairCommand(repoSlug) {
455
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
456
+ }
457
+ function isRemoteProjectRootLinkError(error) {
458
+ const text = error instanceof Error ? error.message : String(error ?? "");
459
+ return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(text);
460
+ }
461
+ function formatRemoteProjectLinkHint(resolution) {
462
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
463
+ if (resolution.status === "auth_required") {
464
+ 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}` : ""}\`.`;
465
+ }
466
+ if (resolution.status === "missing_project") {
467
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
468
+ }
469
+ if (resolution.status === "not_remote")
470
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
471
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
472
+ }
473
+ function remoteProjectLinkFailure(input) {
474
+ const partial = {
475
+ status: input.status,
476
+ alias: input.alias,
477
+ baseUrl: input.baseUrl,
478
+ repoSlug: input.repoSlug
479
+ };
480
+ return {
481
+ ok: false,
482
+ ...input,
483
+ hint: formatRemoteProjectLinkHint(partial),
484
+ next: remoteLinkRepairCommand(input.repoSlug)
485
+ };
486
+ }
487
+ function remoteProjectLinkSuccess(input) {
488
+ return {
489
+ ok: true,
490
+ status: input.status,
491
+ alias: input.alias,
492
+ baseUrl: input.baseUrl,
493
+ repoSlug: input.repoSlug,
494
+ serverProjectRoot: input.serverProjectRoot,
495
+ source: input.source,
496
+ prepared: input.prepared ?? input.status === "prepared",
497
+ validated: input.validated ?? false,
498
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
499
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
500
+ next: "rig task list"
501
+ };
502
+ }
503
+ function localCheckoutPathCandidate(projectRoot, candidate) {
504
+ try {
505
+ const local = resolve2(projectRoot);
506
+ const resolved = resolve2(candidate);
507
+ return resolved === local || resolved.startsWith(`${local}/`);
508
+ } catch {
509
+ return false;
510
+ }
511
+ }
512
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
513
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
514
+ if (authToken && queryAuthFallbackEnabled())
515
+ requestUrl.searchParams.set("rt", authToken);
516
+ const response = await fetch(requestUrl, {
517
+ ...init,
518
+ headers: mergeHeaders(init.headers, authToken)
519
+ });
520
+ const text = await response.text();
521
+ const payload = text.trim().length > 0 ? (() => {
522
+ try {
523
+ return JSON.parse(text);
524
+ } catch {
525
+ return null;
526
+ }
527
+ })() : null;
528
+ return { ok: response.ok, status: response.status, payload, text };
529
+ }
530
+ function payloadError(payload, fallback) {
531
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
532
+ const record = payload;
533
+ const value = record.error ?? record.message ?? record.reason;
534
+ if (typeof value === "string" && value.trim())
535
+ return value.trim();
536
+ }
537
+ return fallback;
538
+ }
539
+ function checkoutPathsFromProjectPayload(payload) {
540
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
541
+ return [];
542
+ const project = payload.project;
543
+ if (!project || typeof project !== "object" || Array.isArray(project))
544
+ return [];
545
+ const checkouts = project.checkouts;
546
+ if (!Array.isArray(checkouts))
547
+ return [];
548
+ return [...checkouts].reverse().flatMap((entry) => {
549
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
550
+ return [];
551
+ const path = entry.path;
552
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
553
+ });
554
+ }
555
+ function checkoutPathFromPreparePayload(payload) {
556
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
557
+ return null;
558
+ const checkout = payload.checkout;
559
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
560
+ return null;
561
+ const path = checkout.path;
562
+ return typeof path === "string" && path.trim() ? path.trim() : null;
563
+ }
564
+ async function validateAndPersistRemoteRoot(input) {
565
+ const candidate = input.candidate.trim();
566
+ if (!candidate || !isAbsolute(candidate)) {
567
+ return remoteProjectLinkFailure({
568
+ status: "invalid_root",
569
+ alias: input.alias,
570
+ baseUrl: input.baseUrl,
571
+ repoSlug: input.repoSlug,
572
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
573
+ });
574
+ }
575
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
576
+ return remoteProjectLinkFailure({
577
+ status: "invalid_root",
578
+ alias: input.alias,
579
+ baseUrl: input.baseUrl,
580
+ repoSlug: input.repoSlug,
581
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
582
+ });
583
+ }
584
+ let response;
585
+ try {
586
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
587
+ method: "POST",
588
+ headers: { "content-type": "application/json" },
589
+ body: JSON.stringify({ projectRoot: candidate })
590
+ });
591
+ } catch (error) {
592
+ return remoteProjectLinkFailure({
593
+ status: "error",
594
+ alias: input.alias,
595
+ baseUrl: input.baseUrl,
596
+ repoSlug: input.repoSlug,
597
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
598
+ });
599
+ }
600
+ if (response.status === 401 || response.status === 403) {
601
+ return remoteProjectLinkFailure({
602
+ status: "auth_required",
603
+ alias: input.alias,
604
+ baseUrl: input.baseUrl,
605
+ repoSlug: input.repoSlug,
606
+ statusCode: response.status,
607
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
608
+ });
609
+ }
610
+ if (!response.ok) {
611
+ return remoteProjectLinkFailure({
612
+ status: "invalid_root",
613
+ alias: input.alias,
614
+ baseUrl: input.baseUrl,
615
+ repoSlug: input.repoSlug,
616
+ statusCode: response.status,
617
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
618
+ });
619
+ }
620
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
621
+ if (record.ok !== true) {
622
+ return remoteProjectLinkFailure({
623
+ status: "invalid_root",
624
+ alias: input.alias,
625
+ baseUrl: input.baseUrl,
626
+ repoSlug: input.repoSlug,
627
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
628
+ });
629
+ }
630
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
631
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
632
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
633
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
634
+ return remoteProjectLinkSuccess({
635
+ status,
636
+ alias: input.alias,
637
+ baseUrl: input.baseUrl,
638
+ repoSlug: input.repoSlug,
639
+ serverProjectRoot: accepted,
640
+ source: input.source,
641
+ prepared: input.prepared,
642
+ validated: true,
643
+ 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}.`
644
+ });
645
+ }
646
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
647
+ let selected;
648
+ try {
649
+ selected = resolveSelectedConnection(projectRoot);
650
+ } catch (error) {
651
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
652
+ }
653
+ if (!selected || selected.connection.kind !== "remote") {
654
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
655
+ }
656
+ const repo = readRepoConnection(projectRoot);
657
+ const explicitRepoRequested = options.repoSlug !== undefined;
658
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
659
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
660
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
661
+ const alias = selected.alias;
662
+ const baseUrl = selected.connection.baseUrl;
663
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
664
+ const mode = options.mode ?? "backfill-only";
665
+ if (explicitRepoRequested && !explicitRepoSlug) {
666
+ return remoteProjectLinkFailure({
667
+ status: "missing_project",
668
+ alias,
669
+ baseUrl,
670
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
671
+ });
672
+ }
673
+ if (!repoSlug) {
674
+ return remoteProjectLinkFailure({
675
+ status: "missing_project",
676
+ alias,
677
+ baseUrl,
678
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
679
+ });
680
+ }
681
+ const skippedCandidates = [];
682
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
683
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
684
+ if (storedRoot && storedRootMatchesResolvedRepo) {
685
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
686
+ clearRepoServerProjectRoot(projectRoot);
687
+ skippedCandidates.push(storedRoot);
688
+ } else {
689
+ const storedResult = await validateAndPersistRemoteRoot({
690
+ projectRoot,
691
+ alias,
692
+ baseUrl,
693
+ authToken,
694
+ repoSlug,
695
+ candidate: storedRoot,
696
+ source: "stored",
697
+ status: "ready"
698
+ });
699
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
700
+ return storedResult;
701
+ clearRepoServerProjectRoot(projectRoot);
702
+ skippedCandidates.push(storedRoot);
703
+ }
704
+ } else if (storedRoot) {
705
+ skippedCandidates.push(storedRoot);
706
+ }
707
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
708
+ if (authCandidate) {
709
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
710
+ if (authResult.ok || authResult.status === "auth_required")
711
+ return authResult;
712
+ }
713
+ let registryResponse;
714
+ try {
715
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
716
+ } catch (error) {
717
+ return remoteProjectLinkFailure({
718
+ status: "error",
719
+ alias,
720
+ baseUrl,
721
+ repoSlug,
722
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
723
+ });
724
+ }
725
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
726
+ return remoteProjectLinkFailure({
727
+ status: "auth_required",
728
+ alias,
729
+ baseUrl,
730
+ repoSlug,
731
+ statusCode: registryResponse.status,
732
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
733
+ });
734
+ }
735
+ if (registryResponse.ok) {
736
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
737
+ for (const candidate of candidates) {
738
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
739
+ if (result.ok || result.status === "auth_required")
740
+ return result;
741
+ skippedCandidates.push(candidate);
742
+ }
743
+ if (mode === "backfill-only") {
744
+ return remoteProjectLinkFailure({
745
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
746
+ alias,
747
+ baseUrl,
748
+ repoSlug,
749
+ 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.`,
750
+ skippedCandidates
751
+ });
752
+ }
753
+ } else if (registryResponse.status === 404) {
754
+ if (mode === "backfill-only") {
755
+ return remoteProjectLinkFailure({
756
+ status: "project_not_registered",
757
+ alias,
758
+ baseUrl,
759
+ repoSlug,
760
+ statusCode: registryResponse.status,
761
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
762
+ });
763
+ }
764
+ } else {
765
+ return remoteProjectLinkFailure({
766
+ status: "error",
767
+ alias,
768
+ baseUrl,
769
+ repoSlug,
770
+ statusCode: registryResponse.status,
771
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
772
+ skippedCandidates
773
+ });
774
+ }
775
+ let prepareResponse;
776
+ try {
777
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
778
+ method: "POST",
779
+ headers: { "content-type": "application/json" },
780
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
781
+ });
782
+ } catch (error) {
783
+ return remoteProjectLinkFailure({
784
+ status: "error",
785
+ alias,
786
+ baseUrl,
787
+ repoSlug,
788
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
789
+ });
790
+ }
791
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
792
+ return remoteProjectLinkFailure({
793
+ status: "auth_required",
794
+ alias,
795
+ baseUrl,
796
+ repoSlug,
797
+ statusCode: prepareResponse.status,
798
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
799
+ });
800
+ }
801
+ if (!prepareResponse.ok) {
802
+ return remoteProjectLinkFailure({
803
+ status: "error",
804
+ alias,
805
+ baseUrl,
806
+ repoSlug,
807
+ statusCode: prepareResponse.status,
808
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
809
+ skippedCandidates
810
+ });
811
+ }
812
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
813
+ if (!preparedPath) {
814
+ return remoteProjectLinkFailure({
815
+ status: "invalid_root",
816
+ alias,
817
+ baseUrl,
818
+ repoSlug,
819
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
820
+ skippedCandidates
821
+ });
822
+ }
823
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
824
+ }
825
+ async function inspectRemoteProjectLink(projectRoot) {
826
+ return ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only" });
827
+ }
828
+ async function repairRemoteProjectRootLink(context, options = {}) {
829
+ const resolution = await ensureRemoteProjectRootLink(context.projectRoot, { mode: options.mode ?? "prepare-if-missing", repoSlug: options.repoSlug });
830
+ if (!resolution.ok)
831
+ throw new CliError(resolution.message, 1, { hint: resolution.hint });
832
+ return resolution;
833
+ }
369
834
  async function ensureServerForCli(projectRoot) {
370
835
  try {
371
836
  const selected = resolveSelectedConnection(projectRoot);
372
837
  if (selected?.connection.kind === "remote") {
373
838
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
374
839
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
375
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
840
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
376
841
  return {
377
842
  baseUrl: selected.connection.baseUrl,
378
843
  authToken,
379
844
  connectionKind: "remote",
380
- serverProjectRoot
845
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
381
846
  };
382
847
  }
383
848
  reportServerPhase("Starting local Rig server\u2026");
@@ -395,32 +860,6 @@ async function ensureServerForCli(projectRoot) {
395
860
  throw error;
396
861
  }
397
862
  }
398
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
399
- const repo = readRepoConnection(projectRoot);
400
- const slug = repo?.project?.trim();
401
- if (!slug)
402
- return null;
403
- try {
404
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
405
- if (authToken && queryAuthFallbackEnabled())
406
- url.searchParams.set("rt", authToken);
407
- const response = await fetch(url, {
408
- headers: mergeHeaders(undefined, authToken)
409
- });
410
- if (!response.ok)
411
- return null;
412
- const payload = await response.json();
413
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
414
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
415
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
416
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
417
- if (path)
418
- writeRepoServerProjectRoot(projectRoot, path);
419
- return path;
420
- } catch {
421
- return null;
422
- }
423
- }
424
863
  function appendTaskFilterParams(url, filters) {
425
864
  if (filters.assignee)
426
865
  url.searchParams.set("assignee", filters.assignee);
@@ -521,13 +960,20 @@ function canUseRemoteWithoutProjectRoot(pathname) {
521
960
  async function requestServerJson(context, pathname, init = {}) {
522
961
  const server = await ensureServerForCli(context.projectRoot);
523
962
  const requestUrl = new URL(`${server.baseUrl}${pathname}`);
524
- if (server.connectionKind === "remote" && !server.serverProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
525
- const repo = readRepoConnection(context.projectRoot);
526
- throw new CliError(`Remote server is selected for ${repo?.project ?? "this repo"}, but this checkout has no server-host project root link.`, 1, { hint: "Run `rig init --repair` or `rig init --yes --repo owner/repo --server remote` to repair the remote project link before task/run commands." });
963
+ let scopedServerProjectRoot = server.serverProjectRoot;
964
+ if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
965
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
966
+ if (link.ok && link.serverProjectRoot) {
967
+ scopedServerProjectRoot = link.serverProjectRoot;
968
+ } else {
969
+ const repo = readRepoConnection(context.projectRoot);
970
+ const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
971
+ throw new CliError(`Remote server ${target} is selected for ${link.repoSlug ?? repo?.project ?? "this repo"}, but this checkout has no server-host project root link. ${link.message}`, 1, { hint: link.hint });
972
+ }
527
973
  }
528
974
  const headers = mergeHeaders(init.headers, server.authToken);
529
- if (server.serverProjectRoot)
530
- headers.set("x-rig-project-root", server.serverProjectRoot);
975
+ if (scopedServerProjectRoot)
976
+ headers.set("x-rig-project-root", scopedServerProjectRoot);
531
977
  if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
532
978
  requestUrl.searchParams.set("rt", server.authToken);
533
979
  }
@@ -1189,6 +1635,14 @@ function permissionAllowsPr(payload) {
1189
1635
  function isNotFoundError(error) {
1190
1636
  return /\b(404|not found)\b/i.test(message(error));
1191
1637
  }
1638
+ function isLoopbackBaseUrl(baseUrl) {
1639
+ try {
1640
+ const host = new URL(baseUrl).hostname.toLowerCase();
1641
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
1642
+ } catch {
1643
+ return false;
1644
+ }
1645
+ }
1192
1646
  function projectCheckoutReady(payload) {
1193
1647
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
1194
1648
  return null;
@@ -1243,25 +1697,37 @@ async function runFastTaskRunPreflight(context, options = {}) {
1243
1697
  }
1244
1698
  const repo = readRepoConnection(context.projectRoot);
1245
1699
  const remoteWithoutProjectLink = selectedServer?.connectionKind === "remote" && !repo?.project;
1246
- checks.push(repo ? preflightCheck("project-link", "project linked to selected server", repo.project ? "pass" : remoteWithoutProjectLink ? "fail" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : " (missing project link)"}`, remoteWithoutProjectLink ? "Run `rig init --repair` or `rig init --yes --repo owner/repo --server remote` to restore the remote project link." : "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to selected server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
1700
+ let remoteRootBlocked = false;
1701
+ checks.push(repo ? preflightCheck("project-link", "project linked to selected server", repo.project ? "pass" : remoteWithoutProjectLink ? "fail" : "warn", `${repo.selected}${repo.project ? ` -> ${repo.project}` : " (missing project link)"}`, remoteWithoutProjectLink ? "Run `rig server repair-link --repo owner/repo` or `rig init --repo owner/repo --server remote` to restore the remote project link." : "Run `rig init --yes --repo owner/repo` to record the GitHub repo slug.") : preflightCheck("project-link", "project linked to selected server", legacyServerCompatibility ? "warn" : "fail", "missing .rig/state/connection.json", "Run `rig init` or `rig server use <alias|local>`."));
1702
+ if (selectedServer?.connectionKind === "remote" && repo?.project && !selectedServer.serverProjectRoot) {
1703
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: selectedServer.authToken });
1704
+ const loopbackDevRemote = !selectedServer.authToken && isLoopbackBaseUrl(selectedServer.baseUrl);
1705
+ checks.push(preflightCheck("remote-project-root-link", "remote server checkout/root linked", link.ok ? "pass" : loopbackDevRemote ? "warn" : "fail", link.ok ? `${link.repoSlug} -> ${link.serverProjectRoot}` : link.message, link.ok ? undefined : loopbackDevRemote ? "Loopback development remotes may continue without x-rig-project-root; production remotes must run `rig server repair-link`." : link.hint));
1706
+ remoteRootBlocked = !link.ok && !loopbackDevRemote;
1707
+ }
1247
1708
  try {
1248
1709
  const auth = await request("/api/github/auth/status");
1249
1710
  checks.push(isAuthenticated(auth) ? preflightCheck("github-auth", "GitHub auth valid", "pass") : preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", "not authenticated", "Run `rig github auth import-gh` or `rig github auth token --token <token>`."));
1250
1711
  } catch (error) {
1251
1712
  checks.push(preflightCheck("github-auth", "GitHub auth valid", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix GitHub auth on the selected Rig server."));
1252
1713
  }
1253
- try {
1254
- const projection = await request("/api/workspace/task-projection");
1255
- checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
1256
- } catch (error) {
1257
- checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
1258
- }
1259
- try {
1260
- const permissions = await request("/api/github/repo/permissions");
1261
- const allowed = permissionAllowsPr(permissions);
1262
- checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
1263
- } catch (error) {
1264
- checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
1714
+ if (!remoteRootBlocked) {
1715
+ try {
1716
+ const projection = await request("/api/workspace/task-projection");
1717
+ checks.push(preflightCheck("task-projection", "task projection ready", "pass", JSON.stringify(projection).slice(0, 120)));
1718
+ } catch (error) {
1719
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", message(error), "Refresh task projection with `rig task list` before launching."));
1720
+ }
1721
+ try {
1722
+ const permissions = await request("/api/github/repo/permissions");
1723
+ const allowed = permissionAllowsPr(permissions);
1724
+ checks.push(allowed === false ? preflightCheck("github-repo-permissions", "GitHub PR permissions", "fail", JSON.stringify(permissions).slice(0, 120), "Grant the selected GitHub token permission to push branches and open PRs.") : preflightCheck("github-repo-permissions", "GitHub PR permissions", allowed === true ? "pass" : "warn", JSON.stringify(permissions).slice(0, 120), "Confirm the selected token can push branches and open PRs."));
1725
+ } catch (error) {
1726
+ checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", message(error), "Ensure the selected token can push branches and open PRs."));
1727
+ }
1728
+ } else {
1729
+ checks.push(preflightCheck("task-projection", "task projection ready", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1730
+ checks.push(preflightCheck("github-repo-permissions", "GitHub PR permissions", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1265
1731
  }
1266
1732
  if (repo?.project) {
1267
1733
  try {
@@ -1273,19 +1739,24 @@ async function runFastTaskRunPreflight(context, options = {}) {
1273
1739
  }
1274
1740
  }
1275
1741
  if (taskId) {
1276
- try {
1277
- const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
1278
- const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
1279
- checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
1280
- } catch (error) {
1281
- checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
1282
- }
1283
- try {
1284
- const runs = await request("/api/runs?limit=200");
1285
- const duplicate = activeDuplicateRun(runs, taskId);
1286
- checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
1287
- } catch (error) {
1288
- checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
1742
+ if (!remoteRootBlocked) {
1743
+ try {
1744
+ const tasks = await request(`/api/workspace/tasks?limit=200&refresh=1`);
1745
+ const found = Array.isArray(tasks) && tasks.some((task) => taskMatchesId(task, taskId));
1746
+ checks.push(found ? preflightCheck("issue", "task/issue accessible", "pass", taskId) : preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", taskId, "Confirm the issue exists and matches the configured task filters."));
1747
+ } catch (error) {
1748
+ checks.push(preflightCheck("issue", "task/issue accessible", legacyServerCompatibility ? "warn" : "fail", message(error), "Fix the task source before launching a run."));
1749
+ }
1750
+ try {
1751
+ const runs = await request("/api/runs?limit=200");
1752
+ const duplicate = activeDuplicateRun(runs, taskId);
1753
+ checks.push(duplicate ? preflightCheck("duplicate-active-run", "one active run per task", "fail", String(duplicate.runId ?? taskId), "Attach to or stop the existing run before starting another one for this task.") : preflightCheck("duplicate-active-run", "one active run per task", "pass", taskId));
1754
+ } catch (error) {
1755
+ checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", message(error), "Could not list active runs; the server will still reject conflicting runs if configured."));
1756
+ }
1757
+ } else {
1758
+ checks.push(preflightCheck("issue", "task/issue accessible", "fail", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1759
+ checks.push(preflightCheck("duplicate-active-run", "one active run per task", "warn", "skipped until remote project-root link is repaired", "Run `rig server repair-link`, then retry."));
1289
1760
  }
1290
1761
  }
1291
1762
  if ((options.runtimeAdapter ?? "pi") === "pi") {
@@ -1714,7 +2185,15 @@ var init__async_ui = __esm(() => {
1714
2185
  });
1715
2186
 
1716
2187
  // packages/cli/src/commands/_pi-frontend.ts
1717
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
2188
+ var exports__pi_frontend = {};
2189
+ __export(exports__pi_frontend, {
2190
+ shouldRequireOperatorTranscript: () => shouldRequireOperatorTranscript,
2191
+ runWithProcessExitGuard: () => runWithProcessExitGuard,
2192
+ missingOperatorTranscriptMessage: () => missingOperatorTranscriptMessage,
2193
+ buildOperatorPiEnv: () => buildOperatorPiEnv,
2194
+ attachRunBundledPiFrontend: () => attachRunBundledPiFrontend
2195
+ });
2196
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync3 } from "fs";
1718
2197
  import { homedir as homedir2, tmpdir } from "os";
1719
2198
  import { join } from "path";
1720
2199
  import { main as runPiMain } from "@earendil-works/pi-coding-agent";
@@ -1766,7 +2245,7 @@ function statusFromRunDetails(run) {
1766
2245
  async function prepareOperatorConsole(context, runId, tempSessionDir) {
1767
2246
  const server = await ensureServerForCli(context.projectRoot);
1768
2247
  const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
1769
- mkdirSync2(localCwd, { recursive: true });
2248
+ mkdirSync3(localCwd, { recursive: true });
1770
2249
  trustDroneCwd(localCwd);
1771
2250
  installRigPiTheme();
1772
2251
  let sessionFileArg = [];
@@ -1788,7 +2267,7 @@ async function prepareOperatorConsole(context, runId, tempSessionDir) {
1788
2267
  return line;
1789
2268
  }).join(`
1790
2269
  `);
1791
- writeFileSync2(localSessionPath, content);
2270
+ writeFileSync3(localSessionPath, content);
1792
2271
  sessionFileArg = ["--session", localSessionPath];
1793
2272
  }
1794
2273
  } catch {}
@@ -1804,12 +2283,12 @@ async function prepareOperatorConsole(context, runId, tempSessionDir) {
1804
2283
  function trustDroneCwd(localCwd) {
1805
2284
  try {
1806
2285
  const agentDir = join(homedir2(), ".pi", "agent");
1807
- mkdirSync2(agentDir, { recursive: true });
2286
+ mkdirSync3(agentDir, { recursive: true });
1808
2287
  const trustPath = join(agentDir, "trust.json");
1809
2288
  const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
1810
2289
  if (store[localCwd] !== true) {
1811
2290
  store[localCwd] = true;
1812
- writeFileSync2(trustPath, `${JSON.stringify(store, null, "\t")}
2291
+ writeFileSync3(trustPath, `${JSON.stringify(store, null, "\t")}
1813
2292
  `);
1814
2293
  }
1815
2294
  } catch {}
@@ -1817,15 +2296,38 @@ function trustDroneCwd(localCwd) {
1817
2296
  function installRigPiTheme() {
1818
2297
  try {
1819
2298
  const themesDir = join(homedir2(), ".pi", "agent", "themes");
1820
- mkdirSync2(themesDir, { recursive: true });
2299
+ mkdirSync3(themesDir, { recursive: true });
1821
2300
  const themePath = join(themesDir, "rig.json");
1822
2301
  const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
1823
2302
  `;
1824
2303
  if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
1825
- writeFileSync2(themePath, next);
2304
+ writeFileSync3(themePath, next);
1826
2305
  }
1827
2306
  } catch {}
1828
2307
  }
2308
+ async function runWithProcessExitGuard(body) {
2309
+ const realExit = process.exit;
2310
+ let exitCode = 0;
2311
+ let signalQuit = () => {};
2312
+ const quit = new Promise((resolve3) => {
2313
+ signalQuit = resolve3;
2314
+ });
2315
+ const guardedExit = (code) => {
2316
+ exitCode = typeof code === "number" ? code : 0;
2317
+ signalQuit();
2318
+ return;
2319
+ };
2320
+ process.exit = guardedExit;
2321
+ try {
2322
+ await Promise.race([Promise.resolve().then(body), quit]);
2323
+ } finally {
2324
+ process.exit = realExit;
2325
+ }
2326
+ return exitCode;
2327
+ }
2328
+ function runPiMainReturningOnQuit(args, options) {
2329
+ return runWithProcessExitGuard(() => runPiMain(args, options));
2330
+ }
1829
2331
  async function attachRunBundledPiFrontend(context, input) {
1830
2332
  const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1831
2333
  const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
@@ -1841,16 +2343,20 @@ async function attachRunBundledPiFrontend(context, input) {
1841
2343
  };
1842
2344
  let detached = false;
1843
2345
  try {
1844
- await runPiMain([
2346
+ const piArgs = [
1845
2347
  "--offline",
1846
2348
  "--no-extensions",
1847
2349
  "--no-skills",
1848
2350
  "--no-prompt-templates",
1849
2351
  "--no-context-files",
1850
2352
  ...sessionFileArg
1851
- ], {
1852
- extensionFactories: [piRigExtensionFactory]
1853
- });
2353
+ ];
2354
+ const piOptions = { extensionFactories: [piRigExtensionFactory] };
2355
+ if (input.returnOnQuit) {
2356
+ await runPiMainReturningOnQuit(piArgs, piOptions);
2357
+ } else {
2358
+ await runPiMain(piArgs, piOptions);
2359
+ }
1854
2360
  detached = true;
1855
2361
  } finally {
1856
2362
  restoreEnv();
@@ -2396,12 +2902,13 @@ var init__help_catalog = __esm(() => {
2396
2902
  {
2397
2903
  name: "server",
2398
2904
  summary: "Choose, inspect, and start the Rig server that owns tasks and runs.",
2399
- usage: ["rig server <status|list|add|use|start> [options]"],
2905
+ usage: ["rig server <status|list|add|use|repair-link|start> [options]"],
2400
2906
  commands: [
2401
- { command: "status", description: "Show the selected server for this repo.", primary: true },
2907
+ { command: "status", description: "Show the selected server and remote project-root link for this repo.", primary: true },
2402
2908
  { command: "use local", description: "Switch this repo to the local Rig server.", primary: true },
2403
2909
  { command: "add <alias> <url>", description: "Save a remote Rig server URL.", primary: true },
2404
2910
  { command: "use <alias>", description: "Select a saved remote server alias.", primary: true },
2911
+ { command: "repair-link [--prepare|--backfill-only] [--repo owner/repo]", description: "Backfill or prepare the selected remote's server-host checkout link.", primary: true },
2405
2912
  { command: "list", description: "List saved local/remote server aliases.", primary: true },
2406
2913
  { command: "start [--host <host>] [--port <n>]", description: "Start a local rig-server process." }
2407
2914
  ],
@@ -2409,6 +2916,7 @@ var init__help_catalog = __esm(() => {
2409
2916
  "rig server status",
2410
2917
  "rig server add prod https://where.rig-does.work",
2411
2918
  "rig server use prod",
2919
+ "rig server repair-link --repo owner/repo",
2412
2920
  "rig server use local",
2413
2921
  "rig server start --port 3773"
2414
2922
  ],
@@ -3238,390 +3746,6 @@ var init_task = __esm(() => {
3238
3746
  init__connection_state();
3239
3747
  });
3240
3748
 
3241
- // packages/cli/src/app-opentui/pi-pty-host.ts
3242
- import { fileURLToPath } from "url";
3243
- import { basename } from "path";
3244
- import { RGBA, StyledText, TextAttributes } from "@opentui/core";
3245
- import { Terminal as XtermTerminal } from "@xterm/headless";
3246
- function clampCols(cols) {
3247
- return Math.max(MIN_COLS, Math.trunc(cols || 100));
3248
- }
3249
- function clampRows(rows) {
3250
- return Math.max(MIN_ROWS, Math.min(MAX_ROWS, Math.trunc(rows || 35)));
3251
- }
3252
- function rgbaFromXtermColor(mode, value) {
3253
- if (mode === 1 || mode === 2 || mode === XTERM_COLOR_MODE_INDEXED_16 || mode === XTERM_COLOR_MODE_INDEXED_256) {
3254
- return RGBA.fromIndex(value);
3255
- }
3256
- if (mode === 3 || mode === XTERM_COLOR_MODE_RGB) {
3257
- return RGBA.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255);
3258
- }
3259
- return;
3260
- }
3261
- function textAttributesFromCell(cell) {
3262
- let attributes = TextAttributes.NONE;
3263
- if (cell.isBold())
3264
- attributes |= TextAttributes.BOLD;
3265
- if (cell.isDim())
3266
- attributes |= TextAttributes.DIM;
3267
- if (cell.isItalic())
3268
- attributes |= TextAttributes.ITALIC;
3269
- if (cell.isUnderline())
3270
- attributes |= TextAttributes.UNDERLINE;
3271
- if (cell.isBlink())
3272
- attributes |= TextAttributes.BLINK;
3273
- if (cell.isInverse())
3274
- attributes |= TextAttributes.INVERSE;
3275
- if (cell.isInvisible())
3276
- attributes |= TextAttributes.HIDDEN;
3277
- if (cell.isStrikethrough())
3278
- attributes |= TextAttributes.STRIKETHROUGH;
3279
- return attributes;
3280
- }
3281
- function sameRgba(a, b) {
3282
- if (!a && !b)
3283
- return true;
3284
- return Boolean(a && b && a.equals(b));
3285
- }
3286
- function sameStyle(a, b) {
3287
- return sameRgba(a.fg, b.fg) && sameRgba(a.bg, b.bg) && (a.attributes ?? 0) === (b.attributes ?? 0);
3288
- }
3289
- function styleFromCell(cell) {
3290
- return {
3291
- fg: rgbaFromXtermColor(cell.getFgColorMode(), cell.getFgColor()),
3292
- bg: rgbaFromXtermColor(cell.getBgColorMode(), cell.getBgColor()),
3293
- attributes: textAttributesFromCell(cell)
3294
- };
3295
- }
3296
- function lineToStyledText(line, cols) {
3297
- if (!line)
3298
- return new StyledText([{ __isChunk: true, text: "" }]);
3299
- const chunks = [];
3300
- let run = "";
3301
- let runStyle = null;
3302
- const flush = () => {
3303
- if (!run)
3304
- return;
3305
- chunks.push({
3306
- __isChunk: true,
3307
- text: run,
3308
- ...runStyle?.fg ? { fg: runStyle.fg } : {},
3309
- ...runStyle?.bg ? { bg: runStyle.bg } : {},
3310
- ...(runStyle?.attributes ?? 0) !== 0 ? { attributes: runStyle.attributes } : {}
3311
- });
3312
- run = "";
3313
- };
3314
- for (let index = 0;index < cols; index += 1) {
3315
- const cell = line.getCell(index);
3316
- if (!cell) {
3317
- if (runStyle !== null)
3318
- flush();
3319
- runStyle = null;
3320
- run += " ";
3321
- continue;
3322
- }
3323
- if (cell.getWidth() === 0)
3324
- continue;
3325
- const style = styleFromCell(cell);
3326
- if (!runStyle || !sameStyle(runStyle, style)) {
3327
- flush();
3328
- runStyle = style;
3329
- }
3330
- run += cell.getChars() || " ";
3331
- }
3332
- flush();
3333
- return new StyledText(chunks.length > 0 ? chunks : [{ __isChunk: true, text: "" }]);
3334
- }
3335
- function childCommandPrefix() {
3336
- const execName = basename(process.execPath).toLowerCase();
3337
- const currentEntry = process.argv[1];
3338
- if (execName === "bun" || execName === "bun.exe") {
3339
- return currentEntry ? [process.execPath, currentEntry, "__opentui-pi-host"] : [process.execPath, fallbackChildScriptPath];
3340
- }
3341
- return [process.execPath, "__opentui-pi-host"];
3342
- }
3343
- function withEnv(base) {
3344
- const env = {};
3345
- for (const [key, value] of Object.entries(base ?? process.env)) {
3346
- if (key === "RIG_PLAIN" || key === "RIG_CLI_PLAIN_HELP" || key === "NO_COLOR")
3347
- continue;
3348
- if (typeof value === "string")
3349
- env[key] = value;
3350
- }
3351
- return {
3352
- ...env,
3353
- TERM: "xterm-256color",
3354
- COLORTERM: "truecolor",
3355
- FORCE_COLOR: env.FORCE_COLOR ?? "1",
3356
- RIG_OPENTUI_PI_HOST: "1"
3357
- };
3358
- }
3359
- async function startPiPtyHost(options) {
3360
- activeHost?.dispose("replace");
3361
- const host = new PiPtyHost(options);
3362
- activeHost = host;
3363
- await host.start();
3364
- return host;
3365
- }
3366
-
3367
- class PiPtyHost {
3368
- runId;
3369
- projectRoot;
3370
- onSnapshot;
3371
- onExit;
3372
- onError;
3373
- terminal;
3374
- disposables = [];
3375
- decoder = new TextDecoder("utf-8");
3376
- proc = null;
3377
- pty = null;
3378
- status = "starting";
3379
- cols;
3380
- rows;
3381
- message = "starting bundled Pi";
3382
- lastResizeError = null;
3383
- exitCode;
3384
- signal;
3385
- notifyTimer = null;
3386
- lastStreamKey = "";
3387
- _disposed = false;
3388
- constructor(options) {
3389
- this.runId = options.runId;
3390
- this.projectRoot = options.projectRoot;
3391
- this.cols = clampCols(options.cols);
3392
- this.rows = clampRows(options.rows);
3393
- this.onSnapshot = options.onSnapshot;
3394
- this.onExit = options.onExit;
3395
- this.onError = options.onError;
3396
- this.terminal = new XtermTerminal({
3397
- allowProposedApi: true,
3398
- cols: this.cols,
3399
- rows: this.rows,
3400
- scrollback: 1000
3401
- });
3402
- this.registerTerminalResponders();
3403
- this.disposables.push(this.terminal.onWriteParsed(() => {
3404
- if (this._disposed)
3405
- return;
3406
- const snapshot = this.createSnapshot();
3407
- const key = snapshot.lines.join(`
3408
- `);
3409
- if (key === this.lastStreamKey)
3410
- return;
3411
- this.lastStreamKey = key;
3412
- this.onSnapshot?.(snapshot);
3413
- }));
3414
- }
3415
- get disposed() {
3416
- return this._disposed;
3417
- }
3418
- get snapshot() {
3419
- return this.createSnapshot();
3420
- }
3421
- async start() {
3422
- if (this._disposed)
3423
- throw new Error("Pi PTY host is disposed.");
3424
- if (typeof Bun.Terminal !== "function") {
3425
- throw new Error("Bun native PTY is unavailable in this runtime. Pi host requires Bun.Terminal.");
3426
- }
3427
- const spawnOptions = {
3428
- cwd: this.projectRoot,
3429
- env: withEnv(process.env),
3430
- terminal: {
3431
- cols: this.cols,
3432
- rows: this.rows,
3433
- name: "xterm-256color",
3434
- data: (_terminal, data) => this.handlePtyData(data)
3435
- }
3436
- };
3437
- const proc = Bun.spawn([
3438
- ...childCommandPrefix(),
3439
- "--run-id",
3440
- this.runId,
3441
- "--project-root",
3442
- this.projectRoot
3443
- ], spawnOptions);
3444
- if (!proc.terminal)
3445
- throw new Error("Bun did not attach a terminal to the bundled Pi child process.");
3446
- this.proc = proc;
3447
- this.pty = proc.terminal;
3448
- this.status = "running";
3449
- this.message = "bundled Pi running inside this app";
3450
- this.emitSnapshotSoon(0);
3451
- proc.exited.then((exitCode) => {
3452
- if (this._disposed)
3453
- return;
3454
- this.status = exitCode === 0 ? "exited" : "failed";
3455
- this.exitCode = exitCode;
3456
- this.signal = null;
3457
- this.message = exitCode === 0 ? "bundled Pi exited" : `bundled Pi exited with code ${exitCode}`;
3458
- const snapshot = this.createSnapshot();
3459
- this.onSnapshot?.(snapshot);
3460
- this.onExit?.(snapshot);
3461
- if (activeHost === this)
3462
- activeHost = null;
3463
- this.dispose("exit", { kill: false, notify: false });
3464
- }).catch((error) => {
3465
- if (this._disposed)
3466
- return;
3467
- this.status = "failed";
3468
- this.message = error instanceof Error ? error.message : String(error);
3469
- const snapshot = this.createSnapshot();
3470
- this.onSnapshot?.(snapshot);
3471
- this.onError?.(error, snapshot);
3472
- if (activeHost === this)
3473
- activeHost = null;
3474
- this.dispose("error", { kill: false, notify: false });
3475
- });
3476
- }
3477
- write(data) {
3478
- if (this._disposed || !this.pty)
3479
- return;
3480
- try {
3481
- this.pty.write(data);
3482
- } catch (error) {
3483
- this.status = "failed";
3484
- this.message = error instanceof Error ? error.message : String(error);
3485
- const snapshot = this.createSnapshot();
3486
- this.onSnapshot?.(snapshot);
3487
- this.onError?.(error, snapshot);
3488
- }
3489
- }
3490
- resize(cols, rows) {
3491
- const nextCols = clampCols(cols);
3492
- const nextRows = clampRows(rows);
3493
- if (nextCols === this.cols && nextRows === this.rows)
3494
- return;
3495
- this.cols = nextCols;
3496
- this.rows = nextRows;
3497
- this.terminal.resize(nextCols, nextRows);
3498
- try {
3499
- this.pty?.resize(nextCols, nextRows);
3500
- this.lastResizeError = null;
3501
- } catch (error) {
3502
- this.lastResizeError = error instanceof Error ? error.message : String(error);
3503
- }
3504
- this.emitSnapshotSoon(0);
3505
- }
3506
- detach() {
3507
- this.dispose("detach");
3508
- return this.createSnapshot("detached from bundled Pi");
3509
- }
3510
- dispose(reason = "dispose", options = {}) {
3511
- if (this._disposed)
3512
- return;
3513
- this._disposed = true;
3514
- if (this.notifyTimer)
3515
- clearTimeout(this.notifyTimer);
3516
- this.notifyTimer = null;
3517
- for (const disposable of this.disposables.splice(0)) {
3518
- try {
3519
- disposable.dispose();
3520
- } catch {}
3521
- }
3522
- if (options.kill !== false) {
3523
- try {
3524
- this.proc?.kill("SIGTERM");
3525
- } catch {}
3526
- }
3527
- try {
3528
- this.pty?.close();
3529
- } catch {}
3530
- try {
3531
- this.terminal.dispose();
3532
- } catch {}
3533
- if (activeHost === this)
3534
- activeHost = null;
3535
- if (options.notify) {
3536
- this.message = reason;
3537
- this.onSnapshot?.(this.createSnapshot(reason));
3538
- }
3539
- }
3540
- handlePtyData(data) {
3541
- if (this._disposed)
3542
- return;
3543
- const text = this.decoder.decode(data, { stream: true });
3544
- this.respondToRawTerminalQueries(text);
3545
- this.terminal.write(data);
3546
- }
3547
- emitSnapshotSoon(delayMs = SNAPSHOT_DELAY_MS) {
3548
- if (this._disposed || this.notifyTimer)
3549
- return;
3550
- this.notifyTimer = setTimeout(() => {
3551
- this.notifyTimer = null;
3552
- if (this._disposed)
3553
- return;
3554
- this.onSnapshot?.(this.createSnapshot());
3555
- }, delayMs);
3556
- }
3557
- createSnapshot(message2 = this.message) {
3558
- const buffer = this.terminal.buffer.active;
3559
- const end = buffer.length;
3560
- const start = Math.max(0, end - MAX_SNAPSHOT_LINES);
3561
- const styledStart = Math.max(start, end - this.rows - STYLED_SNAPSHOT_MARGIN);
3562
- const lines = [];
3563
- const styledLines = [];
3564
- for (let row = start;row < end; row += 1) {
3565
- const line = buffer.getLine(row);
3566
- lines.push((line?.translateToString(false) ?? "").slice(0, this.cols));
3567
- if (row >= styledStart)
3568
- styledLines[lines.length - 1] = lineToStyledText(line, this.cols);
3569
- }
3570
- while (lines.length < this.rows) {
3571
- lines.push("");
3572
- styledLines[lines.length - 1] = new StyledText([{ __isChunk: true, text: "" }]);
3573
- }
3574
- const resolvedMessage = this.lastResizeError ? `resize degraded: ${this.lastResizeError}` : message2;
3575
- return {
3576
- runId: this.runId,
3577
- status: this.status,
3578
- cols: this.cols,
3579
- rows: this.rows,
3580
- lines,
3581
- styledLines,
3582
- message: resolvedMessage,
3583
- ...this.lastResizeError ? { resizeError: this.lastResizeError } : {},
3584
- ...this.exitCode !== undefined ? { exitCode: this.exitCode } : {},
3585
- ...this.signal !== undefined ? { signal: this.signal } : {}
3586
- };
3587
- }
3588
- registerTerminalResponders() {
3589
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "c" }, (params) => {
3590
- if (params.length === 0 || params[0] === 0)
3591
- this.write("\x1B[?62;22c");
3592
- return false;
3593
- }));
3594
- this.disposables.push(this.terminal.parser.registerCsiHandler({ prefix: ">", final: "c" }, (params) => {
3595
- if (params.length === 0 || params[0] === 0)
3596
- this.write("\x1B[>0;0;0c");
3597
- return false;
3598
- }));
3599
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "n" }, (params) => {
3600
- if (params[0] === 5) {
3601
- this.write("\x1B[0n");
3602
- } else if (params[0] === 6) {
3603
- const row = this.terminal.buffer.active.cursorY + 1;
3604
- const col = this.terminal.buffer.active.cursorX + 1;
3605
- this.write(`\x1B[${row};${col}R`);
3606
- }
3607
- return false;
3608
- }));
3609
- }
3610
- respondToRawTerminalQueries(text) {
3611
- if (!text)
3612
- return;
3613
- const decrqm = /\x1b\[\?(\d+)\$p/g;
3614
- let match;
3615
- while ((match = decrqm.exec(text)) !== null) {
3616
- this.write(`\x1B[?${match[1]};2$y`);
3617
- }
3618
- }
3619
- }
3620
- var MIN_COLS = 40, MIN_ROWS = 12, MAX_ROWS = 300, MAX_SNAPSHOT_LINES = 360, STYLED_SNAPSHOT_MARGIN = 6, SNAPSHOT_DELAY_MS = 120, fallbackChildScriptPath, activeHost = null, XTERM_COLOR_MODE_INDEXED_16 = 16777216, XTERM_COLOR_MODE_INDEXED_256 = 33554432, XTERM_COLOR_MODE_RGB = 50331648;
3621
- var init_pi_pty_host = __esm(() => {
3622
- fallbackChildScriptPath = fileURLToPath(new URL("./pi-host-child.ts", import.meta.url));
3623
- });
3624
-
3625
3749
  // packages/cli/src/app-opentui/adapters/fleet.ts
3626
3750
  function normalizeRunRecord(record) {
3627
3751
  const runId = stringField(record, ["runId", "id"]);
@@ -3887,14 +4011,6 @@ function recordStep(ctx, runId, label, emitLabel) {
3887
4011
  });
3888
4012
  emitProgress(ctx, emitLabel, label);
3889
4013
  }
3890
- function settleSteps(ctx, runId) {
3891
- const now = Date.now();
3892
- const previous = currentAttachState(ctx, runId);
3893
- if (!previous?.steps)
3894
- return;
3895
- const steps = previous.steps.map((step) => step.status === "running" ? { ...step, status: "done", endedAtMs: step.endedAtMs ?? now } : step);
3896
- patchData(ctx, { piAttach: { ...previous, steps } });
3897
- }
3898
4014
  async function preparePiAttachHandoff(ctx, runId) {
3899
4015
  const cleanRunId = runId.trim();
3900
4016
  const label = `Preparing Pi ${cleanRunId.slice(0, 8)}`;
@@ -3942,85 +4058,41 @@ async function attachRunWithBundledPi(ctx, runId) {
3942
4058
  throw error;
3943
4059
  }
3944
4060
  emitStarted(ctx, label, { piAttach: { runId: cleanRunId, status: "entering-pi" } });
3945
- patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "starting bundled Pi", steps: [] } });
4061
+ patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "handing the terminal to worker Pi\u2026" } });
4062
+ const projectRoot = projectRootOf(ctx);
4063
+ const outputMode = ctx.rig?.outputMode ?? "text";
4064
+ await releaseRendererForExternalTui(ctx);
4065
+ let outcome = null;
4066
+ let attachError = null;
3946
4067
  try {
3947
- recordStep(ctx, cleanRunId, "connecting to server and fetching run transcript", label);
3948
- await preparePiAttachHandoff(ctx, cleanRunId).catch((error) => {
3949
- patchData(ctx, { lastRefreshError: normalizeAppError(error).message });
3950
- return null;
3951
- });
3952
- recordStep(ctx, cleanRunId, "spawning Bun PTY host for bundled Pi", label);
3953
- const projectRoot = projectRootOf(ctx);
3954
- const cols = typeof process.stdout.columns === "number" ? process.stdout.columns : 100;
3955
- const rows = Math.max(1, (typeof process.stdout.rows === "number" ? process.stdout.rows : 35) - 1);
3956
- const patchTerminal = (snapshot) => {
3957
- const previousSteps = currentAttachState(ctx, cleanRunId)?.steps;
3958
- const failed = snapshot.status === "failed";
3959
- const reason = failed ? snapshot.message ?? `bundled Pi exited with code ${snapshot.exitCode ?? "unknown"}` : undefined;
3960
- patchData(ctx, {
3961
- piTerminal: snapshot,
3962
- piAttach: {
3963
- runId: cleanRunId,
3964
- status: failed ? "failed" : snapshot.status === "exited" ? "returned" : "entering-pi",
3965
- message: snapshot.message ?? "bundled Pi running",
3966
- result: { runId: cleanRunId, status: snapshot.status, exitCode: snapshot.exitCode },
3967
- ...previousSteps ? { steps: previousSteps } : {},
3968
- ...reason ? { failureReason: reason } : {}
3969
- }
3970
- });
3971
- };
3972
- recordStep(ctx, cleanRunId, "starting bundled Pi", label);
3973
- await startPiPtyHost({
3974
- runId: cleanRunId,
3975
- projectRoot,
3976
- cols,
3977
- rows,
3978
- onSnapshot: (snapshot) => {
3979
- if (snapshot.status === "running" && snapshot.lines.some((entry) => entry.trim().length > 0)) {
3980
- settleSteps(ctx, cleanRunId);
3981
- }
3982
- patchTerminal(snapshot);
3983
- },
3984
- onExit: (snapshot) => {
3985
- patchTerminal(snapshot);
3986
- if (snapshot.status === "failed") {
3987
- Promise.resolve().then(() => (init_inspect(), exports_inspect)).then(({ loadInspect: loadInspect2 }) => loadInspect2(ctx, cleanRunId)).catch(() => null);
3988
- emitFailed(ctx, label, new Error(snapshot.message ?? `bundled Pi exited with code ${snapshot.exitCode ?? "unknown"}`), { runId: cleanRunId, result: { status: snapshot.status, exitCode: snapshot.exitCode } });
3989
- return;
3990
- }
3991
- emitCompleted(ctx, label, { runId: cleanRunId, result: { status: snapshot.status, exitCode: snapshot.exitCode } });
3992
- ctx.emit({ type: "scene.change", scene: "fleet", intent: { scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } } });
3993
- refreshFleet(ctx).catch((error) => emitFailed(ctx, "Refresh runs", error));
3994
- },
3995
- onError: (error, snapshot) => {
3996
- patchTerminal(snapshot);
3997
- emitFailed(ctx, label, error, { runId: cleanRunId });
3998
- }
3999
- });
4000
- const record = {
4001
- runId: cleanRunId,
4002
- status: "running",
4003
- rendered: "bundled Pi embedded via Bun.Terminal + @xterm/headless"
4004
- };
4005
- emitProgress(ctx, label, "bundled Pi is running", { piAttach: { runId: cleanRunId, status: "entering-pi", message: "bundled Pi running", result: record } });
4006
- return record;
4068
+ const { attachRunBundledPiFrontend: attachRunBundledPiFrontend2 } = await Promise.resolve().then(() => (init__pi_frontend(), exports__pi_frontend));
4069
+ outcome = await attachRunBundledPiFrontend2({ projectRoot, outputMode }, { runId: cleanRunId, returnOnQuit: true });
4007
4070
  } catch (error) {
4008
- const reason = error instanceof Error ? error.message : String(error);
4071
+ attachError = error;
4072
+ } finally {
4073
+ await resumeRendererAfterExternalTui(ctx);
4074
+ }
4075
+ if (attachError) {
4076
+ const reason = normalizeAppError(attachError).message;
4009
4077
  patchData(ctx, {
4010
- piAttach: {
4011
- runId: cleanRunId,
4012
- status: "failed",
4013
- message: reason,
4014
- failureReason: reason,
4015
- ...currentAttachState(ctx, cleanRunId)?.steps ? { steps: currentAttachState(ctx, cleanRunId).steps } : {}
4016
- }
4078
+ piTerminal: undefined,
4079
+ piAttach: { runId: cleanRunId, status: "failed", message: reason, failureReason: reason }
4017
4080
  });
4018
- emitFailed(ctx, label, error, { runId: cleanRunId });
4019
- throw error;
4081
+ Promise.resolve().then(() => (init_inspect(), exports_inspect)).then(({ loadInspect: loadInspect2 }) => loadInspect2(ctx, cleanRunId)).catch(() => null);
4082
+ emitFailed(ctx, label, attachError, { runId: cleanRunId });
4083
+ throw attachError;
4020
4084
  }
4085
+ const detached = outcome?.detached === true;
4086
+ patchData(ctx, {
4087
+ piTerminal: undefined,
4088
+ piAttach: { runId: cleanRunId, status: "returned", message: detached ? "detached from worker Pi" : "returned from worker Pi" }
4089
+ });
4090
+ emitCompleted(ctx, label, { runId: cleanRunId, result: { runId: cleanRunId, detached } });
4091
+ ctx.emit({ type: "scene.change", scene: "fleet", intent: { scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } } });
4092
+ refreshFleet(ctx).catch((error) => emitFailed(ctx, "Refresh runs", error));
4093
+ return { runId: cleanRunId, status: "returned", detached };
4021
4094
  }
4022
4095
  var init_pi_attach = __esm(() => {
4023
- init_pi_pty_host();
4024
4096
  init_fleet();
4025
4097
  });
4026
4098