@code-yeongyu/senpi 2026.9.19-2 → 2026.9.20

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 (171) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/bundle/chunks/{app-server-command-QBJ4GPN7.js → app-server-command-B35FQUTE.js} +1 -1
  3. package/dist/bundle/chunks/{bun-extension-importer-JQZRPNJH.js → bun-extension-importer-HHH4TV4B.js} +3 -3
  4. package/dist/bundle/chunks/{chunk-YRN3PCTM.js → chunk-DQZB4GVV.js} +4 -4
  5. package/dist/bundle/chunks/{chunk-EHSDTQ6I.js → chunk-E5R67F7G.js} +37 -37
  6. package/dist/bundle/chunks/{chunk-5E5TLB76.js → chunk-TWGC3TBR.js} +2 -2
  7. package/dist/bundle/chunks/{chunk-RLRLQRI2.js → chunk-V2ZB62DG.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-3FRTRCR6.js → chunk-YXQG2SUX.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-PLZK7ABD.js → chunk-Z4LHCTJ6.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-3Q4WGKFA.js → chunk-ZMFHNH6U.js} +1 -1
  11. package/dist/bundle/chunks/{cli-main-MLJ2H637.js → cli-main-USVT7JMN.js} +1 -1
  12. package/dist/bundle/chunks/{interactive-host-runtime-AITXUDCT.js → interactive-host-runtime-ELBAZ4LN.js} +1 -1
  13. package/dist/bundle/chunks/{interactive-mode-7C75IXNF.js → interactive-mode-R6225BKI.js} +1 -1
  14. package/dist/bundle/chunks/{list-tips-KTDNGQUK.js → list-tips-Z7T2ACVU.js} +1 -1
  15. package/dist/bundle/chunks/{multi-session-host-2YCJKQOL.js → multi-session-host-QNEBJW2P.js} +3 -3
  16. package/dist/bundle/chunks/{package-manager-cli-4ANSELYT.js → package-manager-cli-4MVJ3JSE.js} +1 -1
  17. package/dist/bundle/chunks/{rpc-mode-OPFQIWFP.js → rpc-mode-CXVDRIBU.js} +1 -1
  18. package/dist/bundle/chunks/{session-picker-DXCITGLS.js → session-picker-6N666KQZ.js} +1 -1
  19. package/dist/bundle/chunks/session-worker.js +66 -66
  20. package/dist/bundle/cli.js +1 -1
  21. package/dist/bundle/index.js +1 -1
  22. package/dist/bundle/rpc-entry.js +1 -1
  23. package/dist/core/agent-session-services.d.ts.map +1 -1
  24. package/dist/core/agent-session-services.js +14 -1
  25. package/dist/core/agent-session-services.js.map +1 -1
  26. package/dist/core/agent-session.d.ts +45 -0
  27. package/dist/core/agent-session.d.ts.map +1 -1
  28. package/dist/core/agent-session.js +233 -11
  29. package/dist/core/agent-session.js.map +1 -1
  30. package/dist/core/extensions/builtin/ask-user/extension.d.ts.map +1 -1
  31. package/dist/core/extensions/builtin/ask-user/extension.js +16 -5
  32. package/dist/core/extensions/builtin/ask-user/extension.js.map +1 -1
  33. package/dist/core/extensions/builtin/ask-user/format.d.ts +5 -0
  34. package/dist/core/extensions/builtin/ask-user/format.d.ts.map +1 -1
  35. package/dist/core/extensions/builtin/ask-user/format.js +4 -0
  36. package/dist/core/extensions/builtin/ask-user/format.js.map +1 -1
  37. package/dist/core/extensions/builtin/ask-user/notify.d.ts +2 -0
  38. package/dist/core/extensions/builtin/ask-user/notify.d.ts.map +1 -1
  39. package/dist/core/extensions/builtin/ask-user/notify.js +2 -0
  40. package/dist/core/extensions/builtin/ask-user/notify.js.map +1 -1
  41. package/dist/core/extensions/builtin/ask-user/registry.d.ts +15 -2
  42. package/dist/core/extensions/builtin/ask-user/registry.d.ts.map +1 -1
  43. package/dist/core/extensions/builtin/ask-user/registry.js +13 -0
  44. package/dist/core/extensions/builtin/ask-user/registry.js.map +1 -1
  45. package/dist/core/extensions/builtin/ask-user/render.d.ts +6 -0
  46. package/dist/core/extensions/builtin/ask-user/render.d.ts.map +1 -1
  47. package/dist/core/extensions/builtin/ask-user/render.js +9 -0
  48. package/dist/core/extensions/builtin/ask-user/render.js.map +1 -1
  49. package/dist/core/extensions/builtin/ask-user/resume.d.ts.map +1 -1
  50. package/dist/core/extensions/builtin/ask-user/resume.js +59 -24
  51. package/dist/core/extensions/builtin/ask-user/resume.js.map +1 -1
  52. package/dist/core/extensions/builtin/ask-user/tool.d.ts +1 -1
  53. package/dist/core/extensions/builtin/ask-user/tool.d.ts.map +1 -1
  54. package/dist/core/extensions/builtin/ask-user/tool.js +98 -17
  55. package/dist/core/extensions/builtin/ask-user/tool.js.map +1 -1
  56. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts +18 -0
  57. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts.map +1 -1
  58. package/dist/core/extensions/builtin/compaction/model-usability-budget.js +16 -8
  59. package/dist/core/extensions/builtin/compaction/model-usability-budget.js.map +1 -1
  60. package/dist/core/extensions/builtin/compaction/switch-admission.d.ts +23 -0
  61. package/dist/core/extensions/builtin/compaction/switch-admission.d.ts.map +1 -0
  62. package/dist/core/extensions/builtin/compaction/switch-admission.js +19 -0
  63. package/dist/core/extensions/builtin/compaction/switch-admission.js.map +1 -0
  64. package/dist/core/extensions/builtin/goal/index.d.ts.map +1 -1
  65. package/dist/core/extensions/builtin/goal/index.js +10 -0
  66. package/dist/core/extensions/builtin/goal/index.js.map +1 -1
  67. package/dist/core/extensions/bun-extension-commonjs.d.ts +1 -1
  68. package/dist/core/extensions/bun-extension-commonjs.d.ts.map +1 -1
  69. package/dist/core/extensions/bun-extension-commonjs.js +3 -3
  70. package/dist/core/extensions/bun-extension-commonjs.js.map +1 -1
  71. package/dist/core/extensions/bun-extension-importer.d.ts.map +1 -1
  72. package/dist/core/extensions/bun-extension-importer.js +4 -1
  73. package/dist/core/extensions/bun-extension-importer.js.map +1 -1
  74. package/dist/core/extensions/bun-extension-registry.d.ts.map +1 -1
  75. package/dist/core/extensions/bun-extension-registry.js +5 -9
  76. package/dist/core/extensions/bun-extension-registry.js.map +1 -1
  77. package/dist/core/resolved-paths-memo.d.ts +31 -0
  78. package/dist/core/resolved-paths-memo.d.ts.map +1 -0
  79. package/dist/core/resolved-paths-memo.js +57 -0
  80. package/dist/core/resolved-paths-memo.js.map +1 -0
  81. package/dist/core/resource-loader.d.ts +4 -1
  82. package/dist/core/resource-loader.d.ts.map +1 -1
  83. package/dist/core/resource-loader.js +25 -12
  84. package/dist/core/resource-loader.js.map +1 -1
  85. package/dist/core/retry-fallback/settings.d.ts +10 -2
  86. package/dist/core/retry-fallback/settings.d.ts.map +1 -1
  87. package/dist/core/retry-fallback/settings.js +28 -6
  88. package/dist/core/retry-fallback/settings.js.map +1 -1
  89. package/dist/core/skill-discovery.d.ts.map +1 -1
  90. package/dist/core/skill-discovery.js +11 -1
  91. package/dist/core/skill-discovery.js.map +1 -1
  92. package/dist/main.d.ts +10 -0
  93. package/dist/main.d.ts.map +1 -1
  94. package/dist/main.js +19 -2
  95. package/dist/main.js.map +1 -1
  96. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts +2 -5
  97. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts.map +1 -1
  98. package/dist/modes/interactive/components/ask-user-answer-chip.js +1 -4
  99. package/dist/modes/interactive/components/ask-user-answer-chip.js.map +1 -1
  100. package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
  101. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  102. package/dist/modes/interactive/components/assistant-message.js +8 -0
  103. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  104. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts +1 -0
  105. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts.map +1 -1
  106. package/dist/modes/interactive/components/assistant-render-descriptors.js +4 -0
  107. package/dist/modes/interactive/components/assistant-render-descriptors.js.map +1 -1
  108. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  109. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  110. package/dist/modes/interactive/components/status-indicator.js +15 -2
  111. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  112. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  113. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  114. package/dist/modes/interactive/interactive-mode.js +81 -6
  115. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  116. package/dist/modes/interactive/provider-error-presentation.d.ts +18 -0
  117. package/dist/modes/interactive/provider-error-presentation.d.ts.map +1 -0
  118. package/dist/modes/interactive/provider-error-presentation.js +100 -0
  119. package/dist/modes/interactive/provider-error-presentation.js.map +1 -0
  120. package/dist/modes/rpc/rpc-types.d.ts +18 -0
  121. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  122. package/dist/modes/rpc/rpc-types.js.map +1 -1
  123. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  124. package/dist/modes/rpc/session-command-router.js +14 -0
  125. package/dist/modes/rpc/session-command-router.js.map +1 -1
  126. package/dist/modes/rpc/session-event-writer.d.ts +9 -1
  127. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  128. package/dist/modes/rpc/session-event-writer.js +21 -0
  129. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  130. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  131. package/dist/modes/rpc/session-registry.js +9 -2
  132. package/dist/modes/rpc/session-registry.js.map +1 -1
  133. package/dist/modes/rpc/session-worker-requests.d.ts +10 -1
  134. package/dist/modes/rpc/session-worker-requests.d.ts.map +1 -1
  135. package/dist/modes/rpc/session-worker-requests.js +8 -2
  136. package/dist/modes/rpc/session-worker-requests.js.map +1 -1
  137. package/dist/modes/rpc/session-worker-requests.test.d.ts +2 -0
  138. package/dist/modes/rpc/session-worker-requests.test.d.ts.map +1 -0
  139. package/dist/modes/rpc/session-worker-requests.test.js +44 -0
  140. package/dist/modes/rpc/session-worker-requests.test.js.map +1 -0
  141. package/docs/rpc.md +7 -0
  142. package/docs/settings.md +1 -1
  143. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
  144. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  145. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  146. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  147. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  148. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  149. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  150. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  151. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  152. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  153. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  154. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  155. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  156. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  157. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.d.ts.map +1 -1
  158. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.js +26 -3
  159. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.js.map +1 -1
  160. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
  161. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +13 -6
  162. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
  163. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
  164. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +11 -3
  165. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
  166. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +15 -2
  167. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
  168. package/node_modules/@earendil-works/pi-tui/dist/tui.js +45 -2
  169. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  170. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  171. package/package.json +8 -8
