@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
@@ -57,6 +57,21 @@ function patchData(ctx, data) {
57
57
  function patchFooter(ctx, footer) {
58
58
  ctx.emit({ type: "footer.patch", footer });
59
59
  }
60
+ async function releaseRendererForExternalTui(ctx) {
61
+ const renderer = ctx.renderer;
62
+ if (!renderer)
63
+ return;
64
+ if (renderer.suspend) {
65
+ await renderer.suspend();
66
+ return;
67
+ }
68
+ if (renderer.destroy) {
69
+ await renderer.destroy();
70
+ }
71
+ }
72
+ async function resumeRendererAfterExternalTui(ctx) {
73
+ await ctx.renderer?.resume?.();
74
+ }
60
75
  function arrayFromPayload(value) {
61
76
  if (Array.isArray(value)) {
62
77
  return value.filter((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry)));
@@ -168,12 +183,28 @@ function readRepoConnection(projectRoot) {
168
183
  selected,
169
184
  project: typeof record.project === "string" ? record.project : undefined,
170
185
  linkedAt: typeof record.linkedAt === "string" ? record.linkedAt : undefined,
171
- serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined
186
+ serverProjectRoot: typeof record.serverProjectRoot === "string" && record.serverProjectRoot.trim() ? record.serverProjectRoot.trim() : undefined,
187
+ serverProjectRootAlias: typeof record.serverProjectRootAlias === "string" && record.serverProjectRootAlias.trim() ? record.serverProjectRootAlias.trim() : undefined,
188
+ serverProjectRootBaseUrl: typeof record.serverProjectRootBaseUrl === "string" && record.serverProjectRootBaseUrl.trim() ? record.serverProjectRootBaseUrl.trim().replace(/\/+$/, "") : undefined
172
189
  };
173
190
  }
174
191
  function writeRepoConnection(projectRoot, state) {
175
192
  writeJsonFile(resolveRepoConnectionPath(projectRoot), state);
176
193
  }
194
+ function rootAllowedForSelection(repo, connection) {
195
+ const root = repo.serverProjectRoot?.trim();
196
+ if (!root)
197
+ return;
198
+ if (connection.kind === "remote") {
199
+ if (repo.serverProjectRootAlias !== repo.selected)
200
+ return;
201
+ if (repo.serverProjectRootBaseUrl !== connection.baseUrl)
202
+ return;
203
+ } else if (repo.serverProjectRootAlias && repo.serverProjectRootAlias !== repo.selected) {
204
+ return;
205
+ }
206
+ return root;
207
+ }
177
208
  function resolveSelectedConnection(projectRoot, options = {}) {
178
209
  const repo = readRepoConnection(projectRoot);
179
210
  if (!repo)
@@ -185,13 +216,41 @@ function resolveSelectedConnection(projectRoot, options = {}) {
185
216
  if (!connection) {
186
217
  throw new CliError(`Selected Rig server "${repo.selected}" was not found. Run \`rig server list\` or \`rig server use local\`.`, 1);
187
218
  }
188
- return { alias: repo.selected, connection, serverProjectRoot: repo.serverProjectRoot };
219
+ return { alias: repo.selected, connection, serverProjectRoot: rootAllowedForSelection(repo, connection) };
189
220
  }
190
- function writeRepoServerProjectRoot(projectRoot, serverProjectRoot) {
221
+ function writeRepoServerProjectRoot(projectRoot, serverProjectRoot, metadata = {}) {
191
222
  const repo = readRepoConnection(projectRoot);
192
223
  if (!repo)
193
224
  return;
194
- writeRepoConnection(projectRoot, { ...repo, serverProjectRoot });
225
+ let inferred = metadata;
226
+ if (!inferred.alias || !inferred.baseUrl) {
227
+ try {
228
+ const selected = resolveSelectedConnection(projectRoot);
229
+ if (selected?.connection.kind === "remote") {
230
+ inferred = {
231
+ alias: inferred.alias ?? selected.alias,
232
+ baseUrl: inferred.baseUrl ?? selected.connection.baseUrl
233
+ };
234
+ }
235
+ } catch {}
236
+ }
237
+ writeRepoConnection(projectRoot, {
238
+ ...repo,
239
+ ...metadata.project ? { project: metadata.project } : {},
240
+ serverProjectRoot,
241
+ ...inferred.alias ? { serverProjectRootAlias: inferred.alias } : {},
242
+ ...inferred.baseUrl ? { serverProjectRootBaseUrl: inferred.baseUrl.replace(/\/+$/, "") } : {}
243
+ });
244
+ }
245
+ function clearRepoServerProjectRoot(projectRoot) {
246
+ const repo = readRepoConnection(projectRoot);
247
+ if (!repo)
248
+ return;
249
+ writeRepoConnection(projectRoot, {
250
+ selected: repo.selected,
251
+ ...repo.project ? { project: repo.project } : {},
252
+ ...repo.linkedAt ? { linkedAt: repo.linkedAt } : {}
253
+ });
195
254
  }
196
255
  var init__connection_state = __esm(() => {
197
256
  init_runner();
@@ -215,12 +274,16 @@ __export(exports__server_client, {
215
274
  respondRunPiExtensionUiViaServer: () => respondRunPiExtensionUiViaServer,
216
275
  resolveServerConnectionLabel: () => resolveServerConnectionLabel,
217
276
  requestServerJson: () => requestServerJson,
277
+ repairRemoteProjectRootLink: () => repairRemoteProjectRootLink,
218
278
  registerProjectViaServer: () => registerProjectViaServer,
219
279
  prepareRemoteCheckoutViaServer: () => prepareRemoteCheckoutViaServer,
220
280
  postGitHubTokenViaServer: () => postGitHubTokenViaServer,
281
+ normalizeRepoSlug: () => normalizeRepoSlug,
221
282
  listWorkspaceTasksViaServer: () => listWorkspaceTasksViaServer,
222
283
  listRunsViaServer: () => listRunsViaServer,
223
284
  listGitHubProjectsViaServer: () => listGitHubProjectsViaServer,
285
+ isRemoteProjectRootLinkError: () => isRemoteProjectRootLinkError,
286
+ inspectRemoteProjectLink: () => inspectRemoteProjectLink,
224
287
  getWorkspaceTaskViaServer: () => getWorkspaceTaskViaServer,
225
288
  getRunTimelineViaServer: () => getRunTimelineViaServer,
226
289
  getRunPiStatusViaServer: () => getRunPiStatusViaServer,
@@ -232,13 +295,15 @@ __export(exports__server_client, {
232
295
  getRunDetailsViaServer: () => getRunDetailsViaServer,
233
296
  getGitHubProjectStatusFieldViaServer: () => getGitHubProjectStatusFieldViaServer,
234
297
  getGitHubAuthStatusViaServer: () => getGitHubAuthStatusViaServer,
298
+ formatRemoteProjectLinkHint: () => formatRemoteProjectLinkHint,
235
299
  ensureTaskLabelsViaServer: () => ensureTaskLabelsViaServer,
236
300
  ensureServerForCli: () => ensureServerForCli,
301
+ ensureRemoteProjectRootLink: () => ensureRemoteProjectRootLink,
237
302
  buildRunPiEventsWebSocketUrl: () => buildRunPiEventsWebSocketUrl,
238
303
  abortRunPiViaServer: () => abortRunPiViaServer
239
304
  });
240
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
241
- import { resolve as resolve2 } from "path";
305
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
306
+ import { dirname as dirname2, isAbsolute, resolve as resolve2 } from "path";
242
307
  import { ensureLocalRigServerConnection } from "@rig/runtime/local-server";
243
308
  function setServerPhaseListener(listener) {
244
309
  const previous = serverPhaseListener;
@@ -284,11 +349,10 @@ function readStoredGitHubAuthToken(projectRoot) {
284
349
  const parsed = readRemoteAuthState(projectRoot);
285
350
  return parsed ? cleanToken(typeof parsed.token === "string" ? parsed.token : undefined) : null;
286
351
  }
287
- function inferRemoteServerProjectRootFromAuthState(projectRoot) {
288
- const repo = readRepoConnection(projectRoot);
289
- const slug = repo?.project?.trim();
290
- if (!slug || !/^[^/]+\/[^/]+$/.test(slug))
352
+ function inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug) {
353
+ if (!/^[^/]+\/[^/]+$/.test(repoSlug))
291
354
  return null;
355
+ const repo = readRepoConnection(projectRoot);
292
356
  const auth = readRemoteAuthState(projectRoot);
293
357
  const authUpdatedAt = typeof auth?.updatedAt === "string" ? Date.parse(auth.updatedAt) : Number.NaN;
294
358
  const repoLinkedAt = typeof repo?.linkedAt === "string" ? Date.parse(repo.linkedAt) : Number.NaN;
@@ -297,25 +361,426 @@ function inferRemoteServerProjectRootFromAuthState(projectRoot) {
297
361
  const checkoutBaseDir = typeof auth?.checkoutBaseDir === "string" && auth.checkoutBaseDir.trim() ? auth.checkoutBaseDir.trim() : null;
298
362
  if (!checkoutBaseDir)
299
363
  return null;
300
- const inferred = `${checkoutBaseDir.replace(/\/+$/, "")}/${slug}`;
301
- writeRepoServerProjectRoot(projectRoot, inferred);
302
- return inferred;
364
+ return `${checkoutBaseDir.replace(/\/+$/, "")}/${repoSlug}`;
303
365
  }
304
366
  function readLocalConnectionFallbackToken(projectRoot) {
305
367
  return readGitHubBearerTokenForRemote(projectRoot) ?? cleanToken(process.env.RIG_GITHUB_TOKEN) ?? readStoredGitHubAuthToken(projectRoot);
306
368
  }
369
+ function normalizeRepoSlug(value) {
370
+ const slug = value?.trim();
371
+ return slug && /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
372
+ }
373
+ function readProjectLinkSlug(projectRoot) {
374
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
375
+ if (!existsSync2(path))
376
+ return null;
377
+ try {
378
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
379
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
380
+ return null;
381
+ return normalizeRepoSlug(typeof parsed.repoSlug === "string" ? String(parsed.repoSlug) : null);
382
+ } catch {
383
+ return null;
384
+ }
385
+ }
386
+ function writeProjectLinkConnection(projectRoot, repoSlug, alias) {
387
+ const path = resolve2(projectRoot, ".rig", "state", "project-link.json");
388
+ mkdirSync2(dirname2(path), { recursive: true });
389
+ writeFileSync2(path, `${JSON.stringify({ repoSlug, connection: alias, linkedAt: new Date().toISOString() }, null, 2)}
390
+ `, "utf8");
391
+ }
392
+ function remoteLinkRepairCommand(repoSlug) {
393
+ return repoSlug ? `rig server repair-link --repo ${repoSlug}` : "rig server repair-link --repo owner/repo";
394
+ }
395
+ function isRemoteProjectRootLinkError(error) {
396
+ const text = error instanceof Error ? error.message : String(error ?? "");
397
+ return /no server-host project root link|remote project(?:-root)? link|x-rig-project-root|serverProjectRoot/i.test(text);
398
+ }
399
+ function formatRemoteProjectLinkHint(resolution) {
400
+ const repair = remoteLinkRepairCommand(resolution.repoSlug);
401
+ if (resolution.status === "auth_required") {
402
+ 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}` : ""}\`.`;
403
+ }
404
+ if (resolution.status === "missing_project") {
405
+ return `Record the repo slug, then run \`${repair}\` (or \`rig init --repo owner/repo --server remote --github-auth device\`).`;
406
+ }
407
+ if (resolution.status === "not_remote")
408
+ return "Select a remote server with `rig server use <alias>` before repairing a remote project link.";
409
+ return `Run \`${repair}\` to backfill or prepare a server-host checkout for the selected remote${resolution.alias ? ` (${resolution.alias})` : ""}.`;
410
+ }
411
+ function remoteProjectLinkFailure(input) {
412
+ const partial = {
413
+ status: input.status,
414
+ alias: input.alias,
415
+ baseUrl: input.baseUrl,
416
+ repoSlug: input.repoSlug
417
+ };
418
+ return {
419
+ ok: false,
420
+ ...input,
421
+ hint: formatRemoteProjectLinkHint(partial),
422
+ next: remoteLinkRepairCommand(input.repoSlug)
423
+ };
424
+ }
425
+ function remoteProjectLinkSuccess(input) {
426
+ return {
427
+ ok: true,
428
+ status: input.status,
429
+ alias: input.alias,
430
+ baseUrl: input.baseUrl,
431
+ repoSlug: input.repoSlug,
432
+ serverProjectRoot: input.serverProjectRoot,
433
+ source: input.source,
434
+ prepared: input.prepared ?? input.status === "prepared",
435
+ validated: input.validated ?? false,
436
+ message: input.message ?? `Remote project link ready for ${input.repoSlug}.`,
437
+ hint: "Remote-scoped task/run/status requests will send x-rig-project-root for this server-host checkout.",
438
+ next: "rig task list"
439
+ };
440
+ }
441
+ function localCheckoutPathCandidate(projectRoot, candidate) {
442
+ try {
443
+ const local = resolve2(projectRoot);
444
+ const resolved = resolve2(candidate);
445
+ return resolved === local || resolved.startsWith(`${local}/`);
446
+ } catch {
447
+ return false;
448
+ }
449
+ }
450
+ async function requestRemoteProjectLinkJson(baseUrl, pathname, authToken, init = {}) {
451
+ const requestUrl = new URL(`${baseUrl}${pathname}`);
452
+ if (authToken && queryAuthFallbackEnabled())
453
+ requestUrl.searchParams.set("rt", authToken);
454
+ const response = await fetch(requestUrl, {
455
+ ...init,
456
+ headers: mergeHeaders(init.headers, authToken)
457
+ });
458
+ const text = await response.text();
459
+ const payload = text.trim().length > 0 ? (() => {
460
+ try {
461
+ return JSON.parse(text);
462
+ } catch {
463
+ return null;
464
+ }
465
+ })() : null;
466
+ return { ok: response.ok, status: response.status, payload, text };
467
+ }
468
+ function payloadError(payload, fallback) {
469
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
470
+ const record = payload;
471
+ const value = record.error ?? record.message ?? record.reason;
472
+ if (typeof value === "string" && value.trim())
473
+ return value.trim();
474
+ }
475
+ return fallback;
476
+ }
477
+ function checkoutPathsFromProjectPayload(payload) {
478
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
479
+ return [];
480
+ const project = payload.project;
481
+ if (!project || typeof project !== "object" || Array.isArray(project))
482
+ return [];
483
+ const checkouts = project.checkouts;
484
+ if (!Array.isArray(checkouts))
485
+ return [];
486
+ return [...checkouts].reverse().flatMap((entry) => {
487
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
488
+ return [];
489
+ const path = entry.path;
490
+ return typeof path === "string" && path.trim() ? [path.trim()] : [];
491
+ });
492
+ }
493
+ function checkoutPathFromPreparePayload(payload) {
494
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
495
+ return null;
496
+ const checkout = payload.checkout;
497
+ if (!checkout || typeof checkout !== "object" || Array.isArray(checkout))
498
+ return null;
499
+ const path = checkout.path;
500
+ return typeof path === "string" && path.trim() ? path.trim() : null;
501
+ }
502
+ async function validateAndPersistRemoteRoot(input) {
503
+ const candidate = input.candidate.trim();
504
+ if (!candidate || !isAbsolute(candidate)) {
505
+ return remoteProjectLinkFailure({
506
+ status: "invalid_root",
507
+ alias: input.alias,
508
+ baseUrl: input.baseUrl,
509
+ repoSlug: input.repoSlug,
510
+ message: `Remote project root candidate is not an absolute server-host path: ${candidate || "(empty)"}.`
511
+ });
512
+ }
513
+ if (localCheckoutPathCandidate(input.projectRoot, candidate)) {
514
+ return remoteProjectLinkFailure({
515
+ status: "invalid_root",
516
+ alias: input.alias,
517
+ baseUrl: input.baseUrl,
518
+ repoSlug: input.repoSlug,
519
+ message: `Refusing to use local checkout path ${candidate} as a remote server project root.`
520
+ });
521
+ }
522
+ let response;
523
+ try {
524
+ response = await requestRemoteProjectLinkJson(input.baseUrl, "/api/server/project-root", input.authToken, {
525
+ method: "POST",
526
+ headers: { "content-type": "application/json" },
527
+ body: JSON.stringify({ projectRoot: candidate })
528
+ });
529
+ } catch (error) {
530
+ return remoteProjectLinkFailure({
531
+ status: "error",
532
+ alias: input.alias,
533
+ baseUrl: input.baseUrl,
534
+ repoSlug: input.repoSlug,
535
+ message: `Could not validate remote project root ${candidate}: ${error instanceof Error ? error.message : String(error)}`
536
+ });
537
+ }
538
+ if (response.status === 401 || response.status === 403) {
539
+ return remoteProjectLinkFailure({
540
+ status: "auth_required",
541
+ alias: input.alias,
542
+ baseUrl: input.baseUrl,
543
+ repoSlug: input.repoSlug,
544
+ statusCode: response.status,
545
+ message: `Remote server ${input.alias} requires authentication before validating project root ${candidate}.`
546
+ });
547
+ }
548
+ if (!response.ok) {
549
+ return remoteProjectLinkFailure({
550
+ status: "invalid_root",
551
+ alias: input.alias,
552
+ baseUrl: input.baseUrl,
553
+ repoSlug: input.repoSlug,
554
+ statusCode: response.status,
555
+ message: `Remote server rejected project root ${candidate} (${response.status}): ${payloadError(response.payload, response.text || "project-root validation failed")}`
556
+ });
557
+ }
558
+ const record = response.payload && typeof response.payload === "object" && !Array.isArray(response.payload) ? response.payload : {};
559
+ if (record.ok !== true) {
560
+ return remoteProjectLinkFailure({
561
+ status: "invalid_root",
562
+ alias: input.alias,
563
+ baseUrl: input.baseUrl,
564
+ repoSlug: input.repoSlug,
565
+ message: `Remote server did not accept project root ${candidate}: ${payloadError(response.payload, "project-root validation failed")}`
566
+ });
567
+ }
568
+ const accepted = typeof record.projectRoot === "string" && record.projectRoot.trim() ? record.projectRoot.trim() : typeof record.requestedProjectRoot === "string" && record.requestedProjectRoot.trim() ? record.requestedProjectRoot.trim() : candidate;
569
+ writeRepoServerProjectRoot(input.projectRoot, accepted, { alias: input.alias, baseUrl: input.baseUrl, project: input.repoSlug });
570
+ writeProjectLinkConnection(input.projectRoot, input.repoSlug, input.alias);
571
+ const status = input.status ?? (input.prepared ? "prepared" : "backfilled");
572
+ return remoteProjectLinkSuccess({
573
+ status,
574
+ alias: input.alias,
575
+ baseUrl: input.baseUrl,
576
+ repoSlug: input.repoSlug,
577
+ serverProjectRoot: accepted,
578
+ source: input.source,
579
+ prepared: input.prepared,
580
+ validated: true,
581
+ 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}.`
582
+ });
583
+ }
584
+ async function ensureRemoteProjectRootLink(projectRoot, options = {}) {
585
+ let selected;
586
+ try {
587
+ selected = resolveSelectedConnection(projectRoot);
588
+ } catch (error) {
589
+ return remoteProjectLinkFailure({ status: "error", message: error instanceof Error ? error.message : String(error) });
590
+ }
591
+ if (!selected || selected.connection.kind !== "remote") {
592
+ return remoteProjectLinkFailure({ status: "not_remote", message: "No remote Rig server is selected for this repo." });
593
+ }
594
+ const repo = readRepoConnection(projectRoot);
595
+ const explicitRepoRequested = options.repoSlug !== undefined;
596
+ const explicitRepoSlug = explicitRepoRequested ? normalizeRepoSlug(options.repoSlug) : null;
597
+ const repoProjectSlug = normalizeRepoSlug(repo?.project);
598
+ const repoSlug = explicitRepoSlug ?? repoProjectSlug ?? readProjectLinkSlug(projectRoot);
599
+ const alias = selected.alias;
600
+ const baseUrl = selected.connection.baseUrl;
601
+ const authToken = options.authToken === undefined ? readGitHubBearerTokenForRemote(projectRoot) : options.authToken;
602
+ const mode = options.mode ?? "backfill-only";
603
+ if (explicitRepoRequested && !explicitRepoSlug) {
604
+ return remoteProjectLinkFailure({
605
+ status: "missing_project",
606
+ alias,
607
+ baseUrl,
608
+ message: `Invalid --repo value ${JSON.stringify(options.repoSlug)}. Expected owner/repo.`
609
+ });
610
+ }
611
+ if (!repoSlug) {
612
+ return remoteProjectLinkFailure({
613
+ status: "missing_project",
614
+ alias,
615
+ baseUrl,
616
+ message: `Remote server ${alias} is selected, but this checkout has no GitHub repo slug recorded.`
617
+ });
618
+ }
619
+ const skippedCandidates = [];
620
+ const storedRoot = selected.serverProjectRoot?.trim() || null;
621
+ const storedRootMatchesResolvedRepo = repoProjectSlug === repoSlug;
622
+ if (storedRoot && storedRootMatchesResolvedRepo) {
623
+ if (localCheckoutPathCandidate(projectRoot, storedRoot)) {
624
+ clearRepoServerProjectRoot(projectRoot);
625
+ skippedCandidates.push(storedRoot);
626
+ } else {
627
+ const storedResult = await validateAndPersistRemoteRoot({
628
+ projectRoot,
629
+ alias,
630
+ baseUrl,
631
+ authToken,
632
+ repoSlug,
633
+ candidate: storedRoot,
634
+ source: "stored",
635
+ status: "ready"
636
+ });
637
+ if (storedResult.ok || storedResult.status === "auth_required" || storedResult.status === "error")
638
+ return storedResult;
639
+ clearRepoServerProjectRoot(projectRoot);
640
+ skippedCandidates.push(storedRoot);
641
+ }
642
+ } else if (storedRoot) {
643
+ skippedCandidates.push(storedRoot);
644
+ }
645
+ const authCandidate = inferRemoteServerProjectRootCandidateFromAuthState(projectRoot, repoSlug);
646
+ if (authCandidate) {
647
+ const authResult = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: authCandidate, source: "auth-state" });
648
+ if (authResult.ok || authResult.status === "auth_required")
649
+ return authResult;
650
+ }
651
+ let registryResponse;
652
+ try {
653
+ registryResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}`, authToken);
654
+ } catch (error) {
655
+ return remoteProjectLinkFailure({
656
+ status: "error",
657
+ alias,
658
+ baseUrl,
659
+ repoSlug,
660
+ message: `Could not read remote project registry for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
661
+ });
662
+ }
663
+ if (registryResponse.status === 401 || registryResponse.status === 403) {
664
+ return remoteProjectLinkFailure({
665
+ status: "auth_required",
666
+ alias,
667
+ baseUrl,
668
+ repoSlug,
669
+ statusCode: registryResponse.status,
670
+ message: `Remote server ${alias} requires authentication before reading the ${repoSlug} project registry.`
671
+ });
672
+ }
673
+ if (registryResponse.ok) {
674
+ const candidates = checkoutPathsFromProjectPayload(registryResponse.payload);
675
+ for (const candidate of candidates) {
676
+ const result = await validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate, source: "registry" });
677
+ if (result.ok || result.status === "auth_required")
678
+ return result;
679
+ skippedCandidates.push(candidate);
680
+ }
681
+ if (mode === "backfill-only") {
682
+ return remoteProjectLinkFailure({
683
+ status: candidates.length > 0 ? "invalid_root" : "no_server_checkout",
684
+ alias,
685
+ baseUrl,
686
+ repoSlug,
687
+ 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.`,
688
+ skippedCandidates
689
+ });
690
+ }
691
+ } else if (registryResponse.status === 404) {
692
+ if (mode === "backfill-only") {
693
+ return remoteProjectLinkFailure({
694
+ status: "project_not_registered",
695
+ alias,
696
+ baseUrl,
697
+ repoSlug,
698
+ statusCode: registryResponse.status,
699
+ message: `Remote server ${alias} has no registered project record for ${repoSlug}.`
700
+ });
701
+ }
702
+ } else {
703
+ return remoteProjectLinkFailure({
704
+ status: "error",
705
+ alias,
706
+ baseUrl,
707
+ repoSlug,
708
+ statusCode: registryResponse.status,
709
+ message: `Could not backfill ${repoSlug} from remote registry (${registryResponse.status}): ${payloadError(registryResponse.payload, registryResponse.text || "registry lookup failed")}`,
710
+ skippedCandidates
711
+ });
712
+ }
713
+ let prepareResponse;
714
+ try {
715
+ prepareResponse = await requestRemoteProjectLinkJson(baseUrl, `/api/projects/${encodeURIComponent(repoSlug)}/prepare-checkout`, authToken, {
716
+ method: "POST",
717
+ headers: { "content-type": "application/json" },
718
+ body: JSON.stringify({ checkout: { kind: "managed-clone" }, repoUrl: `https://github.com/${repoSlug}.git` })
719
+ });
720
+ } catch (error) {
721
+ return remoteProjectLinkFailure({
722
+ status: "error",
723
+ alias,
724
+ baseUrl,
725
+ repoSlug,
726
+ message: `Could not prepare remote checkout for ${repoSlug} on ${alias}: ${error instanceof Error ? error.message : String(error)}`
727
+ });
728
+ }
729
+ if (prepareResponse.status === 401 || prepareResponse.status === 403) {
730
+ return remoteProjectLinkFailure({
731
+ status: "auth_required",
732
+ alias,
733
+ baseUrl,
734
+ repoSlug,
735
+ statusCode: prepareResponse.status,
736
+ message: `Remote server ${alias} requires authentication before preparing ${repoSlug}.`
737
+ });
738
+ }
739
+ if (!prepareResponse.ok) {
740
+ return remoteProjectLinkFailure({
741
+ status: "error",
742
+ alias,
743
+ baseUrl,
744
+ repoSlug,
745
+ statusCode: prepareResponse.status,
746
+ message: `Remote checkout prepare failed for ${repoSlug} (${prepareResponse.status}): ${payloadError(prepareResponse.payload, prepareResponse.text || "prepare-checkout failed")}`,
747
+ skippedCandidates
748
+ });
749
+ }
750
+ const preparedPath = checkoutPathFromPreparePayload(prepareResponse.payload);
751
+ if (!preparedPath) {
752
+ return remoteProjectLinkFailure({
753
+ status: "invalid_root",
754
+ alias,
755
+ baseUrl,
756
+ repoSlug,
757
+ message: `Remote checkout prepare for ${repoSlug} did not return a checkout.path.`,
758
+ skippedCandidates
759
+ });
760
+ }
761
+ return validateAndPersistRemoteRoot({ projectRoot, alias, baseUrl, authToken, repoSlug, candidate: preparedPath, source: "prepare", prepared: true });
762
+ }
763
+ async function inspectRemoteProjectLink(projectRoot) {
764
+ return ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only" });
765
+ }
766
+ async function repairRemoteProjectRootLink(context, options = {}) {
767
+ const resolution = await ensureRemoteProjectRootLink(context.projectRoot, { mode: options.mode ?? "prepare-if-missing", repoSlug: options.repoSlug });
768
+ if (!resolution.ok)
769
+ throw new CliError(resolution.message, 1, { hint: resolution.hint });
770
+ return resolution;
771
+ }
307
772
  async function ensureServerForCli(projectRoot) {
308
773
  try {
309
774
  const selected = resolveSelectedConnection(projectRoot);
310
775
  if (selected?.connection.kind === "remote") {
311
776
  reportServerPhase(`Connecting to ${selected.alias}\u2026`);
312
777
  const authToken = readGitHubBearerTokenForRemote(projectRoot);
313
- const serverProjectRoot = selected.serverProjectRoot ?? inferRemoteServerProjectRootFromAuthState(projectRoot) ?? await backfillRemoteServerProjectRoot(projectRoot, selected.connection.baseUrl, authToken);
778
+ const link = await ensureRemoteProjectRootLink(projectRoot, { mode: "backfill-only", authToken });
314
779
  return {
315
780
  baseUrl: selected.connection.baseUrl,
316
781
  authToken,
317
782
  connectionKind: "remote",
318
- serverProjectRoot
783
+ serverProjectRoot: link.ok ? link.serverProjectRoot ?? null : null
319
784
  };
320
785
  }
321
786
  reportServerPhase("Starting local Rig server\u2026");
@@ -333,32 +798,6 @@ async function ensureServerForCli(projectRoot) {
333
798
  throw error;
334
799
  }
335
800
  }
336
- async function backfillRemoteServerProjectRoot(projectRoot, baseUrl, authToken) {
337
- const repo = readRepoConnection(projectRoot);
338
- const slug = repo?.project?.trim();
339
- if (!slug)
340
- return null;
341
- try {
342
- const url = new URL(`${baseUrl}/api/projects/${encodeURIComponent(slug)}`);
343
- if (authToken && queryAuthFallbackEnabled())
344
- url.searchParams.set("rt", authToken);
345
- const response = await fetch(url, {
346
- headers: mergeHeaders(undefined, authToken)
347
- });
348
- if (!response.ok)
349
- return null;
350
- const payload = await response.json();
351
- const project = payload.project && typeof payload.project === "object" && !Array.isArray(payload.project) ? payload.project : null;
352
- const checkouts = Array.isArray(project?.checkouts) ? project.checkouts : [];
353
- const latestCheckout = [...checkouts].reverse().find((entry) => Boolean(entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.path === "string"));
354
- const path = typeof latestCheckout?.path === "string" && latestCheckout.path.trim() ? latestCheckout.path.trim() : null;
355
- if (path)
356
- writeRepoServerProjectRoot(projectRoot, path);
357
- return path;
358
- } catch {
359
- return null;
360
- }
361
- }
362
801
  function appendTaskFilterParams(url, filters) {
363
802
  if (filters.assignee)
364
803
  url.searchParams.set("assignee", filters.assignee);
@@ -459,13 +898,20 @@ function canUseRemoteWithoutProjectRoot(pathname) {
459
898
  async function requestServerJson(context, pathname, init = {}) {
460
899
  const server = await ensureServerForCli(context.projectRoot);
461
900
  const requestUrl = new URL(`${server.baseUrl}${pathname}`);
462
- if (server.connectionKind === "remote" && !server.serverProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
463
- const repo = readRepoConnection(context.projectRoot);
464
- 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." });
901
+ let scopedServerProjectRoot = server.serverProjectRoot;
902
+ if (server.connectionKind === "remote" && !scopedServerProjectRoot && !canUseRemoteWithoutProjectRoot(requestUrl.pathname) && (server.authToken || !isLoopbackRemoteBaseUrl(server.baseUrl))) {
903
+ const link = await ensureRemoteProjectRootLink(context.projectRoot, { mode: "backfill-only", authToken: server.authToken });
904
+ if (link.ok && link.serverProjectRoot) {
905
+ scopedServerProjectRoot = link.serverProjectRoot;
906
+ } else {
907
+ const repo = readRepoConnection(context.projectRoot);
908
+ const target = link.alias && link.baseUrl ? `${link.alias} (${link.baseUrl})` : server.baseUrl;
909
+ 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 });
910
+ }
465
911
  }
466
912
  const headers = mergeHeaders(init.headers, server.authToken);
467
- if (server.serverProjectRoot)
468
- headers.set("x-rig-project-root", server.serverProjectRoot);
913
+ if (scopedServerProjectRoot)
914
+ headers.set("x-rig-project-root", scopedServerProjectRoot);
469
915
  if (server.connectionKind === "remote" && server.authToken && queryAuthFallbackEnabled()) {
470
916
  requestUrl.searchParams.set("rt", server.authToken);
471
917
  }
@@ -830,6 +1276,486 @@ var init__server_client = __esm(() => {
830
1276
  ]);
831
1277
  });
832
1278
 
1279
+ // packages/cli/src/commands/_spinner.ts
1280
+ function createTtySpinner(input) {
1281
+ const output = input.output ?? process.stdout;
1282
+ const isTty = output.isTTY === true;
1283
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
1284
+ let label = input.label;
1285
+ let frame = 0;
1286
+ let paused = false;
1287
+ let stopped = false;
1288
+ let lastPrintedLabel = "";
1289
+ const render = () => {
1290
+ if (stopped || paused)
1291
+ return;
1292
+ if (!isTty) {
1293
+ if (label !== lastPrintedLabel) {
1294
+ output.write(`${label}
1295
+ `);
1296
+ lastPrintedLabel = label;
1297
+ }
1298
+ return;
1299
+ }
1300
+ frame = (frame + 1) % frames.length;
1301
+ const glyph = frames[frame] ?? frames[0] ?? "";
1302
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
1303
+ };
1304
+ const clearLine = () => {
1305
+ if (isTty)
1306
+ output.write("\r\x1B[2K");
1307
+ };
1308
+ render();
1309
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 16) : null;
1310
+ return {
1311
+ setLabel(next) {
1312
+ label = next;
1313
+ render();
1314
+ },
1315
+ pause() {
1316
+ paused = true;
1317
+ clearLine();
1318
+ },
1319
+ resume() {
1320
+ if (stopped)
1321
+ return;
1322
+ paused = false;
1323
+ render();
1324
+ },
1325
+ stop(finalLine) {
1326
+ if (stopped)
1327
+ return;
1328
+ stopped = true;
1329
+ if (timer)
1330
+ clearInterval(timer);
1331
+ clearLine();
1332
+ if (finalLine)
1333
+ output.write(`${finalLine}
1334
+ `);
1335
+ }
1336
+ };
1337
+ }
1338
+ var SPINNER_FRAMES;
1339
+ var init__spinner = __esm(() => {
1340
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1341
+ });
1342
+
1343
+ // packages/cli/src/app/theme.ts
1344
+ function hexToRgb(hex) {
1345
+ const value = hex.replace("#", "");
1346
+ return [
1347
+ Number.parseInt(value.slice(0, 2), 16),
1348
+ Number.parseInt(value.slice(2, 4), 16),
1349
+ Number.parseInt(value.slice(4, 6), 16)
1350
+ ];
1351
+ }
1352
+ function fg(hex) {
1353
+ const [r, g, b] = hexToRgb(hex);
1354
+ return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
1355
+ }
1356
+ function bold(text) {
1357
+ return `\x1B[1m${text}\x1B[22m`;
1358
+ }
1359
+ function microDroneFrame(tick) {
1360
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
1361
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
1362
+ return `(${blade})${eye}(${blade})`;
1363
+ }
1364
+ function renderMicroDroneFrame(tick) {
1365
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
1366
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
1367
+ return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
1368
+ }
1369
+ var RIG_PALETTE, ink, ink2, ink3, ink4, accent, accentDim, cyan, red, yellow, DRONE_ART, EYE_FRAMES, DRONE_WIDTH, DRONE_HEIGHT, MICRO_BLADES, MICRO_DRONE_FRAMES;
1370
+ var init_theme = __esm(() => {
1371
+ RIG_PALETTE = {
1372
+ ink: "#f2f3f6",
1373
+ ink2: "#aeb0ba",
1374
+ ink3: "#6c6e79",
1375
+ ink4: "#44464f",
1376
+ accent: "#ccff4d",
1377
+ accentDim: "#a9d63f",
1378
+ cyan: "#56d8ff",
1379
+ red: "#ff5d5d",
1380
+ yellow: "#ffd24d"
1381
+ };
1382
+ ink = fg(RIG_PALETTE.ink);
1383
+ ink2 = fg(RIG_PALETTE.ink2);
1384
+ ink3 = fg(RIG_PALETTE.ink3);
1385
+ ink4 = fg(RIG_PALETTE.ink4);
1386
+ accent = fg(RIG_PALETTE.accent);
1387
+ accentDim = fg(RIG_PALETTE.accentDim);
1388
+ cyan = fg(RIG_PALETTE.cyan);
1389
+ red = fg(RIG_PALETTE.red);
1390
+ yellow = fg(RIG_PALETTE.yellow);
1391
+ DRONE_ART = [
1392
+ " .-=-. .-=-. ",
1393
+ " ( !!! ) ( !!! ) ",
1394
+ " '-=-'._ _.'-=-' ",
1395
+ " '._ _.' ",
1396
+ " '=$$$$$$$=.' ",
1397
+ " =$$$$$$$$$$$= ",
1398
+ " $$$@@@@@@@@@@$$$ ",
1399
+ " $$$@@ @@$$$ ",
1400
+ " $$@ ? @$$$ ",
1401
+ " $$$@ '-' @$$$ ",
1402
+ " $$$@@ @@$$$ ",
1403
+ " $$$@@@@@@@@@@$$$ ",
1404
+ " =$$$$$$$$$$$= ",
1405
+ " '=$$$$$$$=.' ",
1406
+ " _.' '._ ",
1407
+ " .-=-.' '.-=-. ",
1408
+ " ( !!! ) ( !!! ) ",
1409
+ " '-=-' '-=-' "
1410
+ ];
1411
+ EYE_FRAMES = ["@", "o", "."];
1412
+ DRONE_WIDTH = DRONE_ART[0].length;
1413
+ DRONE_HEIGHT = DRONE_ART.length;
1414
+ MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
1415
+ MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
1416
+ });
1417
+
1418
+ // packages/cli/src/commands/_async-ui.ts
1419
+ import pc from "picocolors";
1420
+ async function withSpinner(label, work, options = {}) {
1421
+ if (options.outputMode === "json") {
1422
+ return work(() => {});
1423
+ }
1424
+ if (activeUpdate) {
1425
+ const outer = activeUpdate;
1426
+ outer(label);
1427
+ return work(outer);
1428
+ }
1429
+ const output = options.output ?? process.stderr;
1430
+ const isTty = output.isTTY === true;
1431
+ let lastLabel = label;
1432
+ if (!isTty) {
1433
+ output.write(`${label}
1434
+ `);
1435
+ const update2 = (next) => {
1436
+ lastLabel = next;
1437
+ };
1438
+ activeUpdate = update2;
1439
+ const previousListener2 = setServerPhaseListener(update2);
1440
+ try {
1441
+ return await work(update2);
1442
+ } finally {
1443
+ activeUpdate = null;
1444
+ setServerPhaseListener(previousListener2);
1445
+ }
1446
+ }
1447
+ const spinner = createTtySpinner({
1448
+ label,
1449
+ output,
1450
+ frames: MICRO_DRONE_FRAMES,
1451
+ styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
1452
+ });
1453
+ const update = (next) => {
1454
+ lastLabel = next;
1455
+ spinner.setLabel(next);
1456
+ };
1457
+ activeUpdate = update;
1458
+ const previousListener = setServerPhaseListener(update);
1459
+ try {
1460
+ const result = await work(update);
1461
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
1462
+ return result;
1463
+ } catch (error) {
1464
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
1465
+ throw error;
1466
+ } finally {
1467
+ activeUpdate = null;
1468
+ setServerPhaseListener(previousListener);
1469
+ }
1470
+ }
1471
+ var DONE_SYMBOL, FAIL_SYMBOL, activeUpdate = null;
1472
+ var init__async_ui = __esm(() => {
1473
+ init__spinner();
1474
+ init__server_client();
1475
+ init_theme();
1476
+ DONE_SYMBOL = pc.green("\u25C7");
1477
+ FAIL_SYMBOL = pc.red("\u25A0");
1478
+ });
1479
+
1480
+ // packages/cli/src/commands/_pi-frontend.ts
1481
+ var exports__pi_frontend = {};
1482
+ __export(exports__pi_frontend, {
1483
+ shouldRequireOperatorTranscript: () => shouldRequireOperatorTranscript,
1484
+ runWithProcessExitGuard: () => runWithProcessExitGuard,
1485
+ missingOperatorTranscriptMessage: () => missingOperatorTranscriptMessage,
1486
+ buildOperatorPiEnv: () => buildOperatorPiEnv,
1487
+ attachRunBundledPiFrontend: () => attachRunBundledPiFrontend
1488
+ });
1489
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync3 } from "fs";
1490
+ import { homedir as homedir2, tmpdir } from "os";
1491
+ import { join } from "path";
1492
+ import { main as runPiMain } from "@earendil-works/pi-coding-agent";
1493
+ import createPiRigExtension from "@rig/pi-rig";
1494
+ function setTemporaryEnv(updates) {
1495
+ const previous = new Map;
1496
+ for (const [key, value] of Object.entries(updates)) {
1497
+ previous.set(key, process.env[key]);
1498
+ process.env[key] = value;
1499
+ }
1500
+ return () => {
1501
+ for (const [key, value] of previous) {
1502
+ if (value === undefined)
1503
+ delete process.env[key];
1504
+ else
1505
+ process.env[key] = value;
1506
+ }
1507
+ };
1508
+ }
1509
+ function buildOperatorPiEnv(input) {
1510
+ return {
1511
+ PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
1512
+ PI_SKIP_VERSION_CHECK: "1",
1513
+ PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
1514
+ RIG_PI_OPERATOR_SESSION: "1",
1515
+ RIG_RUN_ID: input.runId,
1516
+ RIG_SERVER_URL: input.serverUrl,
1517
+ ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
1518
+ ...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
1519
+ };
1520
+ }
1521
+ function shouldRequireOperatorTranscript(status) {
1522
+ return typeof status === "string" && TERMINAL_RUN_STATUSES.has(status.trim().toLowerCase());
1523
+ }
1524
+ function missingOperatorTranscriptMessage(runId, status) {
1525
+ const shortRun = runId.trim().slice(0, 8) || "unknown";
1526
+ const statusText = typeof status === "string" && status.trim() ? status.trim() : "terminal";
1527
+ return `Run ${shortRun} is ${statusText}, but no worker Pi session transcript is recorded for this run. It likely failed before Pi started or predates full-session capture. Use \`rig run show ${runId}\` and \`rig run logs ${runId}\` for the lifecycle details.`;
1528
+ }
1529
+ function statusFromRunDetails(run) {
1530
+ if (!run || typeof run !== "object" || Array.isArray(run))
1531
+ return;
1532
+ const record = run;
1533
+ if (typeof record.status === "string")
1534
+ return record.status;
1535
+ const nested = record.run;
1536
+ return nested && typeof nested === "object" && !Array.isArray(nested) ? nested.status : undefined;
1537
+ }
1538
+ async function prepareOperatorConsole(context, runId, tempSessionDir) {
1539
+ const server = await ensureServerForCli(context.projectRoot);
1540
+ const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
1541
+ mkdirSync3(localCwd, { recursive: true });
1542
+ trustDroneCwd(localCwd);
1543
+ installRigPiTheme();
1544
+ let sessionFileArg = [];
1545
+ try {
1546
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
1547
+ if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
1548
+ const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
1549
+ const localSessionPath = join(tempSessionDir, fileName);
1550
+ const content = payload.content.split(`
1551
+ `).map((line, index) => {
1552
+ if (index > 0 || !line.trim())
1553
+ return line;
1554
+ try {
1555
+ const header = JSON.parse(line);
1556
+ if (header.type === "session" && typeof header.cwd === "string") {
1557
+ return JSON.stringify({ ...header, cwd: localCwd });
1558
+ }
1559
+ } catch {}
1560
+ return line;
1561
+ }).join(`
1562
+ `);
1563
+ writeFileSync3(localSessionPath, content);
1564
+ sessionFileArg = ["--session", localSessionPath];
1565
+ }
1566
+ } catch {}
1567
+ if (sessionFileArg.length === 0) {
1568
+ const run = await getRunDetailsViaServer(context, runId).catch(() => null);
1569
+ const status = statusFromRunDetails(run);
1570
+ if (shouldRequireOperatorTranscript(status)) {
1571
+ throw new OperatorTranscriptUnavailableError(missingOperatorTranscriptMessage(runId, status));
1572
+ }
1573
+ }
1574
+ return { server, sessionFileArg };
1575
+ }
1576
+ function trustDroneCwd(localCwd) {
1577
+ try {
1578
+ const agentDir = join(homedir2(), ".pi", "agent");
1579
+ mkdirSync3(agentDir, { recursive: true });
1580
+ const trustPath = join(agentDir, "trust.json");
1581
+ const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
1582
+ if (store[localCwd] !== true) {
1583
+ store[localCwd] = true;
1584
+ writeFileSync3(trustPath, `${JSON.stringify(store, null, "\t")}
1585
+ `);
1586
+ }
1587
+ } catch {}
1588
+ }
1589
+ function installRigPiTheme() {
1590
+ try {
1591
+ const themesDir = join(homedir2(), ".pi", "agent", "themes");
1592
+ mkdirSync3(themesDir, { recursive: true });
1593
+ const themePath = join(themesDir, "rig.json");
1594
+ const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
1595
+ `;
1596
+ if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
1597
+ writeFileSync3(themePath, next);
1598
+ }
1599
+ } catch {}
1600
+ }
1601
+ async function runWithProcessExitGuard(body) {
1602
+ const realExit = process.exit;
1603
+ let exitCode = 0;
1604
+ let signalQuit = () => {};
1605
+ const quit = new Promise((resolve3) => {
1606
+ signalQuit = resolve3;
1607
+ });
1608
+ const guardedExit = (code) => {
1609
+ exitCode = typeof code === "number" ? code : 0;
1610
+ signalQuit();
1611
+ return;
1612
+ };
1613
+ process.exit = guardedExit;
1614
+ try {
1615
+ await Promise.race([Promise.resolve().then(body), quit]);
1616
+ } finally {
1617
+ process.exit = realExit;
1618
+ }
1619
+ return exitCode;
1620
+ }
1621
+ function runPiMainReturningOnQuit(args, options) {
1622
+ return runWithProcessExitGuard(() => runPiMain(args, options));
1623
+ }
1624
+ async function attachRunBundledPiFrontend(context, input) {
1625
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1626
+ const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
1627
+ const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
1628
+ runId: input.runId,
1629
+ serverUrl: server.baseUrl,
1630
+ authToken: server.authToken,
1631
+ serverProjectRoot: server.serverProjectRoot,
1632
+ sessionDir: tempSessionDir
1633
+ }));
1634
+ const piRigExtensionFactory = (pi) => {
1635
+ createPiRigExtension(pi);
1636
+ };
1637
+ let detached = false;
1638
+ try {
1639
+ const piArgs = [
1640
+ "--offline",
1641
+ "--no-extensions",
1642
+ "--no-skills",
1643
+ "--no-prompt-templates",
1644
+ "--no-context-files",
1645
+ ...sessionFileArg
1646
+ ];
1647
+ const piOptions = { extensionFactories: [piRigExtensionFactory] };
1648
+ if (input.returnOnQuit) {
1649
+ await runPiMainReturningOnQuit(piArgs, piOptions);
1650
+ } else {
1651
+ await runPiMain(piArgs, piOptions);
1652
+ }
1653
+ detached = true;
1654
+ } finally {
1655
+ restoreEnv();
1656
+ rmSync(tempSessionDir, { recursive: true, force: true });
1657
+ }
1658
+ let run = { runId: input.runId, status: "unknown" };
1659
+ try {
1660
+ run = await getRunDetailsViaServer(context, input.runId);
1661
+ } catch {}
1662
+ return {
1663
+ run,
1664
+ logs: [],
1665
+ timeline: [],
1666
+ timelineCursor: null,
1667
+ steered: input.steered === true,
1668
+ detached,
1669
+ rendered: "stock Pi operator console with the pi-rig extension"
1670
+ };
1671
+ }
1672
+ var TERMINAL_RUN_STATUSES, OperatorTranscriptUnavailableError, RIG_PI_THEME;
1673
+ var init__pi_frontend = __esm(() => {
1674
+ init__server_client();
1675
+ init__async_ui();
1676
+ TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
1677
+ OperatorTranscriptUnavailableError = class OperatorTranscriptUnavailableError extends Error {
1678
+ constructor(message) {
1679
+ super(message);
1680
+ this.name = "OperatorTranscriptUnavailableError";
1681
+ }
1682
+ };
1683
+ RIG_PI_THEME = {
1684
+ $schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
1685
+ name: "rig",
1686
+ vars: {
1687
+ acid: "#ccff4d",
1688
+ acidDim: "#a9d63f",
1689
+ cyan: "#56d8ff",
1690
+ red: "#ff5d5d",
1691
+ yellow: "#ffd24d",
1692
+ ink: "#f2f3f6",
1693
+ ink2: "#aeb0ba",
1694
+ ink3: "#6c6e79",
1695
+ ink4: "#44464f",
1696
+ panel: "#101115",
1697
+ panelUser: "#14161b",
1698
+ toolPending: "#0e1013",
1699
+ toolSuccess: "#10150c",
1700
+ toolError: "#1a0f0f",
1701
+ customMsg: "#0f1410"
1702
+ },
1703
+ colors: {
1704
+ accent: "acid",
1705
+ border: "ink4",
1706
+ borderAccent: "acid",
1707
+ borderMuted: "ink4",
1708
+ success: "acid",
1709
+ error: "red",
1710
+ warning: "yellow",
1711
+ muted: "ink3",
1712
+ dim: "ink4",
1713
+ text: "ink",
1714
+ thinkingText: "ink3",
1715
+ selectedBg: "panel",
1716
+ userMessageBg: "panelUser",
1717
+ userMessageText: "ink",
1718
+ customMessageBg: "customMsg",
1719
+ customMessageText: "ink2",
1720
+ customMessageLabel: "acidDim",
1721
+ toolPendingBg: "toolPending",
1722
+ toolSuccessBg: "toolSuccess",
1723
+ toolErrorBg: "toolError",
1724
+ toolTitle: "ink",
1725
+ toolOutput: "ink3",
1726
+ mdHeading: "acid",
1727
+ mdLink: "cyan",
1728
+ mdLinkUrl: "ink4",
1729
+ mdCode: "acidDim",
1730
+ mdCodeBlock: "ink2",
1731
+ mdCodeBlockBorder: "ink4",
1732
+ mdQuote: "ink3",
1733
+ mdQuoteBorder: "ink4",
1734
+ mdHr: "ink4",
1735
+ mdListBullet: "acid",
1736
+ toolDiffAdded: "acid",
1737
+ toolDiffRemoved: "red",
1738
+ toolDiffContext: "ink3",
1739
+ syntaxComment: "ink3",
1740
+ syntaxKeyword: "cyan",
1741
+ syntaxFunction: "acid",
1742
+ syntaxVariable: "ink",
1743
+ syntaxString: "acidDim",
1744
+ syntaxNumber: "yellow",
1745
+ syntaxType: "cyan",
1746
+ syntaxOperator: "ink2",
1747
+ syntaxPunctuation: "ink3",
1748
+ thinkingOff: "ink4",
1749
+ thinkingMinimal: "ink3",
1750
+ thinkingLow: "ink2",
1751
+ thinkingMedium: "cyan",
1752
+ thinkingHigh: "acidDim",
1753
+ thinkingXhigh: "acid",
1754
+ bashMode: "cyan"
1755
+ }
1756
+ };
1757
+ });
1758
+
833
1759
  // packages/cli/src/app-opentui/adapters/inspect.ts
834
1760
  var exports_inspect = {};
835
1761
  __export(exports_inspect, {
@@ -838,7 +1764,7 @@ __export(exports_inspect, {
838
1764
  INSPECT_VIEWS: () => INSPECT_VIEWS
839
1765
  });
840
1766
  import { execFile } from "child_process";
841
- import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync, statSync } from "fs";
1767
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync, statSync } from "fs";
842
1768
  import { resolve as resolve3 } from "path";
843
1769
  import { promisify } from "util";
844
1770
  import { resolveTaskArtifactDirs } from "@rig/runtime/control-plane/authority-files";
@@ -860,7 +1786,7 @@ function listArtifacts(projectRoot, taskId) {
860
1786
  if (!taskId)
861
1787
  return { artifacts: [], error: "run has no task id \u2014 artifacts are resolved per task" };
862
1788
  try {
863
- const dirs = resolveTaskArtifactDirs(projectRoot, taskId).filter((dir) => existsSync3(dir));
1789
+ const dirs = resolveTaskArtifactDirs(projectRoot, taskId).filter((dir) => existsSync4(dir));
864
1790
  const out = [];
865
1791
  const seen = new Set;
866
1792
  for (const dir of dirs) {
@@ -906,9 +1832,9 @@ function loadGraph(projectRoot) {
906
1832
  function loadAudit(projectRoot) {
907
1833
  try {
908
1834
  const auditPath = resolve3(resolveHarnessPaths(projectRoot).logsDir, "audit.jsonl");
909
- if (!existsSync3(auditPath))
1835
+ if (!existsSync4(auditPath))
910
1836
  return [];
911
- return readFileSync3(auditPath, "utf-8").split(/\r?\n/).filter(Boolean).slice(-50).flatMap((raw) => {
1837
+ return readFileSync4(auditPath, "utf-8").split(/\r?\n/).filter(Boolean).slice(-50).flatMap((raw) => {
912
1838
  try {
913
1839
  const parsed = JSON.parse(raw);
914
1840
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? [parsed] : [{ detail: raw }];
@@ -1027,396 +1953,6 @@ var init_inspect = __esm(() => {
1027
1953
  "audit"
1028
1954
  ];
1029
1955
  });
1030
- // packages/cli/src/app-opentui/pi-pty-host.ts
1031
- import { fileURLToPath } from "url";
1032
- import { basename } from "path";
1033
- import { RGBA, StyledText, TextAttributes } from "@opentui/core";
1034
- import { Terminal as XtermTerminal } from "@xterm/headless";
1035
- var MIN_COLS = 40;
1036
- var MIN_ROWS = 12;
1037
- var MAX_ROWS = 300;
1038
- var MAX_SNAPSHOT_LINES = 360;
1039
- var STYLED_SNAPSHOT_MARGIN = 6;
1040
- var SNAPSHOT_DELAY_MS = 120;
1041
- var fallbackChildScriptPath = fileURLToPath(new URL("./pi-host-child.ts", import.meta.url));
1042
- var activeHost = null;
1043
- function clampCols(cols) {
1044
- return Math.max(MIN_COLS, Math.trunc(cols || 100));
1045
- }
1046
- function clampRows(rows) {
1047
- return Math.max(MIN_ROWS, Math.min(MAX_ROWS, Math.trunc(rows || 35)));
1048
- }
1049
- var XTERM_COLOR_MODE_INDEXED_16 = 16777216;
1050
- var XTERM_COLOR_MODE_INDEXED_256 = 33554432;
1051
- var XTERM_COLOR_MODE_RGB = 50331648;
1052
- function rgbaFromXtermColor(mode, value) {
1053
- if (mode === 1 || mode === 2 || mode === XTERM_COLOR_MODE_INDEXED_16 || mode === XTERM_COLOR_MODE_INDEXED_256) {
1054
- return RGBA.fromIndex(value);
1055
- }
1056
- if (mode === 3 || mode === XTERM_COLOR_MODE_RGB) {
1057
- return RGBA.fromInts(value >> 16 & 255, value >> 8 & 255, value & 255);
1058
- }
1059
- return;
1060
- }
1061
- function textAttributesFromCell(cell) {
1062
- let attributes = TextAttributes.NONE;
1063
- if (cell.isBold())
1064
- attributes |= TextAttributes.BOLD;
1065
- if (cell.isDim())
1066
- attributes |= TextAttributes.DIM;
1067
- if (cell.isItalic())
1068
- attributes |= TextAttributes.ITALIC;
1069
- if (cell.isUnderline())
1070
- attributes |= TextAttributes.UNDERLINE;
1071
- if (cell.isBlink())
1072
- attributes |= TextAttributes.BLINK;
1073
- if (cell.isInverse())
1074
- attributes |= TextAttributes.INVERSE;
1075
- if (cell.isInvisible())
1076
- attributes |= TextAttributes.HIDDEN;
1077
- if (cell.isStrikethrough())
1078
- attributes |= TextAttributes.STRIKETHROUGH;
1079
- return attributes;
1080
- }
1081
- function sameRgba(a, b) {
1082
- if (!a && !b)
1083
- return true;
1084
- return Boolean(a && b && a.equals(b));
1085
- }
1086
- function sameStyle(a, b) {
1087
- return sameRgba(a.fg, b.fg) && sameRgba(a.bg, b.bg) && (a.attributes ?? 0) === (b.attributes ?? 0);
1088
- }
1089
- function styleFromCell(cell) {
1090
- return {
1091
- fg: rgbaFromXtermColor(cell.getFgColorMode(), cell.getFgColor()),
1092
- bg: rgbaFromXtermColor(cell.getBgColorMode(), cell.getBgColor()),
1093
- attributes: textAttributesFromCell(cell)
1094
- };
1095
- }
1096
- function lineToStyledText(line, cols) {
1097
- if (!line)
1098
- return new StyledText([{ __isChunk: true, text: "" }]);
1099
- const chunks = [];
1100
- let run = "";
1101
- let runStyle = null;
1102
- const flush = () => {
1103
- if (!run)
1104
- return;
1105
- chunks.push({
1106
- __isChunk: true,
1107
- text: run,
1108
- ...runStyle?.fg ? { fg: runStyle.fg } : {},
1109
- ...runStyle?.bg ? { bg: runStyle.bg } : {},
1110
- ...(runStyle?.attributes ?? 0) !== 0 ? { attributes: runStyle.attributes } : {}
1111
- });
1112
- run = "";
1113
- };
1114
- for (let index = 0;index < cols; index += 1) {
1115
- const cell = line.getCell(index);
1116
- if (!cell) {
1117
- if (runStyle !== null)
1118
- flush();
1119
- runStyle = null;
1120
- run += " ";
1121
- continue;
1122
- }
1123
- if (cell.getWidth() === 0)
1124
- continue;
1125
- const style = styleFromCell(cell);
1126
- if (!runStyle || !sameStyle(runStyle, style)) {
1127
- flush();
1128
- runStyle = style;
1129
- }
1130
- run += cell.getChars() || " ";
1131
- }
1132
- flush();
1133
- return new StyledText(chunks.length > 0 ? chunks : [{ __isChunk: true, text: "" }]);
1134
- }
1135
- function childCommandPrefix() {
1136
- const execName = basename(process.execPath).toLowerCase();
1137
- const currentEntry = process.argv[1];
1138
- if (execName === "bun" || execName === "bun.exe") {
1139
- return currentEntry ? [process.execPath, currentEntry, "__opentui-pi-host"] : [process.execPath, fallbackChildScriptPath];
1140
- }
1141
- return [process.execPath, "__opentui-pi-host"];
1142
- }
1143
- function withEnv(base) {
1144
- const env = {};
1145
- for (const [key, value] of Object.entries(base ?? process.env)) {
1146
- if (key === "RIG_PLAIN" || key === "RIG_CLI_PLAIN_HELP" || key === "NO_COLOR")
1147
- continue;
1148
- if (typeof value === "string")
1149
- env[key] = value;
1150
- }
1151
- return {
1152
- ...env,
1153
- TERM: "xterm-256color",
1154
- COLORTERM: "truecolor",
1155
- FORCE_COLOR: env.FORCE_COLOR ?? "1",
1156
- RIG_OPENTUI_PI_HOST: "1"
1157
- };
1158
- }
1159
- async function startPiPtyHost(options) {
1160
- activeHost?.dispose("replace");
1161
- const host = new PiPtyHost(options);
1162
- activeHost = host;
1163
- await host.start();
1164
- return host;
1165
- }
1166
- class PiPtyHost {
1167
- runId;
1168
- projectRoot;
1169
- onSnapshot;
1170
- onExit;
1171
- onError;
1172
- terminal;
1173
- disposables = [];
1174
- decoder = new TextDecoder("utf-8");
1175
- proc = null;
1176
- pty = null;
1177
- status = "starting";
1178
- cols;
1179
- rows;
1180
- message = "starting bundled Pi";
1181
- lastResizeError = null;
1182
- exitCode;
1183
- signal;
1184
- notifyTimer = null;
1185
- lastStreamKey = "";
1186
- _disposed = false;
1187
- constructor(options) {
1188
- this.runId = options.runId;
1189
- this.projectRoot = options.projectRoot;
1190
- this.cols = clampCols(options.cols);
1191
- this.rows = clampRows(options.rows);
1192
- this.onSnapshot = options.onSnapshot;
1193
- this.onExit = options.onExit;
1194
- this.onError = options.onError;
1195
- this.terminal = new XtermTerminal({
1196
- allowProposedApi: true,
1197
- cols: this.cols,
1198
- rows: this.rows,
1199
- scrollback: 1000
1200
- });
1201
- this.registerTerminalResponders();
1202
- this.disposables.push(this.terminal.onWriteParsed(() => {
1203
- if (this._disposed)
1204
- return;
1205
- const snapshot = this.createSnapshot();
1206
- const key = snapshot.lines.join(`
1207
- `);
1208
- if (key === this.lastStreamKey)
1209
- return;
1210
- this.lastStreamKey = key;
1211
- this.onSnapshot?.(snapshot);
1212
- }));
1213
- }
1214
- get disposed() {
1215
- return this._disposed;
1216
- }
1217
- get snapshot() {
1218
- return this.createSnapshot();
1219
- }
1220
- async start() {
1221
- if (this._disposed)
1222
- throw new Error("Pi PTY host is disposed.");
1223
- if (typeof Bun.Terminal !== "function") {
1224
- throw new Error("Bun native PTY is unavailable in this runtime. Pi host requires Bun.Terminal.");
1225
- }
1226
- const spawnOptions = {
1227
- cwd: this.projectRoot,
1228
- env: withEnv(process.env),
1229
- terminal: {
1230
- cols: this.cols,
1231
- rows: this.rows,
1232
- name: "xterm-256color",
1233
- data: (_terminal, data) => this.handlePtyData(data)
1234
- }
1235
- };
1236
- const proc = Bun.spawn([
1237
- ...childCommandPrefix(),
1238
- "--run-id",
1239
- this.runId,
1240
- "--project-root",
1241
- this.projectRoot
1242
- ], spawnOptions);
1243
- if (!proc.terminal)
1244
- throw new Error("Bun did not attach a terminal to the bundled Pi child process.");
1245
- this.proc = proc;
1246
- this.pty = proc.terminal;
1247
- this.status = "running";
1248
- this.message = "bundled Pi running inside this app";
1249
- this.emitSnapshotSoon(0);
1250
- proc.exited.then((exitCode) => {
1251
- if (this._disposed)
1252
- return;
1253
- this.status = exitCode === 0 ? "exited" : "failed";
1254
- this.exitCode = exitCode;
1255
- this.signal = null;
1256
- this.message = exitCode === 0 ? "bundled Pi exited" : `bundled Pi exited with code ${exitCode}`;
1257
- const snapshot = this.createSnapshot();
1258
- this.onSnapshot?.(snapshot);
1259
- this.onExit?.(snapshot);
1260
- if (activeHost === this)
1261
- activeHost = null;
1262
- this.dispose("exit", { kill: false, notify: false });
1263
- }).catch((error) => {
1264
- if (this._disposed)
1265
- return;
1266
- this.status = "failed";
1267
- this.message = error instanceof Error ? error.message : String(error);
1268
- const snapshot = this.createSnapshot();
1269
- this.onSnapshot?.(snapshot);
1270
- this.onError?.(error, snapshot);
1271
- if (activeHost === this)
1272
- activeHost = null;
1273
- this.dispose("error", { kill: false, notify: false });
1274
- });
1275
- }
1276
- write(data) {
1277
- if (this._disposed || !this.pty)
1278
- return;
1279
- try {
1280
- this.pty.write(data);
1281
- } catch (error) {
1282
- this.status = "failed";
1283
- this.message = error instanceof Error ? error.message : String(error);
1284
- const snapshot = this.createSnapshot();
1285
- this.onSnapshot?.(snapshot);
1286
- this.onError?.(error, snapshot);
1287
- }
1288
- }
1289
- resize(cols, rows) {
1290
- const nextCols = clampCols(cols);
1291
- const nextRows = clampRows(rows);
1292
- if (nextCols === this.cols && nextRows === this.rows)
1293
- return;
1294
- this.cols = nextCols;
1295
- this.rows = nextRows;
1296
- this.terminal.resize(nextCols, nextRows);
1297
- try {
1298
- this.pty?.resize(nextCols, nextRows);
1299
- this.lastResizeError = null;
1300
- } catch (error) {
1301
- this.lastResizeError = error instanceof Error ? error.message : String(error);
1302
- }
1303
- this.emitSnapshotSoon(0);
1304
- }
1305
- detach() {
1306
- this.dispose("detach");
1307
- return this.createSnapshot("detached from bundled Pi");
1308
- }
1309
- dispose(reason = "dispose", options = {}) {
1310
- if (this._disposed)
1311
- return;
1312
- this._disposed = true;
1313
- if (this.notifyTimer)
1314
- clearTimeout(this.notifyTimer);
1315
- this.notifyTimer = null;
1316
- for (const disposable of this.disposables.splice(0)) {
1317
- try {
1318
- disposable.dispose();
1319
- } catch {}
1320
- }
1321
- if (options.kill !== false) {
1322
- try {
1323
- this.proc?.kill("SIGTERM");
1324
- } catch {}
1325
- }
1326
- try {
1327
- this.pty?.close();
1328
- } catch {}
1329
- try {
1330
- this.terminal.dispose();
1331
- } catch {}
1332
- if (activeHost === this)
1333
- activeHost = null;
1334
- if (options.notify) {
1335
- this.message = reason;
1336
- this.onSnapshot?.(this.createSnapshot(reason));
1337
- }
1338
- }
1339
- handlePtyData(data) {
1340
- if (this._disposed)
1341
- return;
1342
- const text = this.decoder.decode(data, { stream: true });
1343
- this.respondToRawTerminalQueries(text);
1344
- this.terminal.write(data);
1345
- }
1346
- emitSnapshotSoon(delayMs = SNAPSHOT_DELAY_MS) {
1347
- if (this._disposed || this.notifyTimer)
1348
- return;
1349
- this.notifyTimer = setTimeout(() => {
1350
- this.notifyTimer = null;
1351
- if (this._disposed)
1352
- return;
1353
- this.onSnapshot?.(this.createSnapshot());
1354
- }, delayMs);
1355
- }
1356
- createSnapshot(message = this.message) {
1357
- const buffer = this.terminal.buffer.active;
1358
- const end = buffer.length;
1359
- const start = Math.max(0, end - MAX_SNAPSHOT_LINES);
1360
- const styledStart = Math.max(start, end - this.rows - STYLED_SNAPSHOT_MARGIN);
1361
- const lines = [];
1362
- const styledLines = [];
1363
- for (let row = start;row < end; row += 1) {
1364
- const line = buffer.getLine(row);
1365
- lines.push((line?.translateToString(false) ?? "").slice(0, this.cols));
1366
- if (row >= styledStart)
1367
- styledLines[lines.length - 1] = lineToStyledText(line, this.cols);
1368
- }
1369
- while (lines.length < this.rows) {
1370
- lines.push("");
1371
- styledLines[lines.length - 1] = new StyledText([{ __isChunk: true, text: "" }]);
1372
- }
1373
- const resolvedMessage = this.lastResizeError ? `resize degraded: ${this.lastResizeError}` : message;
1374
- return {
1375
- runId: this.runId,
1376
- status: this.status,
1377
- cols: this.cols,
1378
- rows: this.rows,
1379
- lines,
1380
- styledLines,
1381
- message: resolvedMessage,
1382
- ...this.lastResizeError ? { resizeError: this.lastResizeError } : {},
1383
- ...this.exitCode !== undefined ? { exitCode: this.exitCode } : {},
1384
- ...this.signal !== undefined ? { signal: this.signal } : {}
1385
- };
1386
- }
1387
- registerTerminalResponders() {
1388
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "c" }, (params) => {
1389
- if (params.length === 0 || params[0] === 0)
1390
- this.write("\x1B[?62;22c");
1391
- return false;
1392
- }));
1393
- this.disposables.push(this.terminal.parser.registerCsiHandler({ prefix: ">", final: "c" }, (params) => {
1394
- if (params.length === 0 || params[0] === 0)
1395
- this.write("\x1B[>0;0;0c");
1396
- return false;
1397
- }));
1398
- this.disposables.push(this.terminal.parser.registerCsiHandler({ final: "n" }, (params) => {
1399
- if (params[0] === 5) {
1400
- this.write("\x1B[0n");
1401
- } else if (params[0] === 6) {
1402
- const row = this.terminal.buffer.active.cursorY + 1;
1403
- const col = this.terminal.buffer.active.cursorX + 1;
1404
- this.write(`\x1B[${row};${col}R`);
1405
- }
1406
- return false;
1407
- }));
1408
- }
1409
- respondToRawTerminalQueries(text) {
1410
- if (!text)
1411
- return;
1412
- const decrqm = /\x1b\[\?(\d+)\$p/g;
1413
- let match;
1414
- while ((match = decrqm.exec(text)) !== null) {
1415
- this.write(`\x1B[?${match[1]};2$y`);
1416
- }
1417
- }
1418
- }
1419
-
1420
1956
  // packages/cli/src/app-opentui/adapters/fleet.ts
1421
1957
  function normalizeRunRecord(record) {
1422
1958
  const runId = stringField(record, ["runId", "id"]);
@@ -1478,14 +2014,6 @@ function recordStep(ctx, runId, label, emitLabel) {
1478
2014
  });
1479
2015
  emitProgress(ctx, emitLabel, label);
1480
2016
  }
1481
- function settleSteps(ctx, runId) {
1482
- const now = Date.now();
1483
- const previous = currentAttachState(ctx, runId);
1484
- if (!previous?.steps)
1485
- return;
1486
- const steps = previous.steps.map((step) => step.status === "running" ? { ...step, status: "done", endedAtMs: step.endedAtMs ?? now } : step);
1487
- patchData(ctx, { piAttach: { ...previous, steps } });
1488
- }
1489
2017
  async function preparePiAttachHandoff(ctx, runId) {
1490
2018
  const cleanRunId = runId.trim();
1491
2019
  const label = `Preparing Pi ${cleanRunId.slice(0, 8)}`;
@@ -1533,82 +2061,39 @@ async function attachRunWithBundledPi(ctx, runId) {
1533
2061
  throw error;
1534
2062
  }
1535
2063
  emitStarted(ctx, label, { piAttach: { runId: cleanRunId, status: "entering-pi" } });
1536
- patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "starting bundled Pi", steps: [] } });
2064
+ patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "handing the terminal to worker Pi\u2026" } });
2065
+ const projectRoot = projectRootOf(ctx);
2066
+ const outputMode = ctx.rig?.outputMode ?? "text";
2067
+ await releaseRendererForExternalTui(ctx);
2068
+ let outcome = null;
2069
+ let attachError = null;
1537
2070
  try {
1538
- recordStep(ctx, cleanRunId, "connecting to server and fetching run transcript", label);
1539
- await preparePiAttachHandoff(ctx, cleanRunId).catch((error) => {
1540
- patchData(ctx, { lastRefreshError: normalizeAppError(error).message });
1541
- return null;
1542
- });
1543
- recordStep(ctx, cleanRunId, "spawning Bun PTY host for bundled Pi", label);
1544
- const projectRoot = projectRootOf(ctx);
1545
- const cols = typeof process.stdout.columns === "number" ? process.stdout.columns : 100;
1546
- const rows = Math.max(1, (typeof process.stdout.rows === "number" ? process.stdout.rows : 35) - 1);
1547
- const patchTerminal = (snapshot) => {
1548
- const previousSteps = currentAttachState(ctx, cleanRunId)?.steps;
1549
- const failed = snapshot.status === "failed";
1550
- const reason = failed ? snapshot.message ?? `bundled Pi exited with code ${snapshot.exitCode ?? "unknown"}` : undefined;
1551
- patchData(ctx, {
1552
- piTerminal: snapshot,
1553
- piAttach: {
1554
- runId: cleanRunId,
1555
- status: failed ? "failed" : snapshot.status === "exited" ? "returned" : "entering-pi",
1556
- message: snapshot.message ?? "bundled Pi running",
1557
- result: { runId: cleanRunId, status: snapshot.status, exitCode: snapshot.exitCode },
1558
- ...previousSteps ? { steps: previousSteps } : {},
1559
- ...reason ? { failureReason: reason } : {}
1560
- }
1561
- });
1562
- };
1563
- recordStep(ctx, cleanRunId, "starting bundled Pi", label);
1564
- await startPiPtyHost({
1565
- runId: cleanRunId,
1566
- projectRoot,
1567
- cols,
1568
- rows,
1569
- onSnapshot: (snapshot) => {
1570
- if (snapshot.status === "running" && snapshot.lines.some((entry) => entry.trim().length > 0)) {
1571
- settleSteps(ctx, cleanRunId);
1572
- }
1573
- patchTerminal(snapshot);
1574
- },
1575
- onExit: (snapshot) => {
1576
- patchTerminal(snapshot);
1577
- if (snapshot.status === "failed") {
1578
- Promise.resolve().then(() => (init_inspect(), exports_inspect)).then(({ loadInspect: loadInspect2 }) => loadInspect2(ctx, cleanRunId)).catch(() => null);
1579
- emitFailed(ctx, label, new Error(snapshot.message ?? `bundled Pi exited with code ${snapshot.exitCode ?? "unknown"}`), { runId: cleanRunId, result: { status: snapshot.status, exitCode: snapshot.exitCode } });
1580
- return;
1581
- }
1582
- emitCompleted(ctx, label, { runId: cleanRunId, result: { status: snapshot.status, exitCode: snapshot.exitCode } });
1583
- ctx.emit({ type: "scene.change", scene: "fleet", intent: { scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } } });
1584
- refreshFleet(ctx).catch((error) => emitFailed(ctx, "Refresh runs", error));
1585
- },
1586
- onError: (error, snapshot) => {
1587
- patchTerminal(snapshot);
1588
- emitFailed(ctx, label, error, { runId: cleanRunId });
1589
- }
1590
- });
1591
- const record = {
1592
- runId: cleanRunId,
1593
- status: "running",
1594
- rendered: "bundled Pi embedded via Bun.Terminal + @xterm/headless"
1595
- };
1596
- emitProgress(ctx, label, "bundled Pi is running", { piAttach: { runId: cleanRunId, status: "entering-pi", message: "bundled Pi running", result: record } });
1597
- return record;
2071
+ const { attachRunBundledPiFrontend: attachRunBundledPiFrontend2 } = await Promise.resolve().then(() => (init__pi_frontend(), exports__pi_frontend));
2072
+ outcome = await attachRunBundledPiFrontend2({ projectRoot, outputMode }, { runId: cleanRunId, returnOnQuit: true });
1598
2073
  } catch (error) {
1599
- const reason = error instanceof Error ? error.message : String(error);
2074
+ attachError = error;
2075
+ } finally {
2076
+ await resumeRendererAfterExternalTui(ctx);
2077
+ }
2078
+ if (attachError) {
2079
+ const reason = normalizeAppError(attachError).message;
1600
2080
  patchData(ctx, {
1601
- piAttach: {
1602
- runId: cleanRunId,
1603
- status: "failed",
1604
- message: reason,
1605
- failureReason: reason,
1606
- ...currentAttachState(ctx, cleanRunId)?.steps ? { steps: currentAttachState(ctx, cleanRunId).steps } : {}
1607
- }
2081
+ piTerminal: undefined,
2082
+ piAttach: { runId: cleanRunId, status: "failed", message: reason, failureReason: reason }
1608
2083
  });
1609
- emitFailed(ctx, label, error, { runId: cleanRunId });
1610
- throw error;
2084
+ Promise.resolve().then(() => (init_inspect(), exports_inspect)).then(({ loadInspect: loadInspect2 }) => loadInspect2(ctx, cleanRunId)).catch(() => null);
2085
+ emitFailed(ctx, label, attachError, { runId: cleanRunId });
2086
+ throw attachError;
1611
2087
  }
2088
+ const detached = outcome?.detached === true;
2089
+ patchData(ctx, {
2090
+ piTerminal: undefined,
2091
+ piAttach: { runId: cleanRunId, status: "returned", message: detached ? "detached from worker Pi" : "returned from worker Pi" }
2092
+ });
2093
+ emitCompleted(ctx, label, { runId: cleanRunId, result: { runId: cleanRunId, detached } });
2094
+ ctx.emit({ type: "scene.change", scene: "fleet", intent: { scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } } });
2095
+ refreshFleet(ctx).catch((error) => emitFailed(ctx, "Refresh runs", error));
2096
+ return { runId: cleanRunId, status: "returned", detached };
1612
2097
  }
1613
2098
  export {
1614
2099
  preparePiAttachHandoff,