glimmervoid 0.49.1-next.543 → 0.49.1-next.545

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 (84) hide show
  1. package/dist/chunks/{main-Zn2sHr8C.js → main-kngM7nsP.js} +602 -464
  2. package/dist/client/assets/{benchmark-panel-yuZJn32u.js → benchmark-panel-CZoHN_0Z.js} +1 -1
  3. package/dist/client/assets/benchmark-panel-CZoHN_0Z.js.br +0 -0
  4. package/dist/client/assets/{boards-view-DrXtjn4x.js → boards-view-0hW6lkva.js} +1 -1
  5. package/dist/client/assets/boards-view-0hW6lkva.js.br +0 -0
  6. package/dist/client/assets/{community-panel-BeD47JTx.js → community-panel-CmSsVWBy.js} +1 -1
  7. package/dist/client/assets/community-panel-CmSsVWBy.js.br +0 -0
  8. package/dist/client/assets/{dialogs-DEnOoD4g.js → dialogs-C1JgVkCl.js} +1 -1
  9. package/dist/client/assets/dialogs-C1JgVkCl.js.br +0 -0
  10. package/dist/client/assets/{doc-editor-ui-CJXCKcOc.js → doc-editor-ui-B-8REtdH.js} +1 -1
  11. package/dist/client/assets/doc-editor-ui-B-8REtdH.js.br +0 -0
  12. package/dist/client/assets/{feature-hint-eAiLcLLi.js → feature-hint-DBFiLrtM.js} +1 -1
  13. package/dist/client/assets/feature-hint-DBFiLrtM.js.br +0 -0
  14. package/dist/client/assets/{first-run-checklist-DCFqYML6.js → first-run-checklist-BH9FBVqg.js} +1 -1
  15. package/dist/client/assets/first-run-checklist-BH9FBVqg.js.br +0 -0
  16. package/dist/client/assets/{hooks-panel-BaVy5SNe.js → hooks-panel-Xxum_jet.js} +1 -1
  17. package/dist/client/assets/hooks-panel-Xxum_jet.js.br +0 -0
  18. package/dist/client/assets/{index-Dwwrw5iF.js → index-DI6o7rGH.js} +5 -5
  19. package/dist/client/assets/index-DI6o7rGH.js.br +0 -0
  20. package/dist/client/assets/{issues-panel-Db23FQst.js → issues-panel-C5xv0p5V.js} +1 -1
  21. package/dist/client/assets/issues-panel-C5xv0p5V.js.br +0 -0
  22. package/dist/client/assets/{my-prs-panel-C1RvnKQj.js → my-prs-panel-BBLC7nfh.js} +1 -1
  23. package/dist/client/assets/my-prs-panel-BBLC7nfh.js.br +0 -0
  24. package/dist/client/assets/{nyan-cat-CC6Hj8Si.js → nyan-cat-CiUobSoH.js} +1 -1
  25. package/dist/client/assets/nyan-cat-CiUobSoH.js.br +0 -0
  26. package/dist/client/assets/{phone-shell-DJpppy6T.js → phone-shell-rMLztheW.js} +1 -1
  27. package/dist/client/assets/phone-shell-rMLztheW.js.br +0 -0
  28. package/dist/client/assets/{plan-face-CpOcOIGL.js → plan-face-hbwZGQp-.js} +1 -1
  29. package/dist/client/assets/plan-face-hbwZGQp-.js.br +0 -0
  30. package/dist/client/assets/{plan-render-8MLmW4O4.js → plan-render-lkJvjRvG.js} +1 -1
  31. package/dist/client/assets/plan-render-lkJvjRvG.js.br +0 -0
  32. package/dist/client/assets/{pr-queue-columns-C5-a18oP.js → pr-queue-columns-ZQyQE-Ro.js} +1 -1
  33. package/dist/client/assets/pr-queue-columns-ZQyQE-Ro.js.br +0 -0
  34. package/dist/client/assets/{radar-panel-BvtZS7kb.js → radar-panel-D2yAYg1d.js} +1 -1
  35. package/dist/client/assets/radar-panel-D2yAYg1d.js.br +0 -0
  36. package/dist/client/assets/{repo-roots-adder-DN7ktit5.js → repo-roots-adder-Gs-qdNfB.js} +1 -1
  37. package/dist/client/assets/repo-roots-adder-Gs-qdNfB.js.br +0 -0
  38. package/dist/client/assets/{resume-dialog-V3WpErGL.js → resume-dialog-BQOjuwEs.js} +1 -1
  39. package/dist/client/assets/resume-dialog-BQOjuwEs.js.br +0 -0
  40. package/dist/client/assets/{review-queue-panel-TDNPBbBE.js → review-queue-panel-BEzjHFln.js} +1 -1
  41. package/dist/client/assets/review-queue-panel-BEzjHFln.js.br +0 -0
  42. package/dist/client/assets/settings-panel-DAzl-OG2.js +4 -0
  43. package/dist/client/assets/settings-panel-DAzl-OG2.js.br +0 -0
  44. package/dist/client/assets/{shown-face-BkBrHzQ_.js → shown-face-DDq1psSy.js} +1 -1
  45. package/dist/client/assets/shown-face-DDq1psSy.js.br +0 -0
  46. package/dist/client/assets/{team-review-panel-0I4rrL0A.js → team-review-panel-gzDAuuuZ.js} +1 -1
  47. package/dist/client/assets/team-review-panel-gzDAuuuZ.js.br +0 -0
  48. package/dist/client/assets/{trace-panel-B_-QaQLF.js → trace-panel-DwgSp1Ys.js} +1 -1
  49. package/dist/client/assets/trace-panel-DwgSp1Ys.js.br +0 -0
  50. package/dist/client/assets/{usage-panel-DQdCA298.js → usage-panel-CruNSfkC.js} +1 -1
  51. package/dist/client/assets/usage-panel-CruNSfkC.js.br +0 -0
  52. package/dist/client/assets/{your-day-tip-Cr4QXofT.js → your-day-tip-XR4QFUTf.js} +1 -1
  53. package/dist/client/assets/your-day-tip-XR4QFUTf.js.br +2 -0
  54. package/dist/client/index.html +1 -1
  55. package/dist/client/index.html.br +0 -0
  56. package/dist/server/index.js +1 -1
  57. package/package.json +1 -1
  58. package/dist/client/assets/benchmark-panel-yuZJn32u.js.br +0 -0
  59. package/dist/client/assets/boards-view-DrXtjn4x.js.br +0 -0
  60. package/dist/client/assets/community-panel-BeD47JTx.js.br +0 -0
  61. package/dist/client/assets/dialogs-DEnOoD4g.js.br +0 -0
  62. package/dist/client/assets/doc-editor-ui-CJXCKcOc.js.br +0 -0
  63. package/dist/client/assets/feature-hint-eAiLcLLi.js.br +0 -0
  64. package/dist/client/assets/first-run-checklist-DCFqYML6.js.br +0 -0
  65. package/dist/client/assets/hooks-panel-BaVy5SNe.js.br +0 -0
  66. package/dist/client/assets/index-Dwwrw5iF.js.br +0 -0
  67. package/dist/client/assets/issues-panel-Db23FQst.js.br +0 -0
  68. package/dist/client/assets/my-prs-panel-C1RvnKQj.js.br +0 -0
  69. package/dist/client/assets/nyan-cat-CC6Hj8Si.js.br +0 -0
  70. package/dist/client/assets/phone-shell-DJpppy6T.js.br +0 -0
  71. package/dist/client/assets/plan-face-CpOcOIGL.js.br +0 -0
  72. package/dist/client/assets/plan-render-8MLmW4O4.js.br +0 -0
  73. package/dist/client/assets/pr-queue-columns-C5-a18oP.js.br +0 -0
  74. package/dist/client/assets/radar-panel-BvtZS7kb.js.br +0 -0
  75. package/dist/client/assets/repo-roots-adder-DN7ktit5.js.br +0 -0
  76. package/dist/client/assets/resume-dialog-V3WpErGL.js.br +0 -0
  77. package/dist/client/assets/review-queue-panel-TDNPBbBE.js.br +0 -0
  78. package/dist/client/assets/settings-panel-Cjf8WvjF.js +0 -4
  79. package/dist/client/assets/settings-panel-Cjf8WvjF.js.br +0 -0
  80. package/dist/client/assets/shown-face-BkBrHzQ_.js.br +0 -0
  81. package/dist/client/assets/team-review-panel-0I4rrL0A.js.br +0 -0
  82. package/dist/client/assets/trace-panel-B_-QaQLF.js.br +0 -0
  83. package/dist/client/assets/usage-panel-DQdCA298.js.br +0 -0
  84. package/dist/client/assets/your-day-tip-Cr4QXofT.js.br +0 -0
@@ -14448,20 +14448,6 @@ async function readTranscriptTaskTitle(transcriptPath) {
14448
14448
  }