@@ -1,15 +1,15 @@
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,ProviderScope,bindToProviderScope,createAgentSessionRuntime,runWithProviderScope}from"./chunk-EHSDTQ6I.js";import"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import{SessionManager}from"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.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,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-5E5TLB76.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import{GENERATION_HANDOFF_CAPABILITY}from"./chunk-P7PWCGLJ.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-U6Z6OBX4.js";import{HOST_DAEMON_DIR_ENV,PUBLIC_SOCKET_IDENTITY_FILE,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,createHostDaemonPaths,ensureSocketSecret,parseIdleExitMs,processIsLive,readHostWatchdogConfigFromBrandEnv,readProcessStartTime,readSocketIdentityFile,resolveSocketTransportAddress,shieldSocketDuringClose,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-LF3XTYYF.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostInstanceId,protocolIdentity}from"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killTrackedDetachedChildren}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import{VERSION,envValue,isBunBinary}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{access,chmod,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{dirname as dirname2,join as join2}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 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;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,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.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();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,ProviderScope,bindToProviderScope,createAgentSessionRuntime,runWithProviderScope}from"./chunk-E5R67F7G.js";import"./chunk-YXQG2SUX.js";import"./chunk-EONVPHVX.js";import"./chunk-ZMFHNH6U.js";import{SessionManager}from"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.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,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-TWGC3TBR.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-V2ZB62DG.js";import"./chunk-DQZB4GVV.js";import"./chunk-Z4LHCTJ6.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import{GENERATION_HANDOFF_CAPABILITY}from"./chunk-P7PWCGLJ.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-U6Z6OBX4.js";import{HOST_DAEMON_DIR_ENV,PUBLIC_SOCKET_IDENTITY_FILE,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,createHostDaemonPaths,ensureSocketSecret,parseIdleExitMs,processIsLive,readHostWatchdogConfigFromBrandEnv,readProcessStartTime,readSocketIdentityFile,resolveSocketTransportAddress,shieldSocketDuringClose,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-LF3XTYYF.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostInstanceId,protocolIdentity}from"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killTrackedDetachedChildren}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import{VERSION,envValue,isBunBinary}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{access,chmod,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{dirname as dirname2,join as join2}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 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;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,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.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();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{createHash}from"node:crypto";import{mkdir,readFile,rename,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var SESSION_PATH_RETRY_AFTER_MS=2e3;function reservationFile(dir,sessionPath){return join(dir,`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`)}function createEndpointReservations(host){let told=process.env[HOST_DAEMON_DIR_ENV],dir=told!==void 0&&told.trim()!==""?told:host.socket===void 0?void 0:createHostDaemonPaths({socket:host.socket,agentDir:host.agentDir}).dir;if(dir!==void 0)return createSessionPathReservations({dir:join(dir,"reservations"),instanceId:host.instanceId,...host.onFailure?{onFailure:host.onFailure}:{}})}function createSessionPathReservations(options){let pid=options.pid??process.pid,startTime=readProcessStartTime(pid).then(value=>value??null,()=>null),held=new Set,report=message=>options.onFailure?.(message);return{async claim(sessionPath){let file=reservationFile(options.dir,sessionPath),existing=await readOwner(file);if(existing&&existing.pid!==pid&&await ownerIsLive(existing))return existing;let owner={instanceId:options.instanceId,pid,processStartTime:await startTime,sessionPath};try{await mkdir(options.dir,{recursive:!0,mode:448});let staging=`${file}.${pid}.tmp`;await writeFile(staging,`${JSON.stringify(owner)}
4
4
  `,{mode:384}),await rename(staging,file),held.add(sessionPath)}catch(cause){report(`session path reservation for ${sessionPath} could not be written (${errorMessage(cause)})`)}},release(sessionPath){held.delete(sessionPath)&&rm(reservationFile(options.dir,sessionPath),{force:!0}).catch(cause=>{report(`session path reservation for ${sessionPath} could not be removed (${errorMessage(cause)})`)})}}}async function readOwner(file){let parsed;try{parsed=JSON.parse(await readFile(file,"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let{instanceId,pid,processStartTime,sessionPath}=parsed;if(!(typeof instanceId!="string"||typeof pid!="number"||typeof sessionPath!="string"))return{instanceId,pid,processStartTime:typeof processStartTime=="string"?processStartTime:null,sessionPath}}async function ownerIsLive(owner){if(!processIsLive(owner.pid))return!1;if(owner.processStartTime===null)return!0;let current=await readProcessStartTime(owner.pid).catch(()=>{});return current===void 0||current===owner.processStartTime}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}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;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;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.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(){this.timer===void 0&&(this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark(),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 driftMs=Math.round(now-expectedAt);if(driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool}),!(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)})
5
5
  `))}};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(`
6
6
  `)){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,realpathSync}from"node:fs";import{basename,dirname,isAbsolute,resolve}from"node:path";function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
7
- `)}function beginSessionClose(host,handle,onRole,options){let entry=host.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve2=>{entry.closeResolve=resolve2}),entry)}function closeSession(host,handle){return beginSessionClose(host,handle).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle)}function closeMarkedSession(host,handle){host.sync();let entry=host.get(handle);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await entry.scope.close?.())},release=()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.state="closed",host.delete(handle),entry.reservationKey&&host.releaseReservation(entry.reservationKey))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle,cause)}})(),settled=!1,finish=()=>{settled||(settled=!0,release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle,cause)),graceful.catch(cause=>reportDetachedFailure(handle,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>{reportDetachedFailure(handle,cause),finish()}),completion}var RpcSessionRegistryError=class extends Error{constructor(code,reason,detail){super(code==="open_failed"&&reason?`${code}: ${reason}`:code),this.code=code,this.name="RpcSessionRegistryError",detail&&(this.detail=detail)}};function canonicalPath(path){let absolutePath=resolve(path);return existsSync(absolutePath)?realpathSync(absolutePath):`${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`}function frozenProfile(profile){return Object.freeze({...profile,...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}var RpcSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new Set,this.nextHandle=0,this.options=options,this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle=>this.entries.get(handle),delete:handle=>this.entries.delete(handle),releaseReservation:key=>{this.reservations.delete(key),this.options.pathReservations?.release(key)},sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}async openSession(profile,options){this.validateProfile(profile),this.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalPath(profile.sessionPath):void 0;if(sessionPath&&await this.settleClosingReservation(sessionPath),sessionPath&&this.reservations.has(sessionPath)){let existing=[...this.entries].find(([,entry3])=>entry3.reservationKey===sessionPath&&entry3.state==="open");if(!existing)throw new RpcSessionRegistryError("session_path_in_use");let[handle2,entry2]=existing;if(entry2.attachments+=1,options?.retainOnDisconnect&&(entry2.retainOnDisconnect=!0),!entry2.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return entry2.lastCommandAt=this.now(),{sessionId:handle2,durableSessionId:entry2.durableSessionId,sessionPath:entry2.sessionPath,attached:!0}}if(sessionPath){this.reservations.add(sessionPath);let holder=this.options.pathReservations?await this.options.pathReservations.claim(sessionPath):void 0;if(holder)throw this.reservations.delete(sessionPath),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}let isResume=sessionPath!==void 0&&existsSync(sessionPath),sessionStartEvent=isResume?{type:"session_start",reason:"resume"}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,handle=`rpc-${++this.nextHandle}`,entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve()};entry.switchSession=(sessionPath2,options2)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options2?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath2,options2);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,this.options.createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),entry.runtime=replacement,this.syncRuntimeMetadata(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation},this.entries.set(handle,entry);try{let manager=sessionPath?SessionManager.open(sessionPath,void 0,storedProfile.cwd):SessionManager.create(storedProfile.cwd);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(this.options.createRuntime,{cwd:manager.getCwd(),agentDir:this.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),entry.state="open",{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{this.entries.delete(handle),sessionPath&&(this.reservations.delete(sessionPath),this.options.pathReservations?.release(sessionPath))}}throw error2 instanceof RpcSessionRegistryError?error2:new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0)}}async settleClosingReservation(sessionPath){let closing=[...this.entries.values()].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve2=>{deadline=setTimeout(resolve2,this.closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}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==="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){return beginSessionClose(this.teardownHost,handle,onRole,options)}async close(handle){return closeSession(this.teardownHost,handle)}async closeMarked(handle){return closeMarkedSession(this.teardownHost,handle)}list(){return this.syncRuntimeMetadata(),[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}))}syncRuntimeMetadata(){for(let entry of this.entries.values()){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile();if(currentPath!==entry.sessionPath){let currentKey=currentPath?canonicalPath(currentPath):void 0;entry.reservationKey&&(this.reservations.delete(entry.reservationKey),this.options.pathReservations?.release(entry.reservationKey)),currentKey&&(this.reservations.add(currentKey),this.options.pathReservations?.claim(currentKey)),entry.reservationKey=currentKey,entry.sessionPath=currentPath}entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}validateProfile(profile){if(!isAbsolute(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path")}};var controls=new Set(["get_protocol_info","open_session","close_session","list_sessions"]),DRAIN_SWEEP_MS=50;function error(id,command,code,data){return{id,type:"response",command,success:!1,error:code,...data&&{errorCode:code,errorData:data}}}var SessionCommandRouter=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.opensByConnection=new Map,this.releasedConnections=new Set,this.widths=new Map,this.pendingCapabilities=new Map,this.finalizations=new Map,this.draining=!1,this.memoryPressure=!1,this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.canExitWhenEmpty=idle?.canExitWhenEmpty,Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>this.sweepIdleSessions(),tickMs),this.sweepTimer.unref?.()}}get sessionCount(){return this.registry.size}beginDrain(){this.draining||(this.draining=!0,this.sweepDrain(),this.drainTimer===void 0&&(this.drainTimer=setInterval(()=>this.sweepDrain(),DRAIN_SWEEP_MS),this.drainTimer.unref?.()))}sweepDrain(){for(let{sessionId,status}of this.registry.list()){if(status!=="open")continue;let entry=this.registry.peek(sessionId);!entry||entry.attachments>0||entry.worker?.busy||entry.runtime?.session.isSessionBusy||this.evictIdleSession(sessionId,"handoff_parked")}this.registry.size>0||(this.drainTimer!==void 0&&(clearInterval(this.drainTimer),this.drainTimer=void 0),this.stopSweep(),this.onEmptyExit?.())}setMemoryPressure(pressure){this.memoryPressure=pressure}handle(command){let sessionId="sessionId"in command?command.sessionId:void 0;return runWithSessionAttribution({sessionId},()=>this.dispatch(command))}async dispatch(command){if(command.type==="get_protocol_info"){let capabilities=new Set(["multi_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,...this.connectionOptions?.capabilities??[]]);return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities:[...capabilities],mode:"multi",...protocolIdentity()}}}if(command.type==="list_sessions"){let rows=this.registry.list(),sessions=command.include_workers===!0?rows:rows.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="open_session")return this.openWithBarrier(command);if(command.type==="close_session")return this.close(command);if(command.type==="set_client_info"&&!command.sessionId){let connection=this.writer.currentConnection();return connection!==void 0&&(this.pendingCapabilities.set(connection,command.capabilities??[]),this.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0}}if(!controls.has(command.type)){if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);try{this.registry.getForCommand(command.sessionId,command.type);let binding=this.bindings.get(command.sessionId);if(!binding)return error(command.id,command.type,RPC_ERROR_UNKNOWN_SESSION);await binding.handle(command);return}catch(cause){return error(command.id,command.type,this.code(cause))}}}async dispose(){this.stopSweep(),await Promise.all([...this.bindings.entries()].map(async([sessionId,binding])=>{let claim=this.tryClaimClose(sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await this.finalizeClose(sessionId,binding,()=>this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId))})),this.bindings.clear()}sweepIdleSessions(){let now=this.idleNow(),idleEvictionMs=this.memoryPressure?this.idleEvictionMs/2:this.idleEvictionMs;if(Number.isFinite(idleEvictionMs))for(let{sessionId,status}of this.registry.list()){if(status!=="open")continue;let entry=this.registry.peek(sessionId);if(entry){if(entry.worker?.busy||entry.runtime?.session.isSessionBusy){entry.lastCommandAt=now;continue}now-entry.lastCommandAt>=idleEvictionMs&&this.evictIdleSession(sessionId)}}Number.isFinite(this.emptyExitMs)&&(this.registry.size===0&&(this.canExitWhenEmpty?.()??!0)?this.emptySince===void 0?this.emptySince=now:now-this.emptySince>=this.emptyExitMs&&(this.stopSweep(),this.onEmptyExit?.()):this.emptySince=void 0)}async evictIdleSession(sessionId,reason){let retained=this.registry.peek(sessionId),parkedPath=retained?.retainOnDisconnect===!0?retained.sessionPath:void 0,claim=this.tryClaimClose(sessionId,{drainAttachments:!0});if(!claim)return;let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),this.forgetSessionOwnership(sessionId),claim.finalizer?await this.finalizeClose(sessionId,binding,()=>parkedPath!==void 0&&reason===void 0?this.writer.parkSession(sessionId,parkedPath):this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},reason??"idle_evicted")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId)}forgetSessionOwnership(sessionId){for(let[connection,owned]of this.sessionsByConnection)owned.delete(sessionId),owned.size===0&&this.sessionsByConnection.delete(connection);this.widths.delete(sessionId)}stopSweep(){this.sweepTimer!==void 0&&(clearInterval(this.sweepTimer),this.sweepTimer=void 0)}openWithBarrier(command){let owner=this.writer.currentConnection();if(owner===void 0)return this.open(command);let resolveBarrier,barrier=new Promise(resolve2=>{resolveBarrier=resolve2}),opens=this.opensByConnection.get(owner)??new Set;return opens.add(barrier),this.opensByConnection.set(owner,opens),this.open(command,owner).finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&this.opensByConnection.delete(owner)})}async open(command,owner){let kindError=sessionKindError(command.kind);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let opened;try{opened=await this.registry.openSession({cwd:command.cwd??this.defaults.cwd,sessionPath:command.sessionPath,permissionPreset:command.permissionPreset??this.defaults.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:this.defaults.creationModel,initialThinkingLevel:command.thinkingLevel??this.defaults.initialThinkingLevel,sessionKind:command.kind,sessionContext:command.context,...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{}},{retainOnDisconnect:command.retain_on_disconnect===!0});let openedSession=opened,entry=this.registry.getForCommand(openedSession.sessionId,"open_session");if(this.writer.setSessionKind(openedSession.sessionId,entry.kind),owner!==void 0&&(this.writer.hasRegisteredConnectionCapabilities(owner)||this.writer.setConnectionCapabilities(owner,this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]),this.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=this.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),this.sessionsByConnection.set(owner,owned)}this.bindings.has(openedSession.sessionId)||(this.bindings.set(openedSession.sessionId,await this.createBinding(openedSession.sessionId,entry,this.writer,()=>{this.close({type:"close_session",sessionId:openedSession.sessionId})},{...this.connectionOptions,capabilities:owner!==void 0?this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]:this.connectionOptions?.capabilities,sharedWidth:{getWidth:()=>{let widths=this.widths.get(openedSession.sessionId);return widths?.size?Math.min(...widths.values()):80},setWidth:(connectionId,width)=>{if(connectionId!==void 0){let widths=this.widths.get(openedSession.sessionId)??new Map;widths.set(connectionId,width),this.widths.set(openedSession.sessionId,widths)}},clearWidth:connectionId=>{let widths=this.widths.get(openedSession.sessionId);connectionId!==void 0&&widths?.delete(connectionId)},setCapabilities:(connectionId,capabilities)=>{if(connectionId!==void 0){this.writer.setConnectionCapabilities(connectionId,capabilities),this.pendingCapabilities.set(connectionId,[...capabilities]);for(let binding of this.bindings.values())binding.rerenderComponents?.()}},hasRenderedComponents:sessionId=>this.writer.hasCapableConnection(sessionId),connectionId:()=>this.writer.currentConnection(),onChange:()=>{for(let binding of this.bindings.values())binding.rerenderComponents?.()}}})),entry.worker&&(entry.worker.bindingReady=!0),entry.worker&&entry.worker.exited.then(async()=>{await this.finalizations.get(openedSession.sessionId)?.promise,this.bindings.delete(openedSession.sessionId),this.forgetSessionOwnership(openedSession.sessionId),this.writer.forgetSession(openedSession.sessionId)})),owner!==void 0&&this.releasedConnections.has(owner)&&(this.releaseOwnerAttachment(owner,openedSession.sessionId),await this.releaseOwnedSession(openedSession.sessionId));let state=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!state)throw new Error("Session state was not created");this.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened)try{await this.registry.close(opened.sessionId)}catch{}return error(command.id,"open_session",this.code(cause),this.detail(cause))}}async releaseConnection(connectionId){this.releasedConnections.add(connectionId),this.writer.clearConnectionCapabilities(connectionId);for(let sessionId of this.sessionsByConnection.get(connectionId)?.keys()??[])this.writer.detachConnectionFromSession(connectionId,sessionId);for(let widths of this.widths.values())widths.delete(connectionId);for(let binding of this.bindings.values())binding.rerenderComponents?.();let opens=this.opensByConnection.get(connectionId),owned=this.sessionsByConnection.get(connectionId);if(this.sessionsByConnection.delete(connectionId),owned===void 0){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++){let live=this.registry.peek(sessionId),retained=live?.retainOnDisconnect===!0,session=live?.state==="open"?live.runtime?.session:void 0;if(!retained&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
7
+ `)}function beginSessionClose(host,handle,onRole,options){let entry=host.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve2=>{entry.closeResolve=resolve2}),entry)}function closeSession(host,handle){return beginSessionClose(host,handle).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle)}function closeMarkedSession(host,handle){host.sync();let entry=host.get(handle);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await entry.scope.close?.())},release=()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.state="closed",host.delete(handle),entry.reservationKey&&host.releaseReservation(entry.reservationKey))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle,cause)}})(),settled=!1,finish=()=>{settled||(settled=!0,release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle,cause)),graceful.catch(cause=>reportDetachedFailure(handle,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>{reportDetachedFailure(handle,cause),finish()}),completion}var RpcSessionRegistryError=class extends Error{constructor(code,reason,detail){super(code==="open_failed"&&reason?`${code}: ${reason}`:code),this.code=code,this.name="RpcSessionRegistryError",detail&&(this.detail=detail)}};function canonicalPath(path){let absolutePath=resolve(path);return existsSync(absolutePath)?realpathSync(absolutePath):`${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`}function frozenProfile(profile){return Object.freeze({...profile,...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}var RpcSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new Set,this.nextHandle=0,this.options=options,this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle=>this.entries.get(handle),delete:handle=>this.entries.delete(handle),releaseReservation:key=>{this.reservations.delete(key),this.options.pathReservations?.release(key)},sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}async openSession(profile,options){this.validateProfile(profile),this.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalPath(profile.sessionPath):void 0;if(sessionPath&&await this.settleClosingReservation(sessionPath),sessionPath&&this.reservations.has(sessionPath)){let existing=[...this.entries].find(([,entry3])=>entry3.reservationKey===sessionPath&&entry3.state==="open");if(!existing)throw new RpcSessionRegistryError("session_path_in_use");let[handle2,entry2]=existing;if(entry2.attachments+=1,options?.retainOnDisconnect&&(entry2.retainOnDisconnect=!0),!entry2.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return entry2.lastCommandAt=this.now(),{sessionId:handle2,durableSessionId:entry2.durableSessionId,sessionPath:entry2.sessionPath,attached:!0}}if(sessionPath){this.reservations.add(sessionPath);let holder=this.options.pathReservations?await this.options.pathReservations.claim(sessionPath):void 0;if(holder)throw this.reservations.delete(sessionPath),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}let isResume=sessionPath!==void 0&&existsSync(sessionPath),sessionStartEvent=isResume?{type:"session_start",reason:"resume"}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,handle=`rpc-${++this.nextHandle}`,entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve()};entry.switchSession=(sessionPath2,options2)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options2?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath2,options2);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,this.options.createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),entry.runtime=replacement,this.syncRuntimeMetadata(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation},this.entries.set(handle,entry);try{let manager=sessionPath?SessionManager.open(sessionPath,void 0,storedProfile.cwd):SessionManager.create(storedProfile.cwd);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(this.options.createRuntime,{cwd:manager.getCwd(),agentDir:this.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),entry.state="open",{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{this.entries.delete(handle),sessionPath&&(this.reservations.delete(sessionPath),this.options.pathReservations?.release(sessionPath))}}throw error2 instanceof RpcSessionRegistryError?error2:new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0)}}async settleClosingReservation(sessionPath){let closing=[...this.entries.values()].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve2=>{deadline=setTimeout(resolve2,this.closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}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==="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){return beginSessionClose(this.teardownHost,handle,onRole,options)}async close(handle){return closeSession(this.teardownHost,handle)}async closeMarked(handle){return closeMarkedSession(this.teardownHost,handle)}list(){return this.syncRuntimeMetadata(),[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}))}syncRuntimeMetadata(){for(let entry of this.entries.values()){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(this.reservations.delete(entry.reservationKey),this.options.pathReservations?.release(entry.reservationKey)),currentKey&&(this.reservations.add(currentKey),this.options.pathReservations?.claim(currentKey)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}validateProfile(profile){if(!isAbsolute(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path")}};var controls=new Set(["get_protocol_info","open_session","close_session","list_sessions"]),DRAIN_SWEEP_MS=50;function error(id,command,code,data){return{id,type:"response",command,success:!1,error:code,...data&&{errorCode:code,errorData:data}}}var SessionCommandRouter=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.opensByConnection=new Map,this.releasedConnections=new Set,this.widths=new Map,this.pendingCapabilities=new Map,this.finalizations=new Map,this.draining=!1,this.memoryPressure=!1,this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.canExitWhenEmpty=idle?.canExitWhenEmpty,Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>this.sweepIdleSessions(),tickMs),this.sweepTimer.unref?.()}}get sessionCount(){return this.registry.size}beginDrain(){this.draining||(this.draining=!0,this.sweepDrain(),this.drainTimer===void 0&&(this.drainTimer=setInterval(()=>this.sweepDrain(),DRAIN_SWEEP_MS),this.drainTimer.unref?.()))}sweepDrain(){for(let{sessionId,status}of this.registry.list()){if(status!=="open")continue;let entry=this.registry.peek(sessionId);!entry||entry.attachments>0||entry.worker?.busy||entry.runtime?.session.isSessionBusy||this.evictIdleSession(sessionId,"handoff_parked")}this.registry.size>0||(this.drainTimer!==void 0&&(clearInterval(this.drainTimer),this.drainTimer=void 0),this.stopSweep(),this.onEmptyExit?.())}setMemoryPressure(pressure){this.memoryPressure=pressure}handle(command){let sessionId="sessionId"in command?command.sessionId:void 0;return runWithSessionAttribution({sessionId},()=>this.dispatch(command))}async dispatch(command){if(command.type==="get_protocol_info"){let capabilities=new Set(["multi_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,...this.connectionOptions?.capabilities??[]]);return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities:[...capabilities],mode:"multi",...protocolIdentity()}}}if(command.type==="list_sessions"){let rows=this.registry.list(),sessions=command.include_workers===!0?rows:rows.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="open_session")return this.openWithBarrier(command);if(command.type==="close_session")return this.close(command);if(command.type==="set_client_info"&&!command.sessionId){let connection=this.writer.currentConnection();return connection!==void 0&&(this.pendingCapabilities.set(connection,command.capabilities??[]),this.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0}}if(!controls.has(command.type)){if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);try{this.registry.getForCommand(command.sessionId,command.type);let binding=this.bindings.get(command.sessionId);if(!binding)return error(command.id,command.type,RPC_ERROR_UNKNOWN_SESSION);await binding.handle(command);return}catch(cause){return error(command.id,command.type,this.code(cause))}}}async dispose(){this.stopSweep(),await Promise.all([...this.bindings.entries()].map(async([sessionId,binding])=>{let claim=this.tryClaimClose(sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await this.finalizeClose(sessionId,binding,()=>this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId))})),this.bindings.clear()}sweepIdleSessions(){let now=this.idleNow(),idleEvictionMs=this.memoryPressure?this.idleEvictionMs/2:this.idleEvictionMs;if(Number.isFinite(idleEvictionMs))for(let{sessionId,status}of this.registry.list()){if(status!=="open")continue;let entry=this.registry.peek(sessionId);if(entry){if(entry.worker?.busy||entry.runtime?.session.isSessionBusy){entry.lastCommandAt=now;continue}now-entry.lastCommandAt>=idleEvictionMs&&this.evictIdleSession(sessionId)}}Number.isFinite(this.emptyExitMs)&&(this.registry.size===0&&(this.canExitWhenEmpty?.()??!0)?this.emptySince===void 0?this.emptySince=now:now-this.emptySince>=this.emptyExitMs&&(this.stopSweep(),this.onEmptyExit?.()):this.emptySince=void 0)}async evictIdleSession(sessionId,reason){let retained=this.registry.peek(sessionId),parkedPath=retained?.retainOnDisconnect===!0?retained.sessionPath:void 0,claim=this.tryClaimClose(sessionId,{drainAttachments:!0});if(!claim)return;let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),this.forgetSessionOwnership(sessionId),claim.finalizer?await this.finalizeClose(sessionId,binding,()=>parkedPath!==void 0&&reason===void 0?this.writer.parkSession(sessionId,parkedPath):this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},reason??"idle_evicted")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId)}forgetSessionOwnership(sessionId){for(let[connection,owned]of this.sessionsByConnection)owned.delete(sessionId),owned.size===0&&this.sessionsByConnection.delete(connection);this.widths.delete(sessionId)}stopSweep(){this.sweepTimer!==void 0&&(clearInterval(this.sweepTimer),this.sweepTimer=void 0)}openWithBarrier(command){let owner=this.writer.currentConnection();if(owner===void 0)return this.open(command);let resolveBarrier,barrier=new Promise(resolve2=>{resolveBarrier=resolve2}),opens=this.opensByConnection.get(owner)??new Set,inFlight=0;for(let pending of this.opensByConnection.values())inFlight+=pending.size;return opens.add(barrier),this.opensByConnection.set(owner,opens),command.id!==void 0&&this.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight}),this.open(command,owner).finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&this.opensByConnection.delete(owner)})}async open(command,owner){let kindError=sessionKindError(command.kind);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let opened;try{opened=await this.registry.openSession({cwd:command.cwd??this.defaults.cwd,sessionPath:command.sessionPath,permissionPreset:command.permissionPreset??this.defaults.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:this.defaults.creationModel,initialThinkingLevel:command.thinkingLevel??this.defaults.initialThinkingLevel,sessionKind:command.kind,sessionContext:command.context,...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{}},{retainOnDisconnect:command.retain_on_disconnect===!0});let openedSession=opened,entry=this.registry.getForCommand(openedSession.sessionId,"open_session");if(this.writer.setSessionKind(openedSession.sessionId,entry.kind),owner!==void 0&&(this.writer.hasRegisteredConnectionCapabilities(owner)||this.writer.setConnectionCapabilities(owner,this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]),this.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=this.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),this.sessionsByConnection.set(owner,owned)}this.bindings.has(openedSession.sessionId)||(this.bindings.set(openedSession.sessionId,await this.createBinding(openedSession.sessionId,entry,this.writer,()=>{this.close({type:"close_session",sessionId:openedSession.sessionId})},{...this.connectionOptions,capabilities:owner!==void 0?this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]:this.connectionOptions?.capabilities,sharedWidth:{getWidth:()=>{let widths=this.widths.get(openedSession.sessionId);return widths?.size?Math.min(...widths.values()):80},setWidth:(connectionId,width)=>{if(connectionId!==void 0){let widths=this.widths.get(openedSession.sessionId)??new Map;widths.set(connectionId,width),this.widths.set(openedSession.sessionId,widths)}},clearWidth:connectionId=>{let widths=this.widths.get(openedSession.sessionId);connectionId!==void 0&&widths?.delete(connectionId)},setCapabilities:(connectionId,capabilities)=>{if(connectionId!==void 0){this.writer.setConnectionCapabilities(connectionId,capabilities),this.pendingCapabilities.set(connectionId,[...capabilities]);for(let binding of this.bindings.values())binding.rerenderComponents?.()}},hasRenderedComponents:sessionId=>this.writer.hasCapableConnection(sessionId),connectionId:()=>this.writer.currentConnection(),onChange:()=>{for(let binding of this.bindings.values())binding.rerenderComponents?.()}}})),entry.worker&&(entry.worker.bindingReady=!0),entry.worker&&entry.worker.exited.then(async()=>{await this.finalizations.get(openedSession.sessionId)?.promise,this.bindings.delete(openedSession.sessionId),this.forgetSessionOwnership(openedSession.sessionId),this.writer.forgetSession(openedSession.sessionId)})),owner!==void 0&&this.releasedConnections.has(owner)&&(this.releaseOwnerAttachment(owner,openedSession.sessionId),await this.releaseOwnedSession(openedSession.sessionId));let state=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!state)throw new Error("Session state was not created");this.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened)try{await this.registry.close(opened.sessionId)}catch{}return error(command.id,"open_session",this.code(cause),this.detail(cause))}}async releaseConnection(connectionId){this.releasedConnections.add(connectionId),this.writer.clearConnectionCapabilities(connectionId);for(let sessionId of this.sessionsByConnection.get(connectionId)?.keys()??[])this.writer.detachConnectionFromSession(connectionId,sessionId);for(let widths of this.widths.values())widths.delete(connectionId);for(let binding of this.bindings.values())binding.rerenderComponents?.();let opens=this.opensByConnection.get(connectionId),owned=this.sessionsByConnection.get(connectionId);if(this.sessionsByConnection.delete(connectionId),owned===void 0){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++){let live=this.registry.peek(sessionId),retained=live?.retainOnDisconnect===!0,session=live?.state==="open"?live.runtime?.session:void 0;if(!retained&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
8
8
  `)})});continue}if(!retained&&session?.isStreaming){let released=!1,unsubscribe=session.subscribe(event=>{event.type!=="agent_settled"&&event.type!=="agent_idle"||released||(released=!0,unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred release for session ${sessionId} failed: ${String(cause)}
9
9
  `)}))});continue}await this.releaseOwnedSession(sessionId)}})),opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId)}async releaseOwnedSession(sessionId){let claim=this.tryClaimClose(sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){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(resolve2=>{resolveFinalization=resolve2}),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(resolve2=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve2()};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.openingDeadline=Date.now()+SESSION_WORKER_LIMITS.openMs,this.send=send,this.timeout=timeout}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((resolve2,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:Math.max(0,this.openingDeadline-Date.now()));this.pending.set(request,{resolve:resolve2,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(resolve2=>{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(),resolve2()})}),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}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}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");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()},worker=new SessionWorkerClient({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=>{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(resolve2=>{resolveFinalization=resolve2}),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(resolve2=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve2()};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((resolve2,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve:resolve2,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(resolve2=>{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(),resolve2()})}),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}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}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");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()},worker=new SessionWorkerClient({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=>{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 new RpcSessionRegistryError("session_closing");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(resolve2=>{entry.closeResolve=resolve2}),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(resolve2=>{timer=setTimeout(()=>{entry.state!=="closed"&&(entry.state="quarantined"),resolve2()},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 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,WINDOWS_SHUTDOWN_HARD_EXIT_MS=2e3;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}}function startHostObservers(router,writer){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)});return loopLag.start(),memory.start(),{stop:()=>{loopLag.stop(),memory.stop()}}}async function runMultiSessionHost(options){return 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={}){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,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,options,options.createBinding,{capabilities},{now:policy.now,idleEvictionMs:policy.idleEvictionMs,emptyExitMs:policy.emptyExitMs,onEmptyExit:idle.onEmptyExit,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: ${errorMessage2(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: ${errorMessage2(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,draining=!1,{router,handle}=createHostCore(options,writer,[...parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")).filter(capability=>capability!=="rendered_components"),GENERATION_HANDOFF_CAPABILITY],{onEmptyExit:()=>{shutdown(0)},canExitWhenEmpty:()=>draining||connections.size===0}),observers=startHostObservers(router,writer),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?join2(watchdogConfig.scratchDir,PUBLIC_SOCKET_IDENTITY_FILE):void 0,boundIdentity,supervisorPublicIdentity,server=createServer(socket=>{let accept=()=>{let id=`socket-${++nextConnection}`,sink=socketSink(socket);writer.registerConnection(id,sink);let detachReader=attachJsonlLineReader(socket,line=>{writer.withConnection(id,()=>handle(line)).catch(cause=>{process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage2(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: ${errorMessage2(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-EHSDTQ6I.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.js";import"./chunk-5E5TLB76.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-RLRLQRI2.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-YRN3PCTM.js";import{SettingsManager}from"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import"./chunk-P7PWCGLJ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-LF3XTYYF.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killProcessTree}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import{source_default}from"./chunk-26UBFF6N.js";import{require_proper_lockfile}from"./chunk-3P23SBT3.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-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import{__toESM}from"./chunk-VR4X5O2Z.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-E5R67F7G.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-YXQG2SUX.js";import"./chunk-EONVPHVX.js";import"./chunk-ZMFHNH6U.js";import"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.js";import"./chunk-TWGC3TBR.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-V2ZB62DG.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-DQZB4GVV.js";import{SettingsManager}from"./chunk-Z4LHCTJ6.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import"./chunk-P7PWCGLJ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-LF3XTYYF.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killProcessTree}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import{source_default}from"./chunk-26UBFF6N.js";import{require_proper_lockfile}from"./chunk-3P23SBT3.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-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import{__toESM}from"./chunk-VR4X5O2Z.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-5E5TLB76.js";import"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-HSH674C6.js";import"./chunk-HB35RBP4.js";import"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";export{runRpcMode};
2
+ import{runRpcMode}from"./chunk-TWGC3TBR.js";import"./chunk-V2ZB62DG.js";import"./chunk-DQZB4GVV.js";import"./chunk-Z4LHCTJ6.js";import"./chunk-QOBJEPJZ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-HSH674C6.js";import"./chunk-HB35RBP4.js";import"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";export{runRpcMode};
@@ -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{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-3FRTRCR6.js";import{KeybindingsManager}from"./chunk-3Q4WGKFA.js";import"./chunk-RLRLQRI2.js";import{setKeybindings}from"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-I7YUNMWH.js";import"./chunk-U7RQY7MH.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};
2
+ import{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-YXQG2SUX.js";import{KeybindingsManager}from"./chunk-ZMFHNH6U.js";import"./chunk-V2ZB62DG.js";import{setKeybindings}from"./chunk-DQZB4GVV.js";import"./chunk-Z4LHCTJ6.js";import"./chunk-QOBJEPJZ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-I7YUNMWH.js";import"./chunk-U7RQY7MH.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};