@code-yeongyu/senpi 2026.9.28-2 → 2026.9.28-3

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 (72) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/bundle/chunks/{app-server-command-H6LFICZ2.js → app-server-command-JTHJ2U7J.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-LSW7QSLV.js → chunk-6XBT6OGS.js} +36 -34
  4. package/dist/bundle/chunks/chunk-OP3QMR6B.js +8 -0
  5. package/dist/bundle/chunks/{cli-main-GYRTYPMG.js → cli-main-Z2Y55XHU.js} +1 -1
  6. package/dist/bundle/chunks/{interactive-mode-LX665HTP.js → interactive-mode-A3EYB6DW.js} +1 -1
  7. package/dist/bundle/chunks/{multi-session-host-MFTUM6XQ.js → multi-session-host-HM2UJ4ER.js} +2 -2
  8. package/dist/bundle/chunks/{package-manager-cli-6IAE5WG3.js → package-manager-cli-T7Q4AZKX.js} +1 -1
  9. package/dist/bundle/chunks/{rpc-mode-XN3HNZMH.js → rpc-mode-ROB6IG6J.js} +1 -1
  10. package/dist/bundle/chunks/session-worker.js +140 -138
  11. package/dist/bundle/cli.js +1 -1
  12. package/dist/bundle/index.js +1 -1
  13. package/dist/bundle/rpc-entry.js +1 -1
  14. package/dist/core/webview/bun-chrome.d.ts +15 -0
  15. package/dist/core/webview/bun-chrome.d.ts.map +1 -0
  16. package/dist/core/webview/bun-chrome.js +91 -0
  17. package/dist/core/webview/bun-chrome.js.map +1 -0
  18. package/dist/core/webview/native-webview.d.ts +16 -0
  19. package/dist/core/webview/native-webview.d.ts.map +1 -0
  20. package/dist/core/webview/native-webview.js +15 -0
  21. package/dist/core/webview/native-webview.js.map +1 -0
  22. package/dist/core/webview/webview-broker.d.ts +27 -0
  23. package/dist/core/webview/webview-broker.d.ts.map +1 -0
  24. package/dist/core/webview/webview-broker.js +120 -0
  25. package/dist/core/webview/webview-broker.js.map +1 -0
  26. package/dist/core/webview/webview-client.d.ts +19 -0
  27. package/dist/core/webview/webview-client.d.ts.map +1 -0
  28. package/dist/core/webview/webview-client.js +135 -0
  29. package/dist/core/webview/webview-client.js.map +1 -0
  30. package/dist/core/webview/webview-service.d.ts +26 -0
  31. package/dist/core/webview/webview-service.d.ts.map +1 -0
  32. package/dist/core/webview/webview-service.js +102 -0
  33. package/dist/core/webview/webview-service.js.map +1 -0
  34. package/dist/core/webview/webview-wire.d.ts +76 -0
  35. package/dist/core/webview/webview-wire.d.ts.map +1 -0
  36. package/dist/core/webview/webview-wire.js +57 -0
  37. package/dist/core/webview/webview-wire.js.map +1 -0
  38. package/dist/index.d.ts +1 -0
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +2 -0
  41. package/dist/index.js.map +1 -1
  42. package/dist/modes/rpc/session-worker-client.d.ts +2 -0
  43. package/dist/modes/rpc/session-worker-client.d.ts.map +1 -1
  44. package/dist/modes/rpc/session-worker-client.js +7 -1
  45. package/dist/modes/rpc/session-worker-client.js.map +1 -1
  46. package/dist/modes/rpc/session-worker.js +3 -1
  47. package/dist/modes/rpc/session-worker.js.map +1 -1
  48. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +14 -0
  49. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  50. package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/protocol.ts +14 -0
  51. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/inline-worker.ts +2 -1
  52. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/local-module-loader.ts +2 -0
  53. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/webview-host.ts +59 -0
  54. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-core.js +17 -0
  55. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-host.ts +2 -1
  56. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-runtime.js +2 -1
  57. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-slot.ts +14 -5
  58. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-webview-client.js +79 -0
  59. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-webview.js +204 -0
  60. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-queue.ts +2 -0
  61. package/node_modules/@code-yeongyu/senpi-codemode/src/skill/bun-1-4/references/runtime-apis.md +1 -0
  62. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  63. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  64. package/node_modules/@earendil-works/pi-ai/dist/providers/data/azure-openai-responses.json +1 -1
  65. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  66. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  67. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  68. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  69. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  70. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  71. package/package.json +7 -7
  72. package/dist/bundle/chunks/chunk-KOPTADA3.js +0 -8
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
- import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-LSW7QSLV.js";import"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import"./chunk-KOPTADA3.js";import"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import{configureHttpDispatcher}from"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import"./chunk-FHJYIU3U.js";import"./chunk-HH3KJDWA.js";import"./chunk-GJUCSTAG.js";import"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
3
+ import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-6XBT6OGS.js";import"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import"./chunk-OP3QMR6B.js";import"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import{configureHttpDispatcher}from"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import"./chunk-FHJYIU3U.js";import"./chunk-HH3KJDWA.js";import"./chunk-GJUCSTAG.js";import"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-LSW7QSLV.js";import"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import{isApiKeyLoginProvider}from"./chunk-KOPTADA3.js";import"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import"./chunk-FHJYIU3U.js";import"./chunk-HH3KJDWA.js";import"./chunk-GJUCSTAG.js";import"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
2
+ import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-6XBT6OGS.js";import"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import{isApiKeyLoginProvider}from"./chunk-OP3QMR6B.js";import"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import"./chunk-FHJYIU3U.js";import"./chunk-HH3KJDWA.js";import"./chunk-GJUCSTAG.js";import"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,isSessionBusySnapshot,runWithProviderScope}from"./chunk-LSW7QSLV.js";import"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import{SessionManager,assertValidSessionId}from"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,recordLoopBlockedMs,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-KOPTADA3.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import{GENERATION_HANDOFF_CAPABILITY,runAsHostGenerationProcess}from"./chunk-FHJYIU3U.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-HH3KJDWA.js";import{ClientOccupancy,PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-GJUCSTAG.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostGeneration,hostInstanceId,protocolIdentity}from"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import{killTrackedDetachedChildren}from"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{access,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}from"node:path";import{readdirSync,readFileSync}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadChildReaperSyscalls(platform=process.platform){let supported=supportedPlatform(platform);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat=linuxStat(pid),tail=stat?.slice(stat.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat=linuxStat(pid),open=stat?.indexOf("(")??-1,close=stat?.lastIndexOf(")")??-1;return stat===void 0||open===-1||close<=open?"":stat.slice(open+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS=1e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now();continue}now()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count])=>`${name} x${count}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log}),timer=setInterval(()=>reaper.tick(),config.tickMs);return timer.unref(),()=>clearInterval(timer)}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??4096}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),3e4),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let rssMb=Math.round(this.readRssBytes()/1048576);if(rssMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(rssMb)),this.emit({type:"host_memory_pressure",rssMb,sessions});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<3e5||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: rssMb=${rssMb} sessions=${sessions} (idle parking halved)
2
+ import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,isSessionBusySnapshot,runWithProviderScope}from"./chunk-6XBT6OGS.js";import"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import{SessionManager,assertValidSessionId}from"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,recordLoopBlockedMs,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-OP3QMR6B.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import{GENERATION_HANDOFF_CAPABILITY,runAsHostGenerationProcess}from"./chunk-FHJYIU3U.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-HH3KJDWA.js";import{ClientOccupancy,PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-GJUCSTAG.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostGeneration,hostInstanceId,protocolIdentity}from"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import{killTrackedDetachedChildren}from"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{access,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}from"node:path";import{readdirSync,readFileSync}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadChildReaperSyscalls(platform=process.platform){let supported=supportedPlatform(platform);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat=linuxStat(pid),tail=stat?.slice(stat.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat=linuxStat(pid),open=stat?.indexOf("(")??-1,close=stat?.lastIndexOf(")")??-1;return stat===void 0||open===-1||close<=open?"":stat.slice(open+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS=1e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now();continue}now()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count])=>`${name} x${count}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log}),timer=setInterval(()=>reaper.tick(),config.tickMs);return timer.unref(),()=>clearInterval(timer)}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??4096}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),3e4),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let rssMb=Math.round(this.readRssBytes()/1048576);if(rssMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(rssMb)),this.emit({type:"host_memory_pressure",rssMb,sessions});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<3e5||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: rssMb=${rssMb} sessions=${sessions} (idle parking halved)
3
3
  `))}};import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4,BYTES_PER_MB=1024*1024;function describeWindow(processCpuMs,heapDeltaMb){return`cpu=${processCpuMs}ms heap=${heapDeltaMb>=0?"+":""}${heapDeltaMb}MB`}function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0,this.cpuMicrosAtTick=0,this.heapBytesAtTick=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.cpuUsage=options.cpuUsage??(()=>process.cpuUsage()),this.heapUsed=options.heapUsed??(()=>process.memoryUsage().heapUsed),this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){if(this.timer!==void 0)return;this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage();this.cpuMicrosAtTick=cpu.user+cpu.system,this.heapBytesAtTick=this.heapUsed(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.()}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage(),cpuMicros=cpu.user+cpu.system,heapBytes=this.heapUsed(),previousCpuMicros=this.cpuMicrosAtTick,previousHeapBytes=this.heapBytesAtTick;this.cpuMicrosAtTick=cpuMicros,this.heapBytesAtTick=heapBytes;let driftMs=Math.round(now-expectedAt);if(recordLoopBlockedMs(driftMs),driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark),processCpuMs=Math.round((cpuMicros-previousCpuMicros)/1e3),heapDeltaMb=Math.round((heapBytes-previousHeapBytes)/BYTES_PER_MB);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool,processCpuMs,heapDeltaMb}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)}; ${describeWindow(processCpuMs,heapDeltaMb)})
4
4
  `))}};function isHandoffBusy(snapshot){return isSessionBusySnapshot({...snapshot,hasActiveWakeSource:!1})}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