14449
14449
  }
14450
14450
  //#endregion
14451
- //#region session/core/commit-signing-env.ts
14452
- var GIT_CONFIG_PARAMETERS_ENV = "GIT_CONFIG_PARAMETERS";
14453
- function singleQuoteForGit(text) {
14454
- return `'${text.replace(/'/g, "'\\''").replace(/!/g, "'\\!'")}'`;
14455
- }
14456
- function commitSigningEnv({ port, sessionId, token, signingProgram, inheritedConfigParameters }) {
14457
- if (!port || !token || !signingProgram) return {};
14458
- const programParameter = singleQuoteForGit(`gpg.ssh.program=${signingProgram}`);
14459
- return {
14460
- [SIGN_URL_ENV]: `http://127.0.0.1:${port}/sign/${encodeURIComponent(sessionId)}?t=${encodeURIComponent(token)}`,
14461
- [GIT_CONFIG_PARAMETERS_ENV]: inheritedConfigParameters ? `${inheritedConfigParameters} ${programParameter}` : programParameter
14462
- };
14463
- }
14464
- //#endregion
14465
14451
  //#region detection/osc-title-source.ts
14466
14452
  var DEFAULT_STABILIZATION_MS = 1500;
14467
14453
  var OSC_START = "\x1B]0;";
@@ -19261,6 +19247,82 @@ function createSessionWorktreeLifecycle({ id, projectPath, integrationBranch = n
19261
19247
  return api;
19262
19248
  }
19263
19249
  //#endregion
19250
+ //#region session/session-approval-holds.ts
19251
+ function createSessionApprovalHolds({ agentId, holdsQuestionsForParent, port }) {
19252
+ let conversationApproval = null;
19253
+ let holds = [];
19254
+ let nextApprovalNumber = 1;
19255
+ function setConversationApproval(approval) {
19256
+ conversationApproval = approval;
19257
+ emitConversationChange();
19258
+ }
19259
+ function emitConversationChange() {
19260
+ port.emit("conversation-change", { conversationApproval });
19261
+ }
19262
+ function hold(payload, abandoned) {
19263
+ if (agentId !== "claude-code") return null;
19264
+ const request = parseClaudePermissionRequest(payload);
19265
+ if (!request) return null;
19266
+ if (!holdsQuestionsForParent || request.toolName !== "AskUserQuestion") return null;
19267
+ releaseHolds((hold) => hold.request.agentKey === request.agentKey);
19268
+ const requestId = `claude-${nextApprovalNumber}`;
19269
+ nextApprovalNumber += 1;
19270
+ return new Promise((resolve) => {
19271
+ const hold = {
19272
+ request,
19273
+ approval: claudeApprovalFor(request, requestId),
19274
+ resolve
19275
+ };
19276
+ holds.push(hold);
19277
+ abandoned.addEventListener("abort", () => releaseHolds((candidate) => candidate === hold), { once: true });
19278
+ showFirstApproval();
19279
+ });
19280
+ }
19281
+ function releaseAfterHookEvent(event, payload) {
19282
+ if (holds.length === 0) return;
19283
+ releaseHolds((hold) => isHoldReleasedByHookEvent(hold.request, event, payload));
19284
+ }
19285
+ function releaseHolds(isReleased) {
19286
+ const released = holds.filter(isReleased);
19287
+ if (released.length === 0) return;
19288
+ holds = holds.filter((hold) => !released.includes(hold));
19289
+ for (const hold of released) hold.resolve(null);
19290
+ showFirstApproval();
19291
+ }
19292
+ function showFirstApproval() {
19293
+ setConversationApproval(holds[0]?.approval ?? null);
19294
+ }
19295
+ function answer(requestId, answers) {
19296
+ const hold = holds.find((candidate) => candidate.approval.requestId === requestId);
19297
+ if (!hold) return false;
19298
+ const reply = claudeAnswerReply(hold.request, hold.approval, answers);
19299
+ if (!reply) return false;
19300
+ holds = holds.filter((candidate) => candidate !== hold);
19301
+ hold.resolve(reply);
19302
+ showFirstApproval();
19303
+ return true;
19304
+ }
19305
+ function release(requestId) {
19306
+ const hold = holds.find((candidate) => candidate.approval.requestId === requestId);
19307
+ if (!hold) return false;
19308
+ releaseHolds((candidate) => candidate === hold);
19309
+ return true;
19310
+ }
19311
+ function releaseAll() {
19312
+ releaseHolds(() => true);
19313
+ }
19314
+ return {
19315
+ get conversationApproval() {
19316
+ return conversationApproval;
19317
+ },
19318
+ hold,
19319
+ releaseAfterHookEvent,
19320
+ releaseAll,
19321
+ answer,
19322
+ release
19323
+ };
19324
+ }
19325
+ //#endregion
19264
19326
  //#region session/core/wakeup-tracker.ts
19265
19327
  var DEFAULT_CRON_TTL_MS = 6048e5;
19266
19328
  var MAX_WAKEUPS = 64;
@@ -19662,74 +19724,457 @@ function createSessionBackgroundTracking({ detectBackgroundAgents, agentTtlMs, s
19662
19724
  };
19663
19725
  }
19664
19726
  //#endregion
19665
- //#region session/sessions.ts
19727
+ //#region session/core/commit-signing-env.ts
19728
+ var GIT_CONFIG_PARAMETERS_ENV = "GIT_CONFIG_PARAMETERS";
19729
+ function singleQuoteForGit(text) {
19730
+ return `'${text.replace(/'/g, "'\\''").replace(/!/g, "'\\!'")}'`;
19731
+ }
19732
+ function commitSigningEnv({ port, sessionId, token, signingProgram, inheritedConfigParameters }) {
19733
+ if (!port || !token || !signingProgram) return {};
19734
+ const programParameter = singleQuoteForGit(`gpg.ssh.program=${signingProgram}`);
19735
+ return {
19736
+ [SIGN_URL_ENV]: `http://127.0.0.1:${port}/sign/${encodeURIComponent(sessionId)}?t=${encodeURIComponent(token)}`,
19737
+ [GIT_CONFIG_PARAMETERS_ENV]: inheritedConfigParameters ? `${inheritedConfigParameters} ${programParameter}` : programParameter
19738
+ };
19739
+ }
19740
+ //#endregion
19741
+ //#region session/session-launch.ts
19742
+ var REMOTE_CODEX_STARTUP_TIMEOUT_MS = 3e5;
19743
+ function createSessionLaunch({ id, adapter, platform, startCodexBridge, getRemoteLaunch, hooks, port }) {
19744
+ let codexBridge = null;
19745
+ let hasRespawnedForAuth = false;
19746
+ function agentApiEnv() {
19747
+ const agentToken = port.agentToken();
19748
+ if (!agentToken) return {};
19749
+ const listenerPort = hooks.listenerPort();
19750
+ if (!listenerPort) return {};
19751
+ const url = `http://127.0.0.1:${listenerPort}/agent/${encodeURIComponent(id)}?t=${encodeURIComponent(agentToken)}`;
19752
+ return { [AGENT_URL_ENV]: url };
19753
+ }
19754
+ function signingEnv() {
19755
+ if (getRemoteLaunch() !== null) return {};
19756
+ return commitSigningEnv({
19757
+ port: hooks.listenerPort(),
19758
+ sessionId: id,
19759
+ token: port.commitSigningToken(),
19760
+ signingProgram: port.commitSigningProgram(),
19761
+ inheritedConfigParameters: port.spawnEnv()?.GIT_CONFIG_PARAMETERS ?? process.env.GIT_CONFIG_PARAMETERS
19762
+ });
19763
+ }
19764
+ function spawnCwdSpellings() {
19765
+ const spawnCwd = port.effectiveCwd();
19766
+ try {
19767
+ return Array.from(/* @__PURE__ */ new Set([spawnCwd, fs.realpathSync.native(spawnCwd)]));
19768
+ } catch {
19769
+ return [spawnCwd];
19770
+ }
19771
+ }
19772
+ async function stopCodexBridge() {
19773
+ const bridge = codexBridge;
19774
+ if (!bridge) return;
19775
+ codexBridge = null;
19776
+ await bridge.stop().catch((error) => console.warn(`[session:${port.name()}] codex app-server stop failed: ${errorMessage(error)}`));
19777
+ }
19778
+ async function spawnCommandFor({ remoteLaunch, isRemoteCodex, settingsArgs, agentArgs, bridgedLaunch }) {
19779
+ if (remoteLaunch !== null && !isRemoteCodex) return remoteSpawnCommand(remoteLaunch, agentArgs);
19780
+ const command = adapter.buildSpawnCommand({
19781
+ platform,
19782
+ resolved: port.spawnCommand() || commandFor(adapter),
19783
+ settingsArgs: bridgedLaunch ? [] : settingsArgs,
19784
+ agentArgs: bridgedLaunch?.tuiArgs ?? agentArgs
19785
+ });
19786
+ return {
19787
+ file: command.file,
19788
+ args: command.args,
19789
+ env: {}
19790
+ };
19791
+ }
19792
+ async function startRemoteCodexBridge(remote, agentArgs, env) {
19793
+ await stopCodexBridge();
19794
+ const prepared = await prepareRemoteCodexBridge(remote, agentArgs, env).catch((error) => ({
19795
+ ok: false,
19796
+ reason: errorMessage(error)
19797
+ }));
19798
+ if (port.isDestroyed()) {
19799
+ hooks.cleanup();
19800
+ await stopCodexBridge();
19801
+ return null;
19802
+ }
19803
+ if (!prepared.ok) {
19804
+ port.abandonSpawn(/* @__PURE__ */ new Error(`Coder workspace ${remote.workspace}: ${prepared.reason}`));
19805
+ return null;
19806
+ }
19807
+ return prepared.launch;
19808
+ }
19809
+ async function prepareRemoteCodexBridge(remote, agentArgs, env) {
19810
+ const running = await remote.ensureRunning();
19811
+ if (!running.ok) return running;
19812
+ const version = await remote.codexVersion();
19813
+ if (version === null) return {
19814
+ ok: false,
19815
+ reason: "the host codex version could not be read, so the workspace cannot install a matching codex"
19816
+ };
19817
+ const launch = splitCodexRemoteLaunch(agentArgs, port.promptSupervisionLine());
19818
+ const bridge = await startCodexBridge({
19819
+ command: {
19820
+ file: "coder",
19821
+ argsBeforeAppServer: []
19822
+ },
19823
+ configArgs: launch.appServerConfigArgs,
19824
+ cwd: port.effectiveCwd(),
19825
+ env: { ...env },
19826
+ tokenParentDirectory: os.tmpdir(),
19827
+ startupTimeoutMs: REMOTE_CODEX_STARTUP_TIMEOUT_MS,
19828
+ remote: {
19829
+ launch: (appServerArgs) => {
19830
+ const script = remoteCodexAppServerScript({
19831
+ version,
19832
+ workingDirectory: remote.checkoutDirectory,
19833
+ appServerArgs
19834
+ });
19835
+ const sshArgs = script === null ? null : coderSshExecArgs({
19836
+ workspace: remote.workspace,
19837
+ remoteCommand: script
19838
+ });
19839
+ if (sshArgs === null) throw new Error("the remote Codex app-server command could not be built");
19840
+ return {
19841
+ file: "coder",
19842
+ args: sshArgs
19843
+ };
19844
+ },
19845
+ forward: (remotePort) => startCoderPortForward({
19846
+ workspace: remote.workspace,
19847
+ remotePort
19848
+ }),
19849
+ login: remote.codexLoginParams,
19850
+ refreshLogin: remote.codexRefreshResult
19851
+ }
19852
+ });
19853
+ attachCodexBridge(bridge);
19854
+ return {
19855
+ ok: true,
19856
+ launch: {
19857
+ tuiArgs: remoteTuiArgs(bridge.url, launch.tuiArgs),
19858
+ token: bridge.token
19859
+ }
19860
+ };
19861
+ }
19862
+ function attachCodexBridge(bridge) {
19863
+ codexBridge = bridge;
19864
+ bridge.on("records", (records) => port.emit("conversation-records", { records }));
19865
+ bridge.on("error", (error) => console.warn(`[session:${port.name()}] codex app-server bridge: ${errorMessage(error)}`));
19866
+ bridge.on("exit", () => {
19867
+ if (codexBridge !== bridge) return;
19868
+ codexBridge = null;
19869
+ });
19870
+ }
19871
+ async function remoteSpawnCommand(remote, agentArgs) {
19872
+ const prepared = await prepareRemoteSpawn(remote, agentArgs).catch((error) => ({
19873
+ ok: false,
19874
+ reason: errorMessage(error)
19875
+ }));
19876
+ if (port.isDestroyed()) {
19877
+ hooks.cleanup();
19878
+ return null;
19879
+ }
19880
+ if (!prepared.ok) {
19881
+ port.abandonSpawn(/* @__PURE__ */ new Error(`Coder workspace ${remote.workspace}: ${prepared.reason}`));
19882
+ return null;
19883
+ }
19884
+ return prepared.spawnCommand;
19885
+ }
19886
+ async function prepareRemoteSpawn(remote, agentArgs) {
19887
+ const hookToken = hooks.token();
19888
+ const ingressPort = hooks.listenerPort();
19889
+ if (hookToken === null || ingressPort === null) return {
19890
+ ok: false,
19891
+ reason: "hooks are unavailable, so the remote session could not report its status"
19892
+ };
19893
+ const running = await remote.ensureRunning();
19894
+ if (!running.ok) return running;
19895
+ const login = await remote.claudeToken();
19896
+ if (!login.ok) return login;
19897
+ const settingsPath = path.posix.join(path.posix.dirname(remote.checkoutDirectory), ".glimmervoid-sessions", safePathSegment(id), "settings.json");
19898
+ const settings = buildHookSettings({
19899
+ port: remote.remotePort,
19900
+ glimmervoidId: id,
19901
+ token: hookToken,
19902
+ remoteNodePath: remote.nodePath
19903
+ });
19904
+ await remote.uploadFile({
19905
+ remotePath: settingsPath,
19906
+ contents: JSON.stringify(settings),
19907
+ mode: 384
19908
+ });
19909
+ const remoteCommand = remoteLaunchScript({
19910
+ workingDirectory: remote.checkoutDirectory,
19911
+ argv: [
19912
+ "claude",
19913
+ ...adapter.settingsArgs?.(settingsPath) ?? [],
19914
+ ...agentArgs
19915
+ ],
19916
+ tokenAliases: CLAUDE_TOKEN_ALIASES
19917
+ });
19918
+ const sshArgs = remoteCommand === null ? null : coderSshArgs({
19919
+ workspace: remote.workspace,
19920
+ remotePort: remote.remotePort,
19921
+ ingressPort,
19922
+ remoteCommand
19923
+ });
19924
+ const sshEnv = encodeCoderSshEnv({ [CLAUDE_TOKEN_ALIAS_ENV]: login.token });
19925
+ if (sshArgs === null || sshEnv === null) return {
19926
+ ok: false,
19927
+ reason: "the remote launch command could not be built"
19928
+ };
19929
+ return {
19930
+ ok: true,
19931
+ spawnCommand: {
19932
+ file: "coder",
19933
+ args: sshArgs,
19934
+ env: { [CODER_SSH_ENV]: sshEnv }
19935
+ }
19936
+ };
19937
+ }
19938
+ function respawnAfterAuthFailure() {
19939
+ if (getRemoteLaunch() === null || hasRespawnedForAuth) return false;
19940
+ hasRespawnedForAuth = true;
19941
+ console.warn(`[session:${port.name()}] the remote Claude token was refused; respawning once with a fresh token`);
19942
+ return port.forceRestart({ resumePrompt: AUTO_CONTINUE_PROMPT });
19943
+ }
19944
+ function buildEnv({ extraEnv = port.spawnEnv(), ...options } = {}) {
19945
+ return adapter.buildEnv(process.env, extraEnv, options);
19946
+ }
19947
+ function noteTurnStopped() {
19948
+ hasRespawnedForAuth = false;
19949
+ }
19950
+ return {
19951
+ buildEnv,
19952
+ agentApiEnv,
19953
+ commitSigningEnv: signingEnv,
19954
+ spawnCwdSpellings,
19955
+ spawnCommandFor,
19956
+ startRemoteCodexBridge,
19957
+ stopCodexBridge,
19958
+ respawnAfterAuthFailure,
19959
+ noteTurnStopped
19960
+ };
19961
+ }
19962
+ //#endregion
19963
+ //#region session/session-process-reaper.ts
19666
19964
  var KILL_POLL_INTERVAL_MS = 200;
19667
19965
  var KILL_MAX_WAIT_MS = 3e3;
19668
19966
  var KILL_REAP_MAX_WAIT_MS = 2400;
19669
- var MAX_PENDING_ATTENTION_NOTES = 5;
19670
- var PTY_PROMPT_SETTLE_MS = 1500;
19671
- var PTY_PROMPT_SUBMIT_DELAY_MS = 300;
19672
- var PASTE_BREAKING_CONTROL_BYTES = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
19673
- var SPAWN_FAILURE_TEXT_BY_REASON = { spawn_cwd_missing: "The session folder no longer exists. Re-add the session on a folder that exists." };
19674
- var SPAWN_FAILURE_FALLBACK_TEXT = "The agent could not be started. The server log has the cause.";
19675
- function describeSpawnFailure(detail) {
19676
- if (typeof detail !== "object" || detail === null) return SPAWN_FAILURE_FALLBACK_TEXT;
19677
- if ("error" in detail && typeof detail.error === "string" && detail.error) return detail.error;
19678
- return SPAWN_FAILURE_TEXT_BY_REASON["reason" in detail && typeof detail.reason === "string" ? detail.reason : ""] ?? SPAWN_FAILURE_FALLBACK_TEXT;
19679
- }
19680
19967
  function signalablePid(pid) {
19681
19968
  const parsed = Number(pid);
19682
19969
  if (!Number.isInteger(parsed)) return null;
19683
19970
  if (parsed < 2) return null;
19684
19971
  return parsed;
19685
19972
  }
19686
- function nextPendingPromptToolName(currentKind, currentToolName, nextKind, incomingToolName, mayInheritCurrentToolName) {
19687
- if (nextKind !== "permission") return null;
19688
- if (incomingToolName) return incomingToolName;
19689
- if (mayInheritCurrentToolName && currentKind === "permission") return currentToolName;
19690
- return null;
19691
- }
19692
- var DISMISSIBLE_STATES = /* @__PURE__ */ new Set([STATES.WAITING, STATES.COMPLETE]);
19693
- var REMOTE_CODEX_STARTUP_TIMEOUT_MS = 3e5;
19694
- var Session = class extends EventEmitter {
19695
- customTitle;
19696
- taskTitle;
19697
- taskTitleIsCustom;
19698
- _taskTitleSources;
19699
- _taskTitleStateSignature;
19700
- _taskTitleReadSequence;
19701
- _recentTaskPrompts;
19702
- taskTitlePromptRevision;
19703
- _prLinks;
19704
- id;
19705
- name;
19706
- path;
19707
- dangerouslySkipPermissions;
19708
- ptyProcess;
19709
- state;
19710
- stateSince;
19711
- failureReason;
19712
- unseenOutcome;
19713
- ephemeral;
19714
- agentId;
19715
- usageVendor;
19716
- bypassHookTrust;
19717
- _holdsQuestionsForParent;
19718
- _startCodexBridge;
19719
- _codexBridge;
19720
- _conversationApproval;
19721
- _claudeApprovalHolds;
19722
- _nextClaudeApprovalNumber;
19723
- backgroundTracking;
19724
- worktreeLifecycle;
19973
+ function createSessionProcessReaper({ platform, killProc, signalProc, port }) {
19974
+ let killPollTimer = null;
19975
+ let killReapTimer = null;
19976
+ let resolveKillReap = null;
19977
+ let killReap = null;
19978
+ let exitReap = null;
19979
+ function clearKillPoll() {
19980
+ if (!killPollTimer) return;
19981
+ clearTimeout(killPollTimer);
19982
+ killPollTimer = null;
19983
+ }
19984
+ function clearKillReapTimer() {
19985
+ if (!killReapTimer) return;
19986
+ clearTimeout(killReapTimer);
19987
+ killReapTimer = null;
19988
+ }
19989
+ function taskkill(pid, opts = {}) {
19990
+ return new Promise((resolve, reject) => {
19991
+ killProc([
19992
+ "/PID",
19993
+ String(Number(pid)),
19994
+ "/T",
19995
+ "/F"
19996
+ ], { ...opts }, (err) => {
19997
+ if (err) return reject(err);
19998
+ resolve();
19999
+ });
20000
+ });
20001
+ }
20002
+ function killProcessGroup(pid, signal = "SIGKILL") {
20003
+ const target = signalablePid(pid);
20004
+ if (target === null) return;
20005
+ try {
20006
+ signalProc(-target, signal);
20007
+ } catch (err) {
20008
+ const code = err && typeof err === "object" && "code" in err ? err.code : void 0;
20009
+ if (err && code !== "ESRCH") port.emitError(err);
20010
+ }
20011
+ }
20012
+ function isProcessAlive(pid) {
20013
+ const target = signalablePid(pid);
20014
+ if (target === null) return false;
20015
+ const probeTarget = platform === "win32" ? target : -target;
20016
+ try {
20017
+ signalProc(probeTarget, 0);
20018
+ return true;
20019
+ } catch {
20020
+ return false;
20021
+ }
20022
+ }
20023
+ function awaitProcessGone(pid, maxWaitMs) {
20024
+ if (resolveKillReap) resolveKillReap();
20025
+ return new Promise((resolve) => {
20026
+ const settle = () => {
20027
+ clearKillReapTimer();
20028
+ resolveKillReap = null;
20029
+ resolve();
20030
+ };
20031
+ resolveKillReap = settle;
20032
+ let waited = 0;
20033
+ const poll = () => {
20034
+ if (!isProcessAlive(pid)) {
20035
+ settle();
20036
+ return;
20037
+ }
20038
+ waited += KILL_POLL_INTERVAL_MS;
20039
+ if (waited >= maxWaitMs) {
20040
+ settle();
20041
+ return;
20042
+ }
20043
+ clearKillReapTimer();
20044
+ killReapTimer = setTimeout(() => {
20045
+ killReapTimer = null;
20046
+ poll();
20047
+ }, KILL_POLL_INTERVAL_MS);
20048
+ };
20049
+ poll();
20050
+ });
20051
+ }
20052
+ function reapProcessGroup(pid, { maxWaitMs = KILL_REAP_MAX_WAIT_MS } = {}) {
20053
+ killProcessGroup(pid);
20054
+ return awaitProcessGone(pid, maxWaitMs);
20055
+ }
20056
+ function reapTreeOnce(pid) {
20057
+ if (platform === "win32") return taskkill(pid, { timeout: KILL_REAP_MAX_WAIT_MS }).catch(() => {});
20058
+ if (resolveKillReap) return killReap;
20059
+ return reapProcessGroup(pid);
20060
+ }
20061
+ function awaitPendingReaps() {
20062
+ const pending = [killReap, exitReap].filter((reap) => reap !== null);
20063
+ if (pending.length === 0) return null;
20064
+ return awaitBounded(pending, { capMs: KILL_REAP_MAX_WAIT_MS }).then(() => {});
20065
+ }
20066
+ function forceKillAfterTimeout(pid) {
20067
+ let elapsed = 0;
20068
+ const poll = () => {
20069
+ if (port.isDestroyed()) return;
20070
+ if (!isProcessAlive(pid)) return;
20071
+ elapsed += KILL_POLL_INTERVAL_MS;
20072
+ if (elapsed >= KILL_MAX_WAIT_MS) {
20073
+ if (platform === "win32") {
20074
+ taskkill(pid).catch((err) => port.emitError(err));
20075
+ return;
20076
+ }
20077
+ killProcessGroup(pid);
20078
+ return;
20079
+ }
20080
+ armKillPoll(poll);
20081
+ };
20082
+ armKillPoll(poll);
20083
+ }
20084
+ function armKillPoll(poll) {
20085
+ clearKillPoll();
20086
+ killPollTimer = setTimeout(() => {
20087
+ killPollTimer = null;
20088
+ poll();
20089
+ }, KILL_POLL_INTERVAL_MS);
20090
+ }
20091
+ function kill(pid) {
20092
+ if (platform === "win32") {
20093
+ const windowsKillReap = taskkill(pid);
20094
+ killReap = windowsKillReap;
20095
+ windowsKillReap.catch((err) => port.emitError(err));
20096
+ }
20097
+ if (platform !== "win32") killReap = reapProcessGroup(pid);
20098
+ forceKillAfterTimeout(pid);
20099
+ }
20100
+ return {
20101
+ kill,
20102
+ reapTreeOnce,
20103
+ awaitPendingReaps,
20104
+ isProcessAlive,
20105
+ clearKillPoll,
20106
+ get killReap() {
20107
+ return killReap;
20108
+ },
20109
+ set killReap(next) {
20110
+ killReap = next;
20111
+ },
20112
+ get exitReap() {
20113
+ return exitReap;
20114
+ },
20115
+ set exitReap(next) {
20116
+ exitReap = next;
20117
+ },
20118
+ get killPollTimer() {
20119
+ return killPollTimer;
20120
+ },
20121
+ get killReapTimer() {
20122
+ return killReapTimer;
20123
+ }
20124
+ };
20125
+ }
20126
+ //#endregion
20127
+ //#region session/sessions.ts
20128
+ var MAX_PENDING_ATTENTION_NOTES = 5;
20129
+ var PTY_PROMPT_SETTLE_MS = 1500;
20130
+ var PTY_PROMPT_SUBMIT_DELAY_MS = 300;
20131
+ var PASTE_BREAKING_CONTROL_BYTES = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
20132
+ var SPAWN_FAILURE_TEXT_BY_REASON = { spawn_cwd_missing: "The session folder no longer exists. Re-add the session on a folder that exists." };
20133
+ var SPAWN_FAILURE_FALLBACK_TEXT = "The agent could not be started. The server log has the cause.";
20134
+ function describeSpawnFailure(detail) {
20135
+ if (typeof detail !== "object" || detail === null) return SPAWN_FAILURE_FALLBACK_TEXT;
20136
+ if ("error" in detail && typeof detail.error === "string" && detail.error) return detail.error;
20137
+ return SPAWN_FAILURE_TEXT_BY_REASON["reason" in detail && typeof detail.reason === "string" ? detail.reason : ""] ?? SPAWN_FAILURE_FALLBACK_TEXT;
20138
+ }
20139
+ function nextPendingPromptToolName(currentKind, currentToolName, nextKind, incomingToolName, mayInheritCurrentToolName) {
20140
+ if (nextKind !== "permission") return null;
20141
+ if (incomingToolName) return incomingToolName;
20142
+ if (mayInheritCurrentToolName && currentKind === "permission") return currentToolName;
20143
+ return null;
20144
+ }
20145
+ var DISMISSIBLE_STATES = /* @__PURE__ */ new Set([STATES.WAITING, STATES.COMPLETE]);
20146
+ var Session = class extends EventEmitter {
20147
+ customTitle;
20148
+ taskTitle;
20149
+ taskTitleIsCustom;
20150
+ _taskTitleSources;
20151
+ _taskTitleStateSignature;
20152
+ _taskTitleReadSequence;
20153
+ _recentTaskPrompts;
20154
+ taskTitlePromptRevision;
20155
+ _prLinks;
20156
+ id;
20157
+ name;
20158
+ path;
20159
+ dangerouslySkipPermissions;
20160
+ ptyProcess;
20161
+ state;
20162
+ stateSince;
20163
+ failureReason;
20164
+ unseenOutcome;
20165
+ ephemeral;
20166
+ agentId;
20167
+ usageVendor;
20168
+ bypassHookTrust;
20169
+ _holdsQuestionsForParent;
20170
+ _launch;
20171
+ _approvals;
20172
+ backgroundTracking;
20173
+ worktreeLifecycle;
19725
20174
  _receivedFirstOutput;
19726
20175
  _hasPromptSinceSpawn;
19727
- _killPollTimer;
19728
- _killReapTimer;
19729
20176
  _titleQuietFallbackTimer;
19730
- _resolveKillReap;
19731
- _killReap;
19732
- _exitReap;
20177
+ _reaper;
19733
20178
  _destroyed;
19734
20179
  _pendingRestart;
19735
20180
  _finishing;
@@ -19782,10 +20227,7 @@ var Session = class extends EventEmitter {
19782
20227
  _agentSpawnsInFlight;
19783
20228
  _ptySpawn;
19784
20229
  _getRemoteLaunch;
19785
- _hasRespawnedForAuth;
19786
20230
  _requiresWorktree;
19787
- _killProc;
19788
- _signalProc;
19789
20231
  _platform;
19790
20232
  _startPending;
19791
20233
  _resizeSeq;
@@ -19820,11 +20262,6 @@ var Session = class extends EventEmitter {
19820
20262
  this.unseenOutcome = null;
19821
20263
  this._receivedFirstOutput = false;
19822
20264
  this._hasPromptSinceSpawn = false;
19823
- this._killPollTimer = null;
19824
- this._killReapTimer = null;
19825
- this._resolveKillReap = null;
19826
- this._killReap = null;
19827
- this._exitReap = null;
19828
20265
  this._destroyed = false;
19829
20266
  this._pendingRestart = false;
19830
20267
  this._finishing = false;
@@ -19864,11 +20301,11 @@ var Session = class extends EventEmitter {
19864
20301
  this.usageVendor = this._adapter.usageVendor || "claude";
19865
20302
  this.bypassHookTrust = bypassHookTrust === true;
19866
20303
  this._holdsQuestionsForParent = holdsQuestionsForParent;
19867
- this._startCodexBridge = startCodexBridge;
19868
- this._codexBridge = null;
19869
- this._conversationApproval = null;
19870
- this._claudeApprovalHolds = [];
19871
- this._nextClaudeApprovalNumber = 1;
20304
+ this._approvals = createSessionApprovalHolds({
20305
+ agentId: this.agentId,
20306
+ holdsQuestionsForParent,
20307
+ port: { emit: (event, detail) => this.emit(event, detail) }
20308
+ });
19872
20309
  this._titleQuietFallbackMs = titleQuietFallbackMs;
19873
20310
  this._titleQuietFallbackTimer = null;
19874
20311
  this._hookSeen = false;
@@ -19942,10 +20379,10 @@ var Session = class extends EventEmitter {
19942
20379
  requiresHooks: requiresHooks && hookRouter !== null,
19943
20380
  bypassHookTrust: this.bypassHookTrust,
19944
20381
  effectiveCwd: () => this.effectiveCwd(),
19945
- agentEnv: () => this._buildSpawnEnv(),
20382
+ agentEnv: () => this._launch.buildEnv(),
19946
20383
  ingestSignal: (raw) => this.ingestHookSignal(raw),
19947
20384
  observeHook: (event, payload) => {
19948
- this._releaseClaudeHoldsAfterHookEvent(event, payload);
20385
+ this._approvals.releaseAfterHookEvent(event, payload);
19949
20386
  this.emit("hook-event", {
19950
20387
  event,
19951
20388
  payload
@@ -19967,9 +20404,37 @@ var Session = class extends EventEmitter {
19967
20404
  return pty.spawn(file, args, opts);
19968
20405
  });
19969
20406
  this._getRemoteLaunch = getRemoteLaunch ?? (() => null);
19970
- this._hasRespawnedForAuth = false;
19971
- this._killProc = killProc || ((args, opts, cb) => execFile("taskkill", args, opts, cb));
19972
- this._signalProc = signalProc || ((pid, signal) => process.kill(pid, signal));
20407
+ this._launch = createSessionLaunch({
20408
+ id: this.id,
20409
+ adapter: this._adapter,
20410
+ platform,
20411
+ startCodexBridge,
20412
+ getRemoteLaunch: this._getRemoteLaunch,
20413
+ hooks: this._hooks,
20414
+ port: {
20415
+ name: () => this.name,
20416
+ promptSupervisionLine: () => this._canRunHelpCommand ? supervisionLine({ canSpawn: !this.ephemeral }) : null,
20417
+ effectiveCwd: () => this.effectiveCwd(),
20418
+ spawnEnv: () => this._spawnEnv,
20419
+ spawnCommand: () => this._spawnCommand,
20420
+ agentToken: () => this._agentToken,
20421
+ commitSigningToken: () => this._commitSigningToken,
20422
+ commitSigningProgram: () => this._commitSigningProgram,
20423
+ isDestroyed: () => this._destroyed,
20424
+ abandonSpawn: (cause) => this._abandonSpawn(cause),
20425
+ emit: (event, detail) => this.emit(event, detail),
20426
+ forceRestart: (options) => this.forceRestart(options)
20427
+ }
20428
+ });
20429
+ this._reaper = createSessionProcessReaper({
20430
+ platform,
20431
+ killProc: killProc || ((args, opts, cb) => execFile("taskkill", args, opts, cb)),
20432
+ signalProc: signalProc || ((pid, signal) => process.kill(pid, signal)),
20433
+ port: {
20434
+ isDestroyed: () => this._destroyed,
20435
+ emitError: (err) => this._emitError(err)
20436
+ }
20437
+ });
19973
20438
  this._platform = platform;
19974
20439
  this._startPending = null;
19975
20440
  this._resizeSeq = 0;
@@ -20125,7 +20590,7 @@ var Session = class extends EventEmitter {
20125
20590
  ingestHookSignal(raw) {
20126
20591
  if (this._destroyed) return;
20127
20592
  if (raw?.signal === "auth-failed") {
20128
- if (this._respawnAfterAuthFailure()) return;
20593
+ if (this._launch.respawnAfterAuthFailure()) return;
20129
20594
  this.ingestHookSignal({
20130
20595
  ...raw,
20131
20596
  signal: "awaiting-input"
@@ -20142,7 +20607,7 @@ var Session = class extends EventEmitter {
20142
20607
  });
20143
20608
  return;
20144
20609
  }
20145
- if (raw?.signal === "ready" && String(raw.event || "").toLowerCase() === "stop") this._hasRespawnedForAuth = false;
20610
+ if (raw?.signal === "ready" && String(raw.event || "").toLowerCase() === "stop") this._launch.noteTurnStopped();
20146
20611
  this._hookSeen = true;
20147
20612
  if (this._recorder && raw?.event) this._recorder.writeHook(raw.event, raw.payload);
20148
20613
  if (raw && (raw.signal === "subagent-start" || raw.signal === "subagent-stop")) {
@@ -20416,6 +20881,33 @@ var Session = class extends EventEmitter {
20416
20881
  get pid() {
20417
20882
  return this.ptyProcess ? this.ptyProcess.pid : null;
20418
20883
  }
20884
+ get _killPollTimer() {
20885
+ return this._reaper.killPollTimer;
20886
+ }
20887
+ get _killReapTimer() {
20888
+ return this._reaper.killReapTimer;
20889
+ }
20890
+ get _killReap() {
20891
+ return this._reaper.killReap;
20892
+ }
20893
+ set _killReap(reap) {
20894
+ this._reaper.killReap = reap;
20895
+ }
20896
+ _awaitPendingReaps() {
20897
+ return this._reaper.awaitPendingReaps();
20898
+ }
20899
+ get _conversationApproval() {
20900
+ return this._approvals.conversationApproval;
20901
+ }
20902
+ holdClaudePermission(payload, abandoned) {
20903
+ return this._approvals.hold(payload, abandoned);
20904
+ }
20905
+ answerConversationApproval(requestId, answers) {
20906
+ return this._approvals.answer(requestId, answers);
20907
+ }
20908
+ releaseQuestionHold(requestId) {
20909
+ return this._approvals.release(requestId);
20910
+ }
20419
20911
  get hookSeen() {
20420
20912
  return this._hookSeen;
20421
20913
  }
@@ -20425,26 +20917,9 @@ var Session = class extends EventEmitter {
20425
20917
  get agentToken() {
20426
20918
  return this._agentToken;
20427
20919
  }
20428
- _agentApiEnv() {
20429
- if (!this._agentToken) return {};
20430
- const port = this._hooks.listenerPort();
20431
- if (!port) return {};
20432
- const url = `http://127.0.0.1:${port}/agent/${encodeURIComponent(this.id)}?t=${encodeURIComponent(this._agentToken)}`;
20433
- return { [AGENT_URL_ENV]: url };
20434
- }
20435
20920
  get commitSigningToken() {
20436
20921
  return this._commitSigningToken;
20437
20922
  }
20438
- _commitSigningEnv() {
20439
- if (this._getRemoteLaunch() !== null) return {};
20440
- return commitSigningEnv({
20441
- port: this._hooks.listenerPort(),
20442
- sessionId: this.id,
20443
- token: this._commitSigningToken,
20444
- signingProgram: this._commitSigningProgram,
20445
- inheritedConfigParameters: this._spawnEnv?.GIT_CONFIG_PARAMETERS ?? process.env.GIT_CONFIG_PARAMETERS
20446
- });
20447
- }
20448
20923
  agentSpawnBudget() {
20449
20924
  return {
20450
20925
  liveChildren: this._agentLiveChildren,
@@ -20585,14 +21060,6 @@ var Session = class extends EventEmitter {
20585
21060
  effectiveCwd() {
20586
21061
  return this.worktreeLifecycle.effectiveCwd();
20587
21062
  }
20588
- _spawnCwdSpellings() {
20589
- const spawnCwd = this.effectiveCwd();
20590
- try {
20591
- return Array.from(/* @__PURE__ */ new Set([spawnCwd, fs.realpathSync.native(spawnCwd)]));
20592
- } catch {
20593
- return [spawnCwd];
20594
- }
20595
- }
20596
21063
  _provisionWorktree({ fresh = false } = {}) {
20597
21064
  return this.worktreeLifecycle.provision({ fresh });
20598
21065
  }
@@ -20817,10 +21284,10 @@ var Session = class extends EventEmitter {
20817
21284
  if (this.ptyProcess) {
20818
21285
  console.warn(`[session:${this.name}] start() called while PTY exists - killing previous PTY first`);
20819
21286
  const oldPid = this.ptyProcess.pid;
20820
- this._killReap = this._reapTreeOnce(oldPid);
21287
+ this._reaper.killReap = this._reaper.reapTreeOnce(oldPid);
20821
21288
  this.ptyProcess = null;
20822
21289
  }
20823
- const pendingReaps = this._awaitPendingReaps();
21290
+ const pendingReaps = this._reaper.awaitPendingReaps();
20824
21291
  if (pendingReaps) await pendingReaps;
20825
21292
  if (this._destroyed) return;
20826
21293
  if (this.state === STATES.DORMANT) this.transition("user_start");
@@ -20882,15 +21349,15 @@ var Session = class extends EventEmitter {
20882
21349
  this._titleSource.setContext({ cwdBasename: path.basename(this.effectiveCwd()) });
20883
21350
  const injectedEnv = {
20884
21351
  ...hookInjection.env,
20885
- ...this._agentApiEnv(),
21352
+ ...this._launch.agentApiEnv(),
20886
21353
  ...mcpLaunch.env,
20887
- ...this._commitSigningEnv()
21354
+ ...this._launch.commitSigningEnv()
20888
21355
  };
20889
21356
  const spawnExtraEnv = Object.keys(injectedEnv).length > 0 ? {
20890
21357
  ...this._spawnEnv || {},
20891
21358
  ...injectedEnv
20892
21359
  } : this._spawnEnv;
20893
- const env = this._buildSpawnEnv({
21360
+ const env = this._launch.buildEnv({
20894
21361
  prependPathDirs: this._prependPathDirs,
20895
21362
  extraEnv: spawnExtraEnv
20896
21363
  });
@@ -20901,7 +21368,7 @@ var Session = class extends EventEmitter {
20901
21368
  resumeSessionId: configuredResumeSessionId,
20902
21369
  transcriptPath: this._transcriptPath,
20903
21370
  projectsDirs: projectDirCandidates(env, [], os.homedir()),
20904
- cwds: this._spawnCwdSpellings(),
21371
+ cwds: this._launch.spawnCwdSpellings(),
20905
21372
  isTranscriptRemote: remoteLaunch !== null
20906
21373
  }, fs.existsSync);
20907
21374
  spawnResumeSessionId = resumeTarget.resumeSessionId;
@@ -20915,14 +21382,14 @@ var Session = class extends EventEmitter {
20915
21382
  extraArgs: this._extraClaudeArgs,
20916
21383
  initialPrompt: launchPrompt
20917
21384
  });
20918
- const bridgedLaunch = isRemoteCodex && remoteLaunch !== null ? await this._startRemoteCodexBridge(remoteLaunch, agentArgs, env) : null;
21385
+ const bridgedLaunch = isRemoteCodex && remoteLaunch !== null ? await this._launch.startRemoteCodexBridge(remoteLaunch, agentArgs, env) : null;
20919
21386
  if (isRemoteCodex && !bridgedLaunch) return;
20920
21387
  if (isStartSuperseded()) {
20921
21388
  this._hooks.cleanup();
20922
- await this._stopCodexBridge();
21389
+ await this._launch.stopCodexBridge();
20923
21390
  return;
20924
21391
  }
20925
- const spawnCommand = await this._spawnCommandFor({
21392
+ const spawnCommand = await this._launch.spawnCommandFor({
20926
21393
  remoteLaunch,
20927
21394
  isRemoteCodex,
20928
21395
  settingsArgs,
@@ -20930,12 +21397,12 @@ var Session = class extends EventEmitter {
20930
21397
  bridgedLaunch
20931
21398
  });
20932
21399
  if (!spawnCommand) {
20933
- await this._stopCodexBridge();
21400
+ await this._launch.stopCodexBridge();
20934
21401
  return;
20935
21402
  }
20936
21403
  if (isStartSuperseded()) {
20937
21404
  this._hooks.cleanup();
20938
- await this._stopCodexBridge();
21405
+ await this._launch.stopCodexBridge();
20939
21406
  return;
20940
21407
  }
20941
21408
  if (bridgedLaunch) env[CODEX_REMOTE_TOKEN_ENV] = bridgedLaunch.token;
@@ -21042,242 +21509,14 @@ var Session = class extends EventEmitter {
21042
21509
  submitDelayMs: PTY_PROMPT_SUBMIT_DELAY_MS
21043
21510
  });
21044
21511
  }
21045
- async _stopCodexBridge() {
21046
- const bridge = this._codexBridge;
21047
- if (!bridge) return;
21048
- this._codexBridge = null;
21049
- await bridge.stop().catch((error) => console.warn(`[session:${this.name}] codex app-server stop failed: ${errorMessage(error)}`));
21050
- }
21051
- _setConversationApproval(approval) {
21052
- this._conversationApproval = approval;
21053
- this._emitConversationChange();
21054
- }
21055
- _emitConversationChange() {
21056
- this.emit("conversation-change", { conversationApproval: this._conversationApproval });
21057
- }
21058
- holdClaudePermission(payload, abandoned) {
21059
- if (this.agentId !== "claude-code") return null;
21060
- const request = parseClaudePermissionRequest(payload);
21061
- if (!request) return null;
21062
- if (!this._holdsQuestionsForParent || request.toolName !== "AskUserQuestion") return null;
21063
- this._releaseClaudeHolds((hold) => hold.request.agentKey === request.agentKey);
21064
- const requestId = `claude-${this._nextClaudeApprovalNumber}`;
21065
- this._nextClaudeApprovalNumber += 1;
21066
- return new Promise((resolve) => {
21067
- const hold = {
21068
- request,
21069
- approval: claudeApprovalFor(request, requestId),
21070
- resolve
21071
- };
21072
- this._claudeApprovalHolds.push(hold);
21073
- abandoned.addEventListener("abort", () => this._releaseClaudeHolds((candidate) => candidate === hold), { once: true });
21074
- this._showFirstClaudeApproval();
21075
- });
21076
- }
21077
- _releaseClaudeHoldsAfterHookEvent(event, payload) {
21078
- if (this._claudeApprovalHolds.length === 0) return;
21079
- this._releaseClaudeHolds((hold) => isHoldReleasedByHookEvent(hold.request, event, payload));
21080
- }
21081
- _releaseClaudeHolds(isReleased) {
21082
- const released = this._claudeApprovalHolds.filter(isReleased);
21083
- if (released.length === 0) return;
21084
- this._claudeApprovalHolds = this._claudeApprovalHolds.filter((hold) => !released.includes(hold));
21085
- for (const hold of released) hold.resolve(null);
21086
- this._showFirstClaudeApproval();
21087
- }
21088
- _showFirstClaudeApproval() {
21089
- this._setConversationApproval(this._claudeApprovalHolds[0]?.approval ?? null);
21090
- }
21091
- answerConversationApproval(requestId, answers) {
21092
- const hold = this._claudeApprovalHolds.find((candidate) => candidate.approval.requestId === requestId);
21093
- if (!hold) return false;
21094
- const reply = claudeAnswerReply(hold.request, hold.approval, answers);
21095
- if (!reply) return false;
21096
- this._claudeApprovalHolds = this._claudeApprovalHolds.filter((candidate) => candidate !== hold);
21097
- hold.resolve(reply);
21098
- this._showFirstClaudeApproval();
21099
- return true;
21100
- }
21101
- releaseQuestionHold(requestId) {
21102
- const hold = this._claudeApprovalHolds.find((candidate) => candidate.approval.requestId === requestId);
21103
- if (!hold) return false;
21104
- this._releaseClaudeHolds((candidate) => candidate === hold);
21105
- return true;
21106
- }
21107
21512
  _abandonSpawn(cause) {
21108
21513
  this._isSaneYoloActive = false;
21109
21514
  this._hooks.cleanup();
21110
- this._stopCodexBridge();
21111
- this._releaseClaudeHolds(() => true);
21515
+ this._launch.stopCodexBridge();
21516
+ this._approvals.releaseAll();
21112
21517
  this.transition("spawn_fail", { error: errorMessage(cause) });
21113
21518
  this.emit("error", cause);
21114
21519
  }
21115
- async _spawnCommandFor({ remoteLaunch, isRemoteCodex, settingsArgs, agentArgs, bridgedLaunch }) {
21116
- if (remoteLaunch !== null && !isRemoteCodex) return this._remoteSpawnCommand(remoteLaunch, agentArgs);
21117
- const command = this._adapter.buildSpawnCommand({
21118
- platform: this._platform,
21119
- resolved: this._spawnCommand || commandFor(this._adapter),
21120
- settingsArgs: bridgedLaunch ? [] : settingsArgs,
21121
- agentArgs: bridgedLaunch?.tuiArgs ?? agentArgs
21122
- });
21123
- return {
21124
- file: command.file,
21125
- args: command.args,
21126
- env: {}
21127
- };
21128
- }
21129
- async _startRemoteCodexBridge(remote, agentArgs, env) {
21130
- await this._stopCodexBridge();
21131
- const prepared = await this._prepareRemoteCodexBridge(remote, agentArgs, env).catch((error) => ({
21132
- ok: false,
21133
- reason: errorMessage(error)
21134
- }));
21135
- if (this._destroyed) {
21136
- this._hooks.cleanup();
21137
- await this._stopCodexBridge();
21138
- return null;
21139
- }
21140
- if (!prepared.ok) {
21141
- this._abandonSpawn(/* @__PURE__ */ new Error(`Coder workspace ${remote.workspace}: ${prepared.reason}`));
21142
- return null;
21143
- }
21144
- return prepared.launch;
21145
- }
21146
- async _prepareRemoteCodexBridge(remote, agentArgs, env) {
21147
- const running = await remote.ensureRunning();
21148
- if (!running.ok) return running;
21149
- const version = await remote.codexVersion();
21150
- if (version === null) return {
21151
- ok: false,
21152
- reason: "the host codex version could not be read, so the workspace cannot install a matching codex"
21153
- };
21154
- const launch = splitCodexRemoteLaunch(agentArgs, this._canRunHelpCommand ? supervisionLine({ canSpawn: !this.ephemeral }) : null);
21155
- const bridge = await this._startCodexBridge({
21156
- command: {
21157
- file: "coder",
21158
- argsBeforeAppServer: []
21159
- },
21160
- configArgs: launch.appServerConfigArgs,
21161
- cwd: this.effectiveCwd(),
21162
- env: { ...env },
21163
- tokenParentDirectory: os.tmpdir(),
21164
- startupTimeoutMs: REMOTE_CODEX_STARTUP_TIMEOUT_MS,
21165
- remote: {
21166
- launch: (appServerArgs) => {
21167
- const script = remoteCodexAppServerScript({
21168
- version,
21169
- workingDirectory: remote.checkoutDirectory,
21170
- appServerArgs
21171
- });
21172
- const sshArgs = script === null ? null : coderSshExecArgs({
21173
- workspace: remote.workspace,
21174
- remoteCommand: script
21175
- });
21176
- if (sshArgs === null) throw new Error("the remote Codex app-server command could not be built");
21177
- return {
21178
- file: "coder",
21179
- args: sshArgs
21180
- };
21181
- },
21182
- forward: (remotePort) => startCoderPortForward({
21183
- workspace: remote.workspace,
21184
- remotePort
21185
- }),
21186
- login: remote.codexLoginParams,
21187
- refreshLogin: remote.codexRefreshResult
21188
- }
21189
- });
21190
- this._attachCodexBridge(bridge);
21191
- return {
21192
- ok: true,
21193
- launch: {
21194
- tuiArgs: remoteTuiArgs(bridge.url, launch.tuiArgs),
21195
- token: bridge.token
21196
- }
21197
- };
21198
- }
21199
- _attachCodexBridge(bridge) {
21200
- this._codexBridge = bridge;
21201
- bridge.on("records", (records) => this.emit("conversation-records", { records }));
21202
- bridge.on("error", (error) => console.warn(`[session:${this.name}] codex app-server bridge: ${errorMessage(error)}`));
21203
- bridge.on("exit", () => {
21204
- if (this._codexBridge !== bridge) return;
21205
- this._codexBridge = null;
21206
- });
21207
- }
21208
- async _remoteSpawnCommand(remote, agentArgs) {
21209
- const prepared = await this._prepareRemoteSpawn(remote, agentArgs).catch((error) => ({
21210
- ok: false,
21211
- reason: errorMessage(error)
21212
- }));
21213
- if (this._destroyed) {
21214
- this._hooks.cleanup();
21215
- return null;
21216
- }
21217
- if (!prepared.ok) {
21218
- this._abandonSpawn(/* @__PURE__ */ new Error(`Coder workspace ${remote.workspace}: ${prepared.reason}`));
21219
- return null;
21220
- }
21221
- return prepared.spawnCommand;
21222
- }
21223
- async _prepareRemoteSpawn(remote, agentArgs) {
21224
- const hookToken = this._hooks.token();
21225
- const ingressPort = this._hooks.listenerPort();
21226
- if (hookToken === null || ingressPort === null) return {
21227
- ok: false,
21228
- reason: "hooks are unavailable, so the remote session could not report its status"
21229
- };
21230
- const running = await remote.ensureRunning();
21231
- if (!running.ok) return running;
21232
- const login = await remote.claudeToken();
21233
- if (!login.ok) return login;
21234
- const settingsPath = path.posix.join(path.posix.dirname(remote.checkoutDirectory), ".glimmervoid-sessions", safePathSegment(this.id), "settings.json");
21235
- const settings = buildHookSettings({
21236
- port: remote.remotePort,
21237
- glimmervoidId: this.id,
21238
- token: hookToken,
21239
- remoteNodePath: remote.nodePath
21240
- });
21241
- await remote.uploadFile({
21242
- remotePath: settingsPath,
21243
- contents: JSON.stringify(settings),
21244
- mode: 384
21245
- });
21246
- const remoteCommand = remoteLaunchScript({
21247
- workingDirectory: remote.checkoutDirectory,
21248
- argv: [
21249
- "claude",
21250
- ...this._adapter.settingsArgs?.(settingsPath) ?? [],
21251
- ...agentArgs
21252
- ],
21253
- tokenAliases: CLAUDE_TOKEN_ALIASES
21254
- });
21255
- const sshArgs = remoteCommand === null ? null : coderSshArgs({
21256
- workspace: remote.workspace,
21257
- remotePort: remote.remotePort,
21258
- ingressPort,
21259
- remoteCommand
21260
- });
21261
- const sshEnv = encodeCoderSshEnv({ [CLAUDE_TOKEN_ALIAS_ENV]: login.token });
21262
- if (sshArgs === null || sshEnv === null) return {
21263
- ok: false,
21264
- reason: "the remote launch command could not be built"
21265
- };
21266
- return {
21267
- ok: true,
21268
- spawnCommand: {
21269
- file: "coder",
21270
- args: sshArgs,
21271
- env: { [CODER_SSH_ENV]: sshEnv }
21272
- }
21273
- };
21274
- }
21275
- _respawnAfterAuthFailure() {
21276
- if (this._getRemoteLaunch() === null || this._hasRespawnedForAuth) return false;
21277
- this._hasRespawnedForAuth = true;
21278
- console.warn(`[session:${this.name}] the remote Claude token was refused; respawning once with a fresh token`);
21279
- return this.forceRestart({ resumePrompt: AUTO_CONTINUE_PROMPT });
21280
- }
21281
21520
  _guardPtyInputSocket() {
21282
21521
  try {
21283
21522
  this.ptyProcess?._agent?.inSocket?.on("error", (err) => {
@@ -21317,9 +21556,6 @@ var Session = class extends EventEmitter {
21317
21556
  });
21318
21557
  }, { unref: true });
21319
21558
  }
21320
- _buildSpawnEnv({ extraEnv = this._spawnEnv, ...options } = {}) {
21321
- return this._adapter.buildEnv(process.env, extraEnv, options);
21322
- }
21323
21559
  _handlePtyData(data) {
21324
21560
  if (this._destroyed) return;
21325
21561
  if (this._recorder) this._recorder.writeData(data);
@@ -21340,8 +21576,8 @@ var Session = class extends EventEmitter {
21340
21576
  return TRANSITIONS[this.state]?.[event] === STATES.FAILED;
21341
21577
  }
21342
21578
  _handleSpawnedPtyExit(exitCode, signal) {
21343
- this._stopCodexBridge();
21344
- this._releaseClaudeHolds(() => true);
21579
+ this._launch.stopCodexBridge();
21580
+ this._approvals.releaseAll();
21345
21581
  return this._handlePtyExit(exitCode, signal);
21346
21582
  }
21347
21583
  async _handlePtyExit(exitCode, signal) {
@@ -21354,7 +21590,7 @@ var Session = class extends EventEmitter {
21354
21590
  this._hooks.cleanup();
21355
21591
  this._ptyAlive = false;
21356
21592
  this.ptyProcess = null;
21357
- if (pid) this._exitReap = this._reapTreeOnce(pid);
21593
+ if (pid) this._reaper.exitReap = this._reaper.reapTreeOnce(pid);
21358
21594
  const { event, detail } = decideExitTransition(this.state, exitCode, signal, this._receivedFirstOutput);
21359
21595
  const reason = detail.reason || null;
21360
21596
  const pendingRemoteExitReason = this._isExitHeadedForFailure(event) ? this._getRemoteLaunch()?.describeExit().catch(() => null) : void 0;
@@ -21434,111 +21670,13 @@ var Session = class extends EventEmitter {
21434
21670
  seq: this._resizeSeq
21435
21671
  });
21436
21672
  }
21437
- _taskkill(pid, opts = {}) {
21438
- return new Promise((resolve, reject) => {
21439
- this._killProc([
21440
- "/PID",
21441
- String(Number(pid)),
21442
- "/T",
21443
- "/F"
21444
- ], { ...opts }, (err) => {
21445
- if (err) return reject(err);
21446
- resolve();
21447
- });
21448
- });
21449
- }
21450
21673
  _emitError(err) {
21451
21674
  if (this.listenerCount("error") > 0) this.emit("error", err);
21452
21675
  }
21453
- _killProcessGroup(pid, signal = "SIGKILL") {
21454
- const target = signalablePid(pid);
21455
- if (target === null) return;
21456
- try {
21457
- this._signalProc(-target, signal);
21458
- } catch (err) {
21459
- const code = err && typeof err === "object" && "code" in err ? err.code : void 0;
21460
- if (err && code !== "ESRCH") this._emitError(err);
21461
- }
21462
- }
21463
- _isProcessAlive(pid) {
21464
- const target = signalablePid(pid);
21465
- if (target === null) return false;
21466
- const probeTarget = this._platform === "win32" ? target : -target;
21467
- try {
21468
- this._signalProc(probeTarget, 0);
21469
- return true;
21470
- } catch {
21471
- return false;
21472
- }
21473
- }
21474
- _reapTreeOnce(pid) {
21475
- if (this._platform === "win32") return this._taskkill(pid, { timeout: KILL_REAP_MAX_WAIT_MS }).catch(() => {});
21476
- if (this._resolveKillReap) return this._killReap;
21477
- return this._reapProcessGroup(pid);
21478
- }
21479
- _awaitPendingReaps() {
21480
- const pending = [this._killReap, this._exitReap].filter((reap) => reap !== null);
21481
- if (pending.length === 0) return null;
21482
- return awaitBounded(pending, { capMs: KILL_REAP_MAX_WAIT_MS }).then(() => {});
21483
- }
21484
- _reapProcessGroup(pid, { maxWaitMs = KILL_REAP_MAX_WAIT_MS } = {}) {
21485
- this._killProcessGroup(pid);
21486
- return this._awaitProcessGone(pid, maxWaitMs);
21487
- }
21488
- _awaitProcessGone(pid, maxWaitMs) {
21489
- if (this._resolveKillReap) this._resolveKillReap();
21490
- return new Promise((resolve) => {
21491
- const settle = () => {
21492
- this._clearTimer("_killReapTimer");
21493
- this._resolveKillReap = null;
21494
- resolve();
21495
- };
21496
- this._resolveKillReap = settle;
21497
- let waited = 0;
21498
- const poll = () => {
21499
- if (!this._isProcessAlive(pid)) {
21500
- settle();
21501
- return;
21502
- }
21503
- waited += KILL_POLL_INTERVAL_MS;
21504
- if (waited >= maxWaitMs) {
21505
- settle();
21506
- return;
21507
- }
21508
- this._armTimer("_killReapTimer", KILL_POLL_INTERVAL_MS, poll);
21509
- };
21510
- poll();
21511
- });
21512
- }
21513
21676
  kill() {
21514
21677
  if (!this.ptyProcess) return;
21515
21678
  this._ptyAlive = false;
21516
- const pid = this.ptyProcess.pid;
21517
- if (this._platform === "win32") {
21518
- const killReap = this._taskkill(pid);
21519
- this._killReap = killReap;
21520
- killReap.catch((err) => this._emitError(err));
21521
- }
21522
- if (this._platform !== "win32") this._killReap = this._reapProcessGroup(pid);
21523
- this._forceKillAfterTimeout(pid);
21524
- }
21525
- _forceKillAfterTimeout(pid) {
21526
- let elapsed = 0;
21527
- const poll = () => {
21528
- if (this._destroyed) return;
21529
- if (!this._isProcessAlive(pid)) return;
21530
- elapsed += KILL_POLL_INTERVAL_MS;
21531
- if (elapsed >= KILL_MAX_WAIT_MS) {
21532
- if (this._platform === "win32") {
21533
- this._taskkill(pid).catch((err) => this._emitError(err));
21534
- return;
21535
- }
21536
- this._killProcessGroup(pid);
21537
- return;
21538
- }
21539
- this._armTimer("_killPollTimer", KILL_POLL_INTERVAL_MS, poll);
21540
- };
21541
- this._armTimer("_killPollTimer", KILL_POLL_INTERVAL_MS, poll);
21679
+ this._reaper.kill(this.ptyProcess.pid);
21542
21680
  }
21543
21681
  dismiss() {
21544
21682
  const hadUnseenOutcome = this.unseenOutcome !== null;
@@ -21646,10 +21784,10 @@ var Session = class extends EventEmitter {
21646
21784
  this._pendingAttentionNotes = [];
21647
21785
  this._clearPendingPaste();
21648
21786
  this._hooks.cleanup();
21649
- this._stopCodexBridge();
21650
- this._releaseClaudeHolds(() => true);
21787
+ this._launch.stopCodexBridge();
21788
+ this._approvals.releaseAll();
21651
21789
  this.kill();
21652
- this._clearTimer("_killPollTimer");
21790
+ this._reaper.clearKillPoll();
21653
21791
  this._clearTimer("_titleQuietFallbackTimer");
21654
21792
  this.backgroundTracking.clearGateHeldReady();
21655
21793
  this.backgroundTracking.clearWakeups();