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

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.
@@ -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)));
@@ -830,6 +845,486 @@ var init__server_client = __esm(() => {
830
845
  ]);
831
846
  });
832
847
 
848
+ // packages/cli/src/commands/_spinner.ts
849
+ function createTtySpinner(input) {
850
+ const output = input.output ?? process.stdout;
851
+ const isTty = output.isTTY === true;
852
+ const frames = input.frames && input.frames.length > 0 ? input.frames : SPINNER_FRAMES;
853
+ let label = input.label;
854
+ let frame = 0;
855
+ let paused = false;
856
+ let stopped = false;
857
+ let lastPrintedLabel = "";
858
+ const render = () => {
859
+ if (stopped || paused)
860
+ return;
861
+ if (!isTty) {
862
+ if (label !== lastPrintedLabel) {
863
+ output.write(`${label}
864
+ `);
865
+ lastPrintedLabel = label;
866
+ }
867
+ return;
868
+ }
869
+ frame = (frame + 1) % frames.length;
870
+ const glyph = frames[frame] ?? frames[0] ?? "";
871
+ output.write(`\r\x1B[2K${input.styleFrame ? input.styleFrame(glyph) : glyph} ${label}`);
872
+ };
873
+ const clearLine = () => {
874
+ if (isTty)
875
+ output.write("\r\x1B[2K");
876
+ };
877
+ render();
878
+ const timer = isTty ? setInterval(render, input.intervalMs ?? 16) : null;
879
+ return {
880
+ setLabel(next) {
881
+ label = next;
882
+ render();
883
+ },
884
+ pause() {
885
+ paused = true;
886
+ clearLine();
887
+ },
888
+ resume() {
889
+ if (stopped)
890
+ return;
891
+ paused = false;
892
+ render();
893
+ },
894
+ stop(finalLine) {
895
+ if (stopped)
896
+ return;
897
+ stopped = true;
898
+ if (timer)
899
+ clearInterval(timer);
900
+ clearLine();
901
+ if (finalLine)
902
+ output.write(`${finalLine}
903
+ `);
904
+ }
905
+ };
906
+ }
907
+ var SPINNER_FRAMES;
908
+ var init__spinner = __esm(() => {
909
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
910
+ });
911
+
912
+ // packages/cli/src/app/theme.ts
913
+ function hexToRgb(hex) {
914
+ const value = hex.replace("#", "");
915
+ return [
916
+ Number.parseInt(value.slice(0, 2), 16),
917
+ Number.parseInt(value.slice(2, 4), 16),
918
+ Number.parseInt(value.slice(4, 6), 16)
919
+ ];
920
+ }
921
+ function fg(hex) {
922
+ const [r, g, b] = hexToRgb(hex);
923
+ return (text) => `\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`;
924
+ }
925
+ function bold(text) {
926
+ return `\x1B[1m${text}\x1B[22m`;
927
+ }
928
+ function microDroneFrame(tick) {
929
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
930
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
931
+ return `(${blade})${eye}(${blade})`;
932
+ }
933
+ function renderMicroDroneFrame(tick) {
934
+ const blade = MICRO_BLADES[tick % MICRO_BLADES.length];
935
+ const eye = EYE_FRAMES[Math.floor(tick / 2) % EYE_FRAMES.length];
936
+ return `${ink4("(")}${cyan(blade)}${ink4(")")}${bold(accent(eye))}${ink4("(")}${cyan(blade)}${ink4(")")}`;
937
+ }
938
+ 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;
939
+ var init_theme = __esm(() => {
940
+ RIG_PALETTE = {
941
+ ink: "#f2f3f6",
942
+ ink2: "#aeb0ba",
943
+ ink3: "#6c6e79",
944
+ ink4: "#44464f",
945
+ accent: "#ccff4d",
946
+ accentDim: "#a9d63f",
947
+ cyan: "#56d8ff",
948
+ red: "#ff5d5d",
949
+ yellow: "#ffd24d"
950
+ };
951
+ ink = fg(RIG_PALETTE.ink);
952
+ ink2 = fg(RIG_PALETTE.ink2);
953
+ ink3 = fg(RIG_PALETTE.ink3);
954
+ ink4 = fg(RIG_PALETTE.ink4);
955
+ accent = fg(RIG_PALETTE.accent);
956
+ accentDim = fg(RIG_PALETTE.accentDim);
957
+ cyan = fg(RIG_PALETTE.cyan);
958
+ red = fg(RIG_PALETTE.red);
959
+ yellow = fg(RIG_PALETTE.yellow);
960
+ DRONE_ART = [
961
+ " .-=-. .-=-. ",
962
+ " ( !!! ) ( !!! ) ",
963
+ " '-=-'._ _.'-=-' ",
964
+ " '._ _.' ",
965
+ " '=$$$$$$$=.' ",
966
+ " =$$$$$$$$$$$= ",
967
+ " $$$@@@@@@@@@@$$$ ",
968
+ " $$$@@ @@$$$ ",
969
+ " $$@ ? @$$$ ",
970
+ " $$$@ '-' @$$$ ",
971
+ " $$$@@ @@$$$ ",
972
+ " $$$@@@@@@@@@@$$$ ",
973
+ " =$$$$$$$$$$$= ",
974
+ " '=$$$$$$$=.' ",
975
+ " _.' '._ ",
976
+ " .-=-.' '.-=-. ",
977
+ " ( !!! ) ( !!! ) ",
978
+ " '-=-' '-=-' "
979
+ ];
980
+ EYE_FRAMES = ["@", "o", "."];
981
+ DRONE_WIDTH = DRONE_ART[0].length;
982
+ DRONE_HEIGHT = DRONE_ART.length;
983
+ MICRO_BLADES = ["---", "\\\\\\", "|||", "///"];
984
+ MICRO_DRONE_FRAMES = Array.from({ length: 12 }, (_, index) => microDroneFrame(index));
985
+ });
986
+
987
+ // packages/cli/src/commands/_async-ui.ts
988
+ import pc from "picocolors";
989
+ async function withSpinner(label, work, options = {}) {
990
+ if (options.outputMode === "json") {
991
+ return work(() => {});
992
+ }
993
+ if (activeUpdate) {
994
+ const outer = activeUpdate;
995
+ outer(label);
996
+ return work(outer);
997
+ }
998
+ const output = options.output ?? process.stderr;
999
+ const isTty = output.isTTY === true;
1000
+ let lastLabel = label;
1001
+ if (!isTty) {
1002
+ output.write(`${label}
1003
+ `);
1004
+ const update2 = (next) => {
1005
+ lastLabel = next;
1006
+ };
1007
+ activeUpdate = update2;
1008
+ const previousListener2 = setServerPhaseListener(update2);
1009
+ try {
1010
+ return await work(update2);
1011
+ } finally {
1012
+ activeUpdate = null;
1013
+ setServerPhaseListener(previousListener2);
1014
+ }
1015
+ }
1016
+ const spinner = createTtySpinner({
1017
+ label,
1018
+ output,
1019
+ frames: MICRO_DRONE_FRAMES,
1020
+ styleFrame: (frame) => renderMicroDroneFrame(Math.max(0, MICRO_DRONE_FRAMES.indexOf(frame)))
1021
+ });
1022
+ const update = (next) => {
1023
+ lastLabel = next;
1024
+ spinner.setLabel(next);
1025
+ };
1026
+ activeUpdate = update;
1027
+ const previousListener = setServerPhaseListener(update);
1028
+ try {
1029
+ const result = await work(update);
1030
+ spinner.stop(options.doneLabel ? `${DONE_SYMBOL} ${options.doneLabel}` : undefined);
1031
+ return result;
1032
+ } catch (error) {
1033
+ spinner.stop(`${FAIL_SYMBOL} ${lastLabel}`);
1034
+ throw error;
1035
+ } finally {
1036
+ activeUpdate = null;
1037
+ setServerPhaseListener(previousListener);
1038
+ }
1039
+ }
1040
+ var DONE_SYMBOL, FAIL_SYMBOL, activeUpdate = null;
1041
+ var init__async_ui = __esm(() => {
1042
+ init__spinner();
1043
+ init__server_client();
1044
+ init_theme();
1045
+ DONE_SYMBOL = pc.green("\u25C7");
1046
+ FAIL_SYMBOL = pc.red("\u25A0");
1047
+ });
1048
+
1049
+ // packages/cli/src/commands/_pi-frontend.ts
1050
+ var exports__pi_frontend = {};
1051
+ __export(exports__pi_frontend, {
1052
+ shouldRequireOperatorTranscript: () => shouldRequireOperatorTranscript,
1053
+ runWithProcessExitGuard: () => runWithProcessExitGuard,
1054
+ missingOperatorTranscriptMessage: () => missingOperatorTranscriptMessage,
1055
+ buildOperatorPiEnv: () => buildOperatorPiEnv,
1056
+ attachRunBundledPiFrontend: () => attachRunBundledPiFrontend
1057
+ });
1058
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
1059
+ import { homedir as homedir2, tmpdir } from "os";
1060
+ import { join } from "path";
1061
+ import { main as runPiMain } from "@earendil-works/pi-coding-agent";
1062
+ import createPiRigExtension from "@rig/pi-rig";
1063
+ function setTemporaryEnv(updates) {
1064
+ const previous = new Map;
1065
+ for (const [key, value] of Object.entries(updates)) {
1066
+ previous.set(key, process.env[key]);
1067
+ process.env[key] = value;
1068
+ }
1069
+ return () => {
1070
+ for (const [key, value] of previous) {
1071
+ if (value === undefined)
1072
+ delete process.env[key];
1073
+ else
1074
+ process.env[key] = value;
1075
+ }
1076
+ };
1077
+ }
1078
+ function buildOperatorPiEnv(input) {
1079
+ return {
1080
+ PI_CODING_AGENT_SESSION_DIR: input.sessionDir,
1081
+ PI_SKIP_VERSION_CHECK: "1",
1082
+ PI_HIDDEN_COMMANDS: "import,fork,clone,tree,new,resume,trust",
1083
+ RIG_PI_OPERATOR_SESSION: "1",
1084
+ RIG_RUN_ID: input.runId,
1085
+ RIG_SERVER_URL: input.serverUrl,
1086
+ ...input.authToken ? { RIG_AUTH_TOKEN: input.authToken } : {},
1087
+ ...input.serverProjectRoot ? { RIG_PROJECT_ROOT: input.serverProjectRoot } : {}
1088
+ };
1089
+ }
1090
+ function shouldRequireOperatorTranscript(status) {
1091
+ return typeof status === "string" && TERMINAL_RUN_STATUSES.has(status.trim().toLowerCase());
1092
+ }
1093
+ function missingOperatorTranscriptMessage(runId, status) {
1094
+ const shortRun = runId.trim().slice(0, 8) || "unknown";
1095
+ const statusText = typeof status === "string" && status.trim() ? status.trim() : "terminal";
1096
+ 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.`;
1097
+ }
1098
+ function statusFromRunDetails(run) {
1099
+ if (!run || typeof run !== "object" || Array.isArray(run))
1100
+ return;
1101
+ const record = run;
1102
+ if (typeof record.status === "string")
1103
+ return record.status;
1104
+ const nested = record.run;
1105
+ return nested && typeof nested === "object" && !Array.isArray(nested) ? nested.status : undefined;
1106
+ }
1107
+ async function prepareOperatorConsole(context, runId, tempSessionDir) {
1108
+ const server = await ensureServerForCli(context.projectRoot);
1109
+ const localCwd = join(homedir2(), ".rig", "drones", runId.slice(0, 8));
1110
+ mkdirSync2(localCwd, { recursive: true });
1111
+ trustDroneCwd(localCwd);
1112
+ installRigPiTheme();
1113
+ let sessionFileArg = [];
1114
+ try {
1115
+ const payload = await requestServerJson(context, `/api/runs/${encodeURIComponent(runId)}/session-file`);
1116
+ if (payload?.ok && typeof payload.content === "string" && payload.content.trim()) {
1117
+ const fileName = typeof payload.fileName === "string" && payload.fileName.trim() ? payload.fileName.replace(/[^A-Za-z0-9._-]/g, "_") : `rig-run-${runId}.jsonl`;
1118
+ const localSessionPath = join(tempSessionDir, fileName);
1119
+ const content = payload.content.split(`
1120
+ `).map((line, index) => {
1121
+ if (index > 0 || !line.trim())
1122
+ return line;
1123
+ try {
1124
+ const header = JSON.parse(line);
1125
+ if (header.type === "session" && typeof header.cwd === "string") {
1126
+ return JSON.stringify({ ...header, cwd: localCwd });
1127
+ }
1128
+ } catch {}
1129
+ return line;
1130
+ }).join(`
1131
+ `);
1132
+ writeFileSync2(localSessionPath, content);
1133
+ sessionFileArg = ["--session", localSessionPath];
1134
+ }
1135
+ } catch {}
1136
+ if (sessionFileArg.length === 0) {
1137
+ const run = await getRunDetailsViaServer(context, runId).catch(() => null);
1138
+ const status = statusFromRunDetails(run);
1139
+ if (shouldRequireOperatorTranscript(status)) {
1140
+ throw new OperatorTranscriptUnavailableError(missingOperatorTranscriptMessage(runId, status));
1141
+ }
1142
+ }
1143
+ return { server, sessionFileArg };
1144
+ }
1145
+ function trustDroneCwd(localCwd) {
1146
+ try {
1147
+ const agentDir = join(homedir2(), ".pi", "agent");
1148
+ mkdirSync2(agentDir, { recursive: true });
1149
+ const trustPath = join(agentDir, "trust.json");
1150
+ const store = existsSync3(trustPath) ? JSON.parse(readFileSync3(trustPath, "utf8")) : {};
1151
+ if (store[localCwd] !== true) {
1152
+ store[localCwd] = true;
1153
+ writeFileSync2(trustPath, `${JSON.stringify(store, null, "\t")}
1154
+ `);
1155
+ }
1156
+ } catch {}
1157
+ }
1158
+ function installRigPiTheme() {
1159
+ try {
1160
+ const themesDir = join(homedir2(), ".pi", "agent", "themes");
1161
+ mkdirSync2(themesDir, { recursive: true });
1162
+ const themePath = join(themesDir, "rig.json");
1163
+ const next = `${JSON.stringify(RIG_PI_THEME, null, "\t")}
1164
+ `;
1165
+ if (!existsSync3(themePath) || readFileSync3(themePath, "utf8") !== next) {
1166
+ writeFileSync2(themePath, next);
1167
+ }
1168
+ } catch {}
1169
+ }
1170
+ async function runWithProcessExitGuard(body) {
1171
+ const realExit = process.exit;
1172
+ let exitCode = 0;
1173
+ let signalQuit = () => {};
1174
+ const quit = new Promise((resolve3) => {
1175
+ signalQuit = resolve3;
1176
+ });
1177
+ const guardedExit = (code) => {
1178
+ exitCode = typeof code === "number" ? code : 0;
1179
+ signalQuit();
1180
+ return;
1181
+ };
1182
+ process.exit = guardedExit;
1183
+ try {
1184
+ await Promise.race([Promise.resolve().then(body), quit]);
1185
+ } finally {
1186
+ process.exit = realExit;
1187
+ }
1188
+ return exitCode;
1189
+ }
1190
+ function runPiMainReturningOnQuit(args, options) {
1191
+ return runWithProcessExitGuard(() => runPiMain(args, options));
1192
+ }
1193
+ async function attachRunBundledPiFrontend(context, input) {
1194
+ const tempSessionDir = mkdtempSync(join(tmpdir(), "rig-pi-frontend-sessions-"));
1195
+ const { server, sessionFileArg } = await withSpinner(`Opening Pi console for run ${input.runId}\u2026`, () => prepareOperatorConsole(context, input.runId, tempSessionDir), { outputMode: context.outputMode });
1196
+ const restoreEnv = setTemporaryEnv(buildOperatorPiEnv({
1197
+ runId: input.runId,
1198
+ serverUrl: server.baseUrl,
1199
+ authToken: server.authToken,
1200
+ serverProjectRoot: server.serverProjectRoot,
1201
+ sessionDir: tempSessionDir
1202
+ }));
1203
+ const piRigExtensionFactory = (pi) => {
1204
+ createPiRigExtension(pi);
1205
+ };
1206
+ let detached = false;
1207
+ try {
1208
+ const piArgs = [
1209
+ "--offline",
1210
+ "--no-extensions",
1211
+ "--no-skills",
1212
+ "--no-prompt-templates",
1213
+ "--no-context-files",
1214
+ ...sessionFileArg
1215
+ ];
1216
+ const piOptions = { extensionFactories: [piRigExtensionFactory] };
1217
+ if (input.returnOnQuit) {
1218
+ await runPiMainReturningOnQuit(piArgs, piOptions);
1219
+ } else {
1220
+ await runPiMain(piArgs, piOptions);
1221
+ }
1222
+ detached = true;
1223
+ } finally {
1224
+ restoreEnv();
1225
+ rmSync(tempSessionDir, { recursive: true, force: true });
1226
+ }
1227
+ let run = { runId: input.runId, status: "unknown" };
1228
+ try {
1229
+ run = await getRunDetailsViaServer(context, input.runId);
1230
+ } catch {}
1231
+ return {
1232
+ run,
1233
+ logs: [],
1234
+ timeline: [],
1235
+ timelineCursor: null,
1236
+ steered: input.steered === true,
1237
+ detached,
1238
+ rendered: "stock Pi operator console with the pi-rig extension"
1239
+ };
1240
+ }
1241
+ var TERMINAL_RUN_STATUSES, OperatorTranscriptUnavailableError, RIG_PI_THEME;
1242
+ var init__pi_frontend = __esm(() => {
1243
+ init__server_client();
1244
+ init__async_ui();
1245
+ TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "stopped", "cancelled", "canceled", "closed", "merged", "needs_attention", "needs-attention"]);
1246
+ OperatorTranscriptUnavailableError = class OperatorTranscriptUnavailableError extends Error {
1247
+ constructor(message) {
1248
+ super(message);
1249
+ this.name = "OperatorTranscriptUnavailableError";
1250
+ }
1251
+ };
1252
+ RIG_PI_THEME = {
1253
+ $schema: "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
1254
+ name: "rig",
1255
+ vars: {
1256
+ acid: "#ccff4d",
1257
+ acidDim: "#a9d63f",
1258
+ cyan: "#56d8ff",
1259
+ red: "#ff5d5d",
1260
+ yellow: "#ffd24d",
1261
+ ink: "#f2f3f6",
1262
+ ink2: "#aeb0ba",
1263
+ ink3: "#6c6e79",
1264
+ ink4: "#44464f",
1265
+ panel: "#101115",
1266
+ panelUser: "#14161b",
1267
+ toolPending: "#0e1013",
1268
+ toolSuccess: "#10150c",
1269
+ toolError: "#1a0f0f",
1270
+ customMsg: "#0f1410"
1271
+ },
1272
+ colors: {
1273
+ accent: "acid",
1274
+ border: "ink4",
1275
+ borderAccent: "acid",
1276
+ borderMuted: "ink4",
1277
+ success: "acid",
1278
+ error: "red",
1279
+ warning: "yellow",
1280
+ muted: "ink3",
1281
+ dim: "ink4",
1282
+ text: "ink",
1283
+ thinkingText: "ink3",
1284
+ selectedBg: "panel",
1285
+ userMessageBg: "panelUser",
1286
+ userMessageText: "ink",
1287
+ customMessageBg: "customMsg",
1288
+ customMessageText: "ink2",
1289
+ customMessageLabel: "acidDim",
1290
+ toolPendingBg: "toolPending",
1291
+ toolSuccessBg: "toolSuccess",
1292
+ toolErrorBg: "toolError",
1293
+ toolTitle: "ink",
1294
+ toolOutput: "ink3",
1295
+ mdHeading: "acid",
1296
+ mdLink: "cyan",
1297
+ mdLinkUrl: "ink4",
1298
+ mdCode: "acidDim",
1299
+ mdCodeBlock: "ink2",
1300
+ mdCodeBlockBorder: "ink4",
1301
+ mdQuote: "ink3",
1302
+ mdQuoteBorder: "ink4",
1303
+ mdHr: "ink4",
1304
+ mdListBullet: "acid",
1305
+ toolDiffAdded: "acid",
1306
+ toolDiffRemoved: "red",
1307
+ toolDiffContext: "ink3",
1308
+ syntaxComment: "ink3",
1309
+ syntaxKeyword: "cyan",
1310
+ syntaxFunction: "acid",
1311
+ syntaxVariable: "ink",
1312
+ syntaxString: "acidDim",
1313
+ syntaxNumber: "yellow",
1314
+ syntaxType: "cyan",
1315
+ syntaxOperator: "ink2",
1316
+ syntaxPunctuation: "ink3",
1317
+ thinkingOff: "ink4",
1318
+ thinkingMinimal: "ink3",
1319
+ thinkingLow: "ink2",
1320
+ thinkingMedium: "cyan",
1321
+ thinkingHigh: "acidDim",
1322
+ thinkingXhigh: "acid",
1323
+ bashMode: "cyan"
1324
+ }
1325
+ };
1326
+ });
1327
+
833
1328
  // packages/cli/src/app-opentui/adapters/inspect.ts
834
1329
  var exports_inspect = {};
835
1330
  __export(exports_inspect, {
@@ -838,7 +1333,7 @@ __export(exports_inspect, {
838
1333
  INSPECT_VIEWS: () => INSPECT_VIEWS
839
1334
  });
840
1335
  import { execFile } from "child_process";
841
- import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync, statSync } from "fs";
1336
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync, statSync } from "fs";
842
1337
  import { resolve as resolve3 } from "path";
843
1338
  import { promisify } from "util";
844
1339
  import { resolveTaskArtifactDirs } from "@rig/runtime/control-plane/authority-files";
@@ -860,7 +1355,7 @@ function listArtifacts(projectRoot, taskId) {
860
1355
  if (!taskId)
861
1356
  return { artifacts: [], error: "run has no task id \u2014 artifacts are resolved per task" };
862
1357
  try {
863
- const dirs = resolveTaskArtifactDirs(projectRoot, taskId).filter((dir) => existsSync3(dir));
1358
+ const dirs = resolveTaskArtifactDirs(projectRoot, taskId).filter((dir) => existsSync4(dir));
864
1359
  const out = [];
865
1360
  const seen = new Set;
866
1361
  for (const dir of dirs) {
@@ -906,9 +1401,9 @@ function loadGraph(projectRoot) {
906
1401
  function loadAudit(projectRoot) {
907
1402
  try {
908
1403
  const auditPath = resolve3(resolveHarnessPaths(projectRoot).logsDir, "audit.jsonl");
909
- if (!existsSync3(auditPath))
1404
+ if (!existsSync4(auditPath))
910
1405
  return [];
911
- return readFileSync3(auditPath, "utf-8").split(/\r?\n/).filter(Boolean).slice(-50).flatMap((raw) => {
1406
+ return readFileSync4(auditPath, "utf-8").split(/\r?\n/).filter(Boolean).slice(-50).flatMap((raw) => {
912
1407
  try {
913
1408
  const parsed = JSON.parse(raw);
914
1409
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? [parsed] : [{ detail: raw }];
@@ -1027,396 +1522,6 @@ var init_inspect = __esm(() => {
1027
1522
  "audit"
1028
1523
  ];
1029
1524
  });
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
1525
  // packages/cli/src/app-opentui/adapters/fleet.ts
1421
1526
  function normalizeRunRecord(record) {
1422
1527
  const runId = stringField(record, ["runId", "id"]);
@@ -1478,14 +1583,6 @@ function recordStep(ctx, runId, label, emitLabel) {
1478
1583
  });
1479
1584
  emitProgress(ctx, emitLabel, label);
1480
1585
  }
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
1586
  async function preparePiAttachHandoff(ctx, runId) {
1490
1587
  const cleanRunId = runId.trim();
1491
1588
  const label = `Preparing Pi ${cleanRunId.slice(0, 8)}`;
@@ -1533,82 +1630,39 @@ async function attachRunWithBundledPi(ctx, runId) {
1533
1630
  throw error;
1534
1631
  }
1535
1632
  emitStarted(ctx, label, { piAttach: { runId: cleanRunId, status: "entering-pi" } });
1536
- patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "starting bundled Pi", steps: [] } });
1633
+ patchData(ctx, { piAttach: { runId: cleanRunId, status: "entering-pi", message: "handing the terminal to worker Pi\u2026" } });
1634
+ const projectRoot = projectRootOf(ctx);
1635
+ const outputMode = ctx.rig?.outputMode ?? "text";
1636
+ await releaseRendererForExternalTui(ctx);
1637
+ let outcome = null;
1638
+ let attachError = null;
1537
1639
  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;
1640
+ const { attachRunBundledPiFrontend: attachRunBundledPiFrontend2 } = await Promise.resolve().then(() => (init__pi_frontend(), exports__pi_frontend));
1641
+ outcome = await attachRunBundledPiFrontend2({ projectRoot, outputMode }, { runId: cleanRunId, returnOnQuit: true });
1598
1642
  } catch (error) {
1599
- const reason = error instanceof Error ? error.message : String(error);
1643
+ attachError = error;
1644
+ } finally {
1645
+ await resumeRendererAfterExternalTui(ctx);
1646
+ }
1647
+ if (attachError) {
1648
+ const reason = normalizeAppError(attachError).message;
1600
1649
  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
- }
1650
+ piTerminal: undefined,
1651
+ piAttach: { runId: cleanRunId, status: "failed", message: reason, failureReason: reason }
1608
1652
  });
1609
- emitFailed(ctx, label, error, { runId: cleanRunId });
1610
- throw error;
1653
+ Promise.resolve().then(() => (init_inspect(), exports_inspect)).then(({ loadInspect: loadInspect2 }) => loadInspect2(ctx, cleanRunId)).catch(() => null);
1654
+ emitFailed(ctx, label, attachError, { runId: cleanRunId });
1655
+ throw attachError;
1611
1656
  }
1657
+ const detached = outcome?.detached === true;
1658
+ patchData(ctx, {
1659
+ piTerminal: undefined,
1660
+ piAttach: { runId: cleanRunId, status: "returned", message: detached ? "detached from worker Pi" : "returned from worker Pi" }
1661
+ });
1662
+ emitCompleted(ctx, label, { runId: cleanRunId, result: { runId: cleanRunId, detached } });
1663
+ ctx.emit({ type: "scene.change", scene: "fleet", intent: { scene: "fleet", argv: ["runs"], action: { kind: "refresh", label: "Opening runs" } } });
1664
+ refreshFleet(ctx).catch((error) => emitFailed(ctx, "Refresh runs", error));
1665
+ return { runId: cleanRunId, status: "returned", detached };
1612
1666
  }
1613
1667
  export {
1614
1668
  preparePiAttachHandoff,