5
5
  `)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),handler=await runWithProviderScope(entry.scope,async()=>{let taggedSink={writeRaw:bindToProviderScope(enqueueRecords),waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),...options})});return await handler.ready,{handle:command=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),rerenderComponents:()=>runWithProviderScope(entry.scope,()=>handler.rerenderComponents()),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}import{existsSync}from"node:fs";import{isAbsolute}from"node:path";function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
@@ -9,7 +9,7 @@ import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,b
9
9
  `)}))});continue}await this.releaseOwnedSession(sessionId)}})),opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId)}async releaseOwnedSession(sessionId){let live=this.registry.peek(sessionId),parks=live?.state==="open"&&live.retainOnDisconnect===!0&&live.attachments===1,claim=this.tryClaimClose(sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){parks&&live.runtime&&(live.lifecycleMutex=live.lifecycleMutex.then(()=>live.runtime?.emitAttachmentEvent("session_parked")),await live.lifecycleMutex),await this.finalizations.get(sessionId)?.promise;return}let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),await this.finalizeClose(sessionId,binding)}claimClose(sessionId,options){let finalizer=!0,onRole=isFinalizer=>{finalizer=isFinalizer,isFinalizer&&!this.finalizations.has(sessionId)&&this.finalizations.set(sessionId,this.createFinalization())},entry=this.registry.beginClose(sessionId,onRole,{detach:options.detach});for(;options.drainAttachments&&entry.state==="open";)entry=this.registry.beginClose(sessionId,onRole);return{finalizer:finalizer&&entry.state==="closing"}}tryClaimClose(sessionId,options){try{return this.claimClose(sessionId,options)}catch{return}}async close(command){let response={id:command.id,type:"response",command:"close_session",success:!0,data:{}},owner=this.writer.currentConnection();if(owner!==void 0&&this.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return error(command.id,"close_session",RPC_ERROR_UNKNOWN_SESSION);let reply=this.writer.reserveCloseResponse(command.sessionId,response);if(!reply)return;let claim;try{claim=this.claimClose(command.sessionId,{drainAttachments:!1})}catch(cause){return reply.release(),error(command.id,"close_session",this.code(cause))}try{owner!==void 0&&this.releaseOwnerAttachment(owner,command.sessionId),claim.finalizer?await this.finalizeClose(command.sessionId,this.bindings.get(command.sessionId),()=>reply.complete(!0,"client_close")):(await this.finalizations.get(command.sessionId)?.promise,reply.complete(!1));return}finally{reply.release()}}releaseOwnerAttachment(owner,sessionId){this.widths.get(sessionId)?.delete(owner),this.writer.detachConnectionFromSession(owner,sessionId);for(let binding of this.bindings.values())try{binding.rerenderComponents?.()}catch(cause){process.stderr.write(`senpi rpc rerender after close of session ${sessionId} failed: ${String(cause)}
10
10
  `)}let owned=this.sessionsByConnection.get(owner),count=owned?.get(sessionId);!owned||count===void 0||(count===1?owned.delete(sessionId):owned.set(sessionId,count-1),owned.size===0&&this.sessionsByConnection.delete(owner))}async finalizeClose(sessionId,binding,terminal){let finalization=this.finalizations.get(sessionId)??this.createFinalization();this.finalizations.set(sessionId,finalization);try{try{await binding?.dispose()}catch(cause){process.stderr.write(`senpi rpc binding dispose for session ${sessionId} failed: ${String(cause)}
11
11
  `)}this.bindings.delete(sessionId);try{await this.registry.closeMarked(sessionId)}catch(cause){process.stderr.write(`senpi rpc close for session ${sessionId} failed: ${String(cause)}
12
- `)}await this.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),this.finalizations.delete(sessionId)}}createFinalization(){let resolveFinalization;return{promise:new Promise(resolve=>{resolveFinalization=resolve}),resolve:()=>resolveFinalization?.()}}detail(cause){return cause instanceof RpcSessionRegistryError?cause.detail:void 0}code(cause){return cause instanceof RpcSessionRegistryError?cause.code===RPC_ERROR_OPEN_FAILED?cause.message:cause.code:cause instanceof Error&&[RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_SESSION_CLOSING].includes(cause.message)?cause.message:cause instanceof Error&&cause.message?`${RPC_ERROR_OPEN_FAILED}: ${cause.message}`:RPC_ERROR_UNKNOWN_SESSION}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve()};socket.once("drain",done),socket.once("close",done)}))}}}import{isAbsolute as isAbsolute2}from"node:path";var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1048576,requestBytes:16777216,outputBytes:16777216,reservations:64,openMs:3e4,controlMs:5e3},WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3};var RESERVATION_DENIAL_CODES={conflict:"session_path_in_use",limit:"session_reservation_limit"},SessionPathReservations=class{constructor(){this.owners=new Map}owner(path){return this.owners.get(path)}count(handle){let count=0;for(let owner of this.owners.values())owner===handle&&count++;return count}reserve(handle,path,live){let owner=this.owners.get(path);return owner?owner===handle?"granted":"conflict":this.count(handle)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle,live),this.count(handle)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle),"granted")}reconcile(handle,live){for(let[path,owner]of this.owners)owner!==handle||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle){for(let[path,owner]of this.owners)owner===handle&&this.owners.delete(path)}};import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var SessionWorkerRequests=class{constructor(send,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.send=send,this.timeout=timeout}remainingOpenMs(){let now=Date.now();return this.openingDeadline===void 0&&(this.openingDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.openingDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="command"&&"type"in message.command&&typeof message.command.type=="string"&&["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(message.command.type),bytes=Buffer.byteLength(JSON.stringify(message)),count=0,pendingBytes=0;for(let pending of this.pending.values())pending.control===control&&(count++,pendingBytes+=pending.bytes);let maxCount=control?SESSION_WORKER_LIMITS.controlRequests:SESSION_WORKER_LIMITS.requests,maxBytes=control?SESSION_WORKER_LIMITS.controlBytes:SESSION_WORKER_LIMITS.requestBytes;if(count>=maxCount||pendingBytes+bytes>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve,reject,bytes,control,timer});try{this.send({...message,request})}catch(cause){this.pending.delete(request),clearTimeout(timer),reject(cause instanceof Error?cause:new Error(String(cause)))}})}receive(message){let pending=this.pending.get(message.request);pending&&(clearTimeout(pending.timer),this.pending.delete(message.request),message.type==="result"&&message.error?pending.reject(new Error(message.error)):pending.resolve(message))}close(error2){this.closed=!0;for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(error2);this.pending.clear()}};function acknowledgeGrant(signal,grant){let state=new Int32Array(signal);Atomics.store(state,0,WORKER_CREDIT_CODES[grant]),Atomics.notify(state,0)}function acknowledge(signal,granted){acknowledgeGrant(signal,granted?"granted":"conflict")}function respondDisplay(signal,display){let values=new Float64Array(signal);values[1]=display.width,values[2]=display.revision,Atomics.store(new Int32Array(signal),1,display.rendered?1:0),acknowledge(signal,!0)}var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts",SessionWorkerClient=class{constructor(callbacks){this.worker=new Worker(isBunBinary?fileURLToPath(new URL(compiledWorkerEntry,import.meta.url)).replaceAll("\\","/"):new URL(import.meta.url.endsWith(".ts")?"./session-worker.ts":"./session-worker.js",import.meta.url)),this.bindingReady=!1,this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.displayRevision=0,this.options={},this.listeners=new Set,this.controls=new Set,this.callbacks=callbacks,this.exited=new Promise(resolve=>{this.worker.once("exit",()=>{!this.stopped&&!this.closeTimer&&this.fail("session_worker_exited"),this.stopped=!0,this.closeTimer&&clearTimeout(this.closeTimer),this.requests.close(new Error("session_worker_exited")),this.listeners.clear(),callbacks.exit(),this.publishTerminalFailure(),resolve()})}),this.worker.on("message",message=>this.receive(message)),this.worker.on("error",error2=>this.fail(error2 instanceof Error?error2.message:String(error2)))}async prepare(configuration,profile){let result=await this.request({type:"prepare",configuration,profile});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async commit(){let result=await this.request({type:"commit"});if(result.type!=="ready")throw new Error("Invalid worker commit response");return this.snapshot=result.snapshot,result.snapshot}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.requestClose=requestClose,this.options=options,await this.request({type:"bind",sessionId,display:this.display(),connection:writer.currentConnection()}),{handle:async command=>{await this.request({type:"command",command,connection:writer.currentConnection(),display:this.display()})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),rerenderComponents:()=>this.post({type:"display",display:this.display()}),dispose:async()=>{this.post({type:"cancel_ui"})}}}get busy(){return this.requests.activeCount>0||this.snapshot?.busy===!0}get handoffBusy(){return this.requests.activeCount>0||(this.snapshot?.handoffBusy??this.snapshot?.busy)===!0}subscribeSettled(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}close(graceMs){return this.stopped||this.closeTimer?this.exited:(this.post({type:"close"}),this.closeTimer=setTimeout(()=>this.quarantine(),graceMs),this.exited)}quarantine(){this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}display(){return{revision:++this.displayRevision,width:this.options.sharedWidth?.getWidth()??80,rendered:this.options.sharedWidth?.hasRenderedComponents?.(this.sessionId??"")??!1,capabilities:this.options.capabilities??[]}}request(message){return this.requests.request(message)}post(message){if(!this.stopped){if(message.type==="display"||message.type==="cancel_ui"){if(this.controls.has(message.type)){message.type==="display"&&(this.latestDisplay=message);return}this.controls.add(message.type)}this.worker.postMessage(message)}}receive(message){if(this.stopped){"signal"in message&&acknowledge(message.signal,!1);return}switch(message.type){case"prepared":case"ready":case"result":{this.requests.receive(message);return}case"reserve":acknowledgeGrant(message.signal,this.callbacks.reserve(message.path));return;case"snapshot":if(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths),acknowledge(message.signal,!0),message.settled)for(let listener of[...this.listeners])listener();return;case"control_done":{if(this.controls.delete(message.control),message.control==="display"&&this.latestDisplay){let latest=this.latestDisplay;this.latestDisplay=void 0,this.post(latest)}return}case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}message.snapshot?(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths)):this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let enqueue=()=>writer.enqueue(sessionId,message.record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")));(message.connection===void 0?enqueue():writer.withConnection(message.connection,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"width":this.options.sharedWidth?.setWidth(message.connection,message.width),this.options.sharedWidth?.onChange?.(),respondDisplay(message.signal,this.display());return;case"capabilities":this.options.sharedWidth?.setCapabilities?.(message.connection,message.capabilities),respondDisplay(message.signal,this.display());return;case"request_close":this.requestClose?.();return;case"failure":this.fail(message.error);return}}fail(error2){this.stopped||(this.callbacks.failure(error2),this.terminalFailure=error2,this.writer&&this.sessionId&&this.writer.enqueue(this.sessionId,{type:"session_error",error:error2}),this.quarantine())}publishTerminalFailure(){let error2=this.terminalFailure,writer=this.writer,sessionId=this.sessionId;error2===void 0||!writer||!sessionId||(this.terminalFailure=void 0,writer.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:error2},"error"))}};var WorkerSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new SessionPathReservations,this.serial=0,this.options=options,this.closeGraceMs=options.closeGraceMs,this.now=options.now,this.createWorker=options.createWorker??(callbacks=>new SessionWorkerClient(callbacks))}get size(){return this.entries.size}async openSession(profile,options){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");let requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){try{assertValidSessionId(requestedDurableId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}let requestedKey=profile.sessionPath?this.knownReservationKey(profile.sessionPath):void 0;for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(requestedKey!==void 0&&entry2.reservationKey===requestedKey))throw new RpcSessionRegistryError("session_id_in_use")}if(profile.sessionPath){let key=this.knownReservationKey(profile.sessionPath),owner=key?this.reservations.owner(key):void 0;if(key&&owner)return this.attach(owner,key,options)}if(this.size>=SESSION_WORKER_LIMITS.workers)throw new Error("too_many_sessions");let handle=`rpc-${++this.serial}`,storedProfile=frozenProfile(profile),entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),cwd:profile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve(),...requestedDurableId!==void 0?{durableSessionId:requestedDurableId}:{}},workerFailure,worker=this.createWorker({reserve:path=>this.reserve(handle,path),reconcile:livePaths=>this.reconcile(handle,livePaths),exit:()=>{this.entries.get(handle)===entry&&(entry.state="closed",this.entries.delete(handle),this.reservations.releaseAll(handle),entry.closeResolve?.())},failure:error2=>{workerFailure=error2,entry.state="quarantined",process.stderr.write(`senpi rpc session ${handle} quarantined: ${error2}
12
+ `)}await this.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),this.finalizations.delete(sessionId)}}createFinalization(){let resolveFinalization;return{promise:new Promise(resolve=>{resolveFinalization=resolve}),resolve:()=>resolveFinalization?.()}}detail(cause){return cause instanceof RpcSessionRegistryError?cause.detail:void 0}code(cause){return cause instanceof RpcSessionRegistryError?cause.code===RPC_ERROR_OPEN_FAILED?cause.message:cause.code:cause instanceof Error&&[RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_SESSION_CLOSING].includes(cause.message)?cause.message:cause instanceof Error&&cause.message?`${RPC_ERROR_OPEN_FAILED}: ${cause.message}`:RPC_ERROR_UNKNOWN_SESSION}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve()};socket.once("drain",done),socket.once("close",done)}))}}}import{isAbsolute as isAbsolute2}from"node:path";var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1048576,requestBytes:16777216,outputBytes:16777216,reservations:64,openMs:3e4,controlMs:5e3},WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3};var RESERVATION_DENIAL_CODES={conflict:"session_path_in_use",limit:"session_reservation_limit"},SessionPathReservations=class{constructor(){this.owners=new Map}owner(path){return this.owners.get(path)}count(handle){let count=0;for(let owner of this.owners.values())owner===handle&&count++;return count}reserve(handle,path,live){let owner=this.owners.get(path);return owner?owner===handle?"granted":"conflict":this.count(handle)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle,live),this.count(handle)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle),"granted")}reconcile(handle,live){for(let[path,owner]of this.owners)owner!==handle||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle){for(let[path,owner]of this.owners)owner===handle&&this.owners.delete(path)}};import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var SessionWorkerRequests=class{constructor(send,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.send=send,this.timeout=timeout}remainingOpenMs(){let now=Date.now();return this.openingDeadline===void 0&&(this.openingDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.openingDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="command"&&"type"in message.command&&typeof message.command.type=="string"&&["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(message.command.type),bytes=Buffer.byteLength(JSON.stringify(message)),count=0,pendingBytes=0;for(let pending of this.pending.values())pending.control===control&&(count++,pendingBytes+=pending.bytes);let maxCount=control?SESSION_WORKER_LIMITS.controlRequests:SESSION_WORKER_LIMITS.requests,maxBytes=control?SESSION_WORKER_LIMITS.controlBytes:SESSION_WORKER_LIMITS.requestBytes;if(count>=maxCount||pendingBytes+bytes>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve,reject,bytes,control,timer});try{this.send({...message,request})}catch(cause){this.pending.delete(request),clearTimeout(timer),reject(cause instanceof Error?cause:new Error(String(cause)))}})}receive(message){let pending=this.pending.get(message.request);pending&&(clearTimeout(pending.timer),this.pending.delete(message.request),message.type==="result"&&message.error?pending.reject(new Error(message.error)):pending.resolve(message))}close(error2){this.closed=!0;for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(error2);this.pending.clear()}};function acknowledgeGrant(signal,grant){let state=new Int32Array(signal);Atomics.store(state,0,WORKER_CREDIT_CODES[grant]),Atomics.notify(state,0)}function acknowledge(signal,granted){acknowledgeGrant(signal,granted?"granted":"conflict")}function respondDisplay(signal,display){let values=new Float64Array(signal);values[1]=display.width,values[2]=display.revision,Atomics.store(new Int32Array(signal),1,display.rendered?1:0),acknowledge(signal,!0)}var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts",SessionWorkerClient=class{constructor(callbacks){this.webviewBroker=createWebViewBroker(),this.worker=new Worker(isBunBinary?fileURLToPath(new URL(compiledWorkerEntry,import.meta.url)).replaceAll("\\","/"):new URL(import.meta.url.endsWith(".ts")?"./session-worker.ts":"./session-worker.js",import.meta.url),this.webviewBroker?{workerData:{webviewBroker:this.webviewBroker.port},transferList:[this.webviewBroker.port]}:{}),this.bindingReady=!1,this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.displayRevision=0,this.options={},this.listeners=new Set,this.controls=new Set,this.callbacks=callbacks,this.exited=new Promise(resolve=>{this.worker.once("exit",()=>{!this.stopped&&!this.closeTimer&&this.fail("session_worker_exited"),this.stopped=!0,this.closeTimer&&clearTimeout(this.closeTimer),this.requests.close(new Error("session_worker_exited")),this.webviewBroker?.dispose(),this.listeners.clear(),callbacks.exit(),this.publishTerminalFailure(),resolve()})}),this.worker.on("message",message=>this.receive(message)),this.worker.on("error",error2=>this.fail(error2 instanceof Error?error2.message:String(error2)))}async prepare(configuration,profile){let result=await this.request({type:"prepare",configuration,profile});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async commit(){let result=await this.request({type:"commit"});if(result.type!=="ready")throw new Error("Invalid worker commit response");return this.snapshot=result.snapshot,result.snapshot}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.requestClose=requestClose,this.options=options,await this.request({type:"bind",sessionId,display:this.display(),connection:writer.currentConnection()}),{handle:async command=>{await this.request({type:"command",command,connection:writer.currentConnection(),display:this.display()})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),rerenderComponents:()=>this.post({type:"display",display:this.display()}),dispose:async()=>{this.post({type:"cancel_ui"})}}}get busy(){return this.requests.activeCount>0||this.snapshot?.busy===!0}get handoffBusy(){return this.requests.activeCount>0||(this.snapshot?.handoffBusy??this.snapshot?.busy)===!0}subscribeSettled(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}close(graceMs){return this.stopped||this.closeTimer?this.exited:(this.post({type:"close"}),this.closeTimer=setTimeout(()=>this.quarantine(),graceMs),this.exited)}quarantine(){this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}display(){return{revision:++this.displayRevision,width:this.options.sharedWidth?.getWidth()??80,rendered:this.options.sharedWidth?.hasRenderedComponents?.(this.sessionId??"")??!1,capabilities:this.options.capabilities??[]}}request(message){return this.requests.request(message)}post(message){if(!this.stopped){if(message.type==="display"||message.type==="cancel_ui"){if(this.controls.has(message.type)){message.type==="display"&&(this.latestDisplay=message);return}this.controls.add(message.type)}this.worker.postMessage(message)}}receive(message){if(this.stopped){"signal"in message&&acknowledge(message.signal,!1);return}switch(message.type){case"prepared":case"ready":case"result":{this.requests.receive(message);return}case"reserve":acknowledgeGrant(message.signal,this.callbacks.reserve(message.path));return;case"snapshot":if(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths),acknowledge(message.signal,!0),message.settled)for(let listener of[...this.listeners])listener();return;case"control_done":{if(this.controls.delete(message.control),message.control==="display"&&this.latestDisplay){let latest=this.latestDisplay;this.latestDisplay=void 0,this.post(latest)}return}case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}message.snapshot?(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths)):this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let enqueue=()=>writer.enqueue(sessionId,message.record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")));(message.connection===void 0?enqueue():writer.withConnection(message.connection,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"width":this.options.sharedWidth?.setWidth(message.connection,message.width),this.options.sharedWidth?.onChange?.(),respondDisplay(message.signal,this.display());return;case"capabilities":this.options.sharedWidth?.setCapabilities?.(message.connection,message.capabilities),respondDisplay(message.signal,this.display());return;case"request_close":this.requestClose?.();return;case"failure":this.fail(message.error);return}}fail(error2){this.stopped||(this.callbacks.failure(error2),this.terminalFailure=error2,this.writer&&this.sessionId&&this.writer.enqueue(this.sessionId,{type:"session_error",error:error2}),this.quarantine())}publishTerminalFailure(){let error2=this.terminalFailure,writer=this.writer,sessionId=this.sessionId;error2===void 0||!writer||!sessionId||(this.terminalFailure=void 0,writer.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:error2},"error"))}};var WorkerSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new SessionPathReservations,this.serial=0,this.options=options,this.closeGraceMs=options.closeGraceMs,this.now=options.now,this.createWorker=options.createWorker??(callbacks=>new SessionWorkerClient(callbacks))}get size(){return this.entries.size}async openSession(profile,options){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");let requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){try{assertValidSessionId(requestedDurableId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}let requestedKey=profile.sessionPath?this.knownReservationKey(profile.sessionPath):void 0;for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(requestedKey!==void 0&&entry2.reservationKey===requestedKey))throw new RpcSessionRegistryError("session_id_in_use")}if(profile.sessionPath){let key=this.knownReservationKey(profile.sessionPath),owner=key?this.reservations.owner(key):void 0;if(key&&owner)return this.attach(owner,key,options)}if(this.size>=SESSION_WORKER_LIMITS.workers)throw new Error("too_many_sessions");let handle=`rpc-${++this.serial}`,storedProfile=frozenProfile(profile),entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),cwd:profile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve(),...requestedDurableId!==void 0?{durableSessionId:requestedDurableId}:{}},workerFailure,worker=this.createWorker({reserve:path=>this.reserve(handle,path),reconcile:livePaths=>this.reconcile(handle,livePaths),exit:()=>{this.entries.get(handle)===entry&&(entry.state="closed",this.entries.delete(handle),this.reservations.releaseAll(handle),entry.closeResolve?.())},failure:error2=>{workerFailure=error2,entry.state="quarantined",process.stderr.write(`senpi rpc session ${handle} quarantined: ${error2}
13
13
  `)}});entry.worker=worker,this.entries.set(handle,entry);try{let path=await worker.prepare(this.options.configuration,profile),owner=this.reservations.owner(path);if(owner){let attached=this.attach(owner,path,options);return entry.state="quarantined",worker.quarantine(),attached}let grant=this.reserve(handle,path);if(grant!=="granted")throw new RpcSessionRegistryError(RESERVATION_DENIAL_CODES[grant]);entry.reservationKey=path,entry.requestedPathKey=profile.sessionPath?path:void 0,entry.sessionPath=path;let snapshot=await worker.commit();if(entry.state!=="opening")throw workerFailure===void 0?new RpcSessionRegistryError("session_closing"):new RpcSessionRegistryError("open_failed",workerFailure);return entry.durableSessionId=snapshot.state.sessionId,entry.cwd=snapshot.state.cwd,entry.state="open",this.openResult(handle,entry)}catch(cause){throw entry.state="quarantined",worker.quarantine(),cause}}peek(handle){return this.entries.get(handle)}getForCommand(handle,command){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="quarantined"||entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return entry.lastCommandAt=this.now(),entry}beginClose(handle,onRole,options){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"||entry.state==="quarantined")return onRole?.(!1),entry;if(entry.state!=="open"&&entry.state!=="opening")throw new RpcSessionRegistryError("unknown_session");return entry.attachments--,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry):(entry.state="closing",entry.closeCompletion=new Promise(resolve=>{entry.closeResolve=resolve}),onRole?.(!0),entry)}close(handle){return this.beginClose(handle).state==="closing"?this.closeMarked(handle):Promise.resolve()}async closeMarked(handle){let entry=this.entries.get(handle);if(entry?.state!=="closing"||!entry.worker)throw new RpcSessionRegistryError("unknown_session");if(entry.closeStarted)return entry.closeCompletion;entry.closeStarted=!0;let timer;await Promise.race([entry.worker.close(this.closeGraceMs),new Promise(resolve=>{timer=setTimeout(()=>{entry.state!=="closed"&&(entry.state="quarantined"),resolve()},this.closeGraceMs)})]),timer&&clearTimeout(timer)}list(){return[...this.entries].map(([sessionId,entry])=>{let state=entry.worker?.snapshot?.state;return{sessionId,durableSessionId:state?.sessionId??entry.durableSessionId,sessionPath:state?.sessionFile??entry.sessionPath,cwd:state?.cwd??entry.cwd,name:state?.sessionName,kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}})}knownReservationKey(path){if(this.reservations.owner(path))return path;for(let entry of this.entries.values()){if(entry.profile.sessionPath===path&&entry.requestedPathKey&&this.reservations.owner(entry.requestedPathKey))return entry.requestedPathKey;let snapshot=entry.worker?.snapshot;if(snapshot?.state.sessionFile===path)return snapshot.sessionPath}}attach(owner,path,options){let entry=this.entries.get(owner);if(entry?.state!=="open"||!entry.worker?.bindingReady||entry.worker.snapshot?.sessionPath!==path)throw new RpcSessionRegistryError("session_path_in_use");let result=this.openResult(owner,entry);return entry.attachments++,options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),entry.lastCommandAt=this.now(),{...result,attached:!0}}reservationCount(handle){return this.reservations.count(handle)}reserve(handle,path){let entry=this.entries.get(handle);return entry?this.reservations.owner(path)===handle?"granted":entry.state!=="opening"&&entry.state!=="open"?"conflict":this.reservations.reserve(handle,path,this.liveWorkerPaths(entry)):"conflict"}reconcile(handle,livePaths){let entry=this.entries.get(handle);if(entry?.state!=="open")return;let sessionPath=entry.worker?.snapshot?.sessionPath;this.reservations.reconcile(handle,{livePaths,sessionPath}),sessionPath&&(entry.reservationKey=sessionPath,entry.sessionPath=sessionPath)}liveWorkerPaths(entry){let snapshot=entry.state==="open"?entry.worker?.snapshot:void 0;if(snapshot)return{livePaths:snapshot.liveSessionPaths,sessionPath:snapshot.sessionPath}}openResult(handle,entry){let state=entry.worker?.snapshot?.state;if(!state)throw new RpcSessionRegistryError("open_failed");return{sessionId:handle,durableSessionId:state.sessionId,sessionPath:state.sessionFile}}};var WINDOWS_SHUTDOWN_HARD_EXIT_MS=2e3;function startHostObservers(router,writer,options={}){let loopLag=new LoopLagWatchdog({emit:record=>writer.broadcastHostRecord(record)}),memory=new HostMemorySampler({emit:record=>writer.broadcastHostRecord(record),sessions:()=>router.sessionCount,onPressure:pressure=>router.setMemoryPressure(pressure),...options.onIdlePressure?{onIdlePressure:options.onIdlePressure}:{}});return loopLag.start(),memory.start(),{stop:()=>{loopLag.stop(),memory.stop()}}}async function runMultiSessionHost(options){return runAsHostGenerationProcess(()=>options.listen===void 0||options.listen==="stdio://"?runStdioHost(options):runSocketHost(options,resolveSocketPath(options.listen,options.agentDir)))}function createHostCore(options,writer,capabilities=parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),idle={},hostContext){let policy=resolveHostIdlePolicy(process.env,idle),router=new SessionCommandRouter(options.workerConfiguration?new WorkerSessionRegistry({configuration:options.workerConfiguration,now:policy.now,closeGraceMs:idle.closeGraceMs??parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV])??1e4}):new RpcSessionRegistry({agentDir:options.agentDir,createRuntime:options.createRuntime,mcpRegistry:new HostMcpRegistry,now:policy.now,closeGraceMs:idle.closeGraceMs??parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV])??1e4,pathReservations:createEndpointReservations({agentDir:options.agentDir,socket:listenSocketPath(options),instanceId:hostInstanceId(),onFailure:hostLog})}),writer,hostContext?{...options,hostContext}:options,options.createBinding,{capabilities},{now:policy.now,idleEvictionMs:policy.idleEvictionMs,emptyExitMs:policy.emptyExitMs,onEmptyExit:idle.onEmptyExit,onHandoffParked:idle.onHandoffParked,canExitWhenEmpty:idle.canExitWhenEmpty});return{router,handle:async line=>{let parsed;try{parsed=JSON.parse(line)}catch(cause){await writer.enqueueControl(parseError(`Failed to parse command: ${errorMessage(cause)}`));return}let shapeError=rpcCommandShapeError(parsed);if(shapeError){await writer.enqueueControl(parseError(shapeError));return}let response=await router.handle(parsed);response&&await writer.enqueueControl(response)}}}async function runStdioHost(options){takeOverStdout();let sink={writeRaw:writeRawStdout,waitForBackpressure:waitForRawStdoutBackpressure},writer=new SessionEventWriter(sink.writeRaw,sink.waitForBackpressure),{router,handle}=createHostCore(options,writer,void 0,{onEmptyExit:()=>{shutdown(0)}}),observers=startHostObservers(router,writer),shuttingDown=!1,shutdown=async(exitCode=0)=>{shuttingDown&&process.exit(exitCode),shuttingDown=!0,observers.stop(),detach(),await router.dispose(),await writer.flush(),await flushRawStdout(),process.exit(exitCode)},onEnd=()=>{shutdown()};process.stdin.on("end",onEnd);let reportInputFailure=cause=>{process.stderr.write(`senpi rpc stdio request failed: ${errorMessage(cause)}
14
14
  `)},detachReader=attachJsonlLineReader(process.stdin,line=>{handle(line).catch(reportInputFailure)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>{writer.enqueueControl(parseError(oversizedLineError())).catch(reportInputFailure)}}),detach=()=>{detachReader(),process.stdin.off("end",onEnd)};return registerShutdownSignals(shutdown),new Promise(()=>{})}async function runSocketHost(options,socketPath){await prepareSocketPath(socketPath);let writer=new SessionEventWriter(()=>{}),connections=new Map,occupancy=new ClientOccupancy(()=>{}),draining=!1,handoffAnnounced=!1,hostContext=hostSessionContext(socketPath),{router,handle}=createHostCore(options,writer,[...parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")).filter(capability=>capability!=="rendered_components"),GENERATION_HANDOFF_CAPABILITY],{onEmptyExit:()=>{shutdown(0)},canExitWhenEmpty:()=>draining||occupancy.attachedCount===0&&occupancy.unclassifiedCount===0,onHandoffParked:async ids=>{await Promise.all(ids.map(async id=>{await writer.flushConnection(id),connections.get(id)?.close()}))}},hostContext),observers=startHostObservers(router,writer,{onIdlePressure:rssMb=>{hostLog(`memory pressure with no sessions: rssMb=${rssMb}`),endpointSuperseded().then(superseded=>{superseded&&drainForHandoff()},noop)}}),nextConnection=0,shuttingDown=!1,secret=process.platform==="win32"?await ensureSocketSecret(process.env[SOCKET_SECRET_FILE_ENV]??socketSecretPath(socketPath)):void 0,watchdogConfig=readHostWatchdogConfigFromBrandEnv(),crashCleanupPaths=[...watchdogConfig?.cleanupPaths??[]],supervisorPublicSocketPath=process.platform==="win32"||socketPath.startsWith("\0")?void 0:watchdogConfig?.publicSocket,supervisorPublicOwnerFile=supervisorPublicSocketPath&&watchdogConfig?.scratchDir?join(watchdogConfig.scratchDir,PUBLIC_SOCKET_IDENTITY_FILE):void 0,boundIdentity,supervisorPublicIdentity,server=createServer(socket=>{let accept=()=>{if(draining||shuttingDown){socket.destroy();return}let id=`socket-${++nextConnection}`,sink=socketSink(socket);writer.registerConnection(id,sink),occupancy.admit(socket);let detachReader=attachJsonlLineReader(socket,line=>{writer.withConnection(id,()=>handle(line)).catch(cause=>{process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}
15
15
  `)})},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>{writer.withConnection(id,()=>writer.enqueueControl(parseError(oversizedLineError()))).catch(cause=>process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-LSW7QSLV.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import"./chunk-KOPTADA3.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-6VD3EBQE.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import{SettingsManager}from"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import"./chunk-FHJYIU3U.js";import"./chunk-HH3KJDWA.js";import"./chunk-GJUCSTAG.js";import"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import{killProcessTree}from"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
2
+ import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-6XBT6OGS.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-SICBVLRH.js";import"./chunk-A4UMPXQF.js";import"./chunk-TFA3YAJK.js";import"./chunk-DRN4FQCE.js";import"./chunk-YS5YEX4S.js";import"./chunk-OP3QMR6B.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-6VD3EBQE.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import{SettingsManager}from"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-7YUGCTEV.js";import"./chunk-FHJYIU3U.js";import"./chunk-HH3KJDWA.js";import"./chunk-GJUCSTAG.js";import"./chunk-QOVUQZO4.js";import"./chunk-DA4W77J7.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VFSXUT7K.js";import"./chunk-62XHQXCZ.js";import{killProcessTree}from"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-EHSZ7UCW.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-BBK6SSYT.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-4LVZQRDG.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-WASCMT6Y.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
3
3
  `)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...process.execArgv,cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
4
4
  `,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
5
5
  `)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{runRpcMode}from"./chunk-KOPTADA3.js";import"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-HH3KJDWA.js";import"./chunk-QOVUQZO4.js";import"./chunk-HB35RBP4.js";import"./chunk-62XHQXCZ.js";import"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{runRpcMode};
2
+ import{runRpcMode}from"./chunk-OP3QMR6B.js";import"./chunk-6VD3EBQE.js";import"./chunk-6BWCPOCV.js";import"./chunk-CNQ4JB45.js";import"./chunk-SN4ZHPMN.js";import"./chunk-YU2P3CAR.js";import"./chunk-HH3KJDWA.js";import"./chunk-QOVUQZO4.js";import"./chunk-HB35RBP4.js";import"./chunk-62XHQXCZ.js";import"./chunk-TRSQVD6V.js";import"./chunk-36ACNYQR.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-Y5A6TKBN.js";import"./chunk-LUPPSEQW.js";import"./chunk-26UBFF6N.js";import"./chunk-3GMFUEU7.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ELFCNCBY.js";import"./chunk-PBWQK23Z.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-L6QV7NZI.js";import"./chunk-45SZOLCU.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import"./chunk-WL5EQYNL.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{runRpcMode